Java swing calculator example

Create a simple calculator using Java Swing

Swing API is a set of extensible GUI Components to ease the developer’s life to create JAVA based Front End/GUI Applications. It is built on top of AWT API and acts as a replacement of AWT API since it has almost every control corresponding to AWT controls.

Following example showcases a simple calculator application.

import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator implements ActionListener < private static JTextField inputBox; Calculator()<>public static void main(String[] args) < createWindow(); >private static void createWindow() < JFrame frame = new JFrame("Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); >private static void createUI(JFrame frame) < JPanel panel = new JPanel(); Calculator calculator = new Calculator(); GridBagLayout layout = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); panel.setLayout(layout); inputBox = new JTextField(10); inputBox.setEditable(false); JButton button0 = new JButton("0");JButton button1 = new JButton("1"); JButton button2 = new JButton("2");JButton button3 = new JButton("3"); JButton button4 = new JButton("4");JButton button5 = new JButton("5"); JButton button6 = new JButton("6");JButton button7 = new JButton("7"); JButton button8 = new JButton("8");JButton button9 = new JButton("9"); JButton buttonPlus = new JButton("+");JButton buttonMinus = new JButton("-"); JButton buttonDivide = new JButton("/");JButton buttonMultiply = new JButton("x"); JButton buttonClear = new JButton("C");JButton buttonDot = new JButton("."); JButton buttonEquals = new JButton("="); button1.addActionListener(calculator);button2.addActionListener(calculator); button3.addActionListener(calculator);button4.addActionListener(calculator); button5.addActionListener(calculator);button6.addActionListener(calculator); button7.addActionListener(calculator);button8.addActionListener(calculator); button9.addActionListener(calculator);button0.addActionListener(calculator); buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator); buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator); buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator); buttonEquals.addActionListener(calculator); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc); gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc); gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc); gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc); gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc); gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc); gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc); gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc); gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc); gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc); gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc); gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc); gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc); gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc); gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc); gbc.gridwidth = 3; gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc); gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc); frame.getContentPane().add(panel, BorderLayout.CENTER); >public void actionPerformed(ActionEvent e) < String command = e.getActionCommand(); if (command.charAt(0) == 'C') < inputBox.setText(""); >else if (command.charAt(0) == '=') < inputBox.setText(evaluate(inputBox.getText())); >else < inputBox.setText(inputBox.getText() + command); >> public static String evaluate(String expression) < char[] arr = expression.toCharArray(); String operand1 = "";String operand2 = "";String operator = ""; double result = 0; for (int i = 0; i < arr.length; i++) < if (arr[i] >= '0' && arr[i] else < operand2 += arr[i]; >> if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') < operator += arr[i]; >> if (operator.equals("+")) result = (Double.parseDouble(operand1) + Double.parseDouble(operand2)); else if (operator.equals("-")) result = (Double.parseDouble(operand1) - Double.parseDouble(operand2)); else if (operator.equals("/")) result = (Double.parseDouble(operand1) / Double.parseDouble(operand2)); else result = (Double.parseDouble(operand1) * Double.parseDouble(operand2)); return operand1 + operator + operand2 + "=" +result; > >

Output

karthikeya Boyini

I love programming (: That’s all I know

Читайте также:  Open zip files in php

Источник

Calculator Program in Java Swing/JFrame with Source Code

Hello friends today we will learn how we can create a Simple Calculator Program in Java Using Swing with Source Code. This is going to be our first application using swing programming. This is going to be a simple Java GUI calculator project which will perform basic arithmetic operations like addition, subtraction, multiplication, division etc. It can also be used for finding the square, square root and reciprocal of any number.

Before starting this tutorial, I assume that you have the basic concept of swing components and also you should have the idea of JButton Click Event means what should be the response of a button when we click on it. If you already know about Basic Components of Java Swing, then it’s not going to be very difficult for you.

I will use NetBeans IDE(integrated development environment) for the coding part of my calculator program. You can use any IDE like IntelliJ IDEA, Eclipse or you can just use notepad++ to code your program. It doesn’t matter whatever IDE or editor you will use the programming logic will be the same.

So friends, lets get started with our tutorial Simple Calculator Program in Java Using Swing or can say simple calculator program in Java using JFrame/frame step by step.

Watch Video Tutorial

Simple Calculator Program in Java Using Swing

Creating a New Calculator Project in NetBeans

First of all, we need to create a new project in Netbeans. For this, follow these steps.

  • Open the NetBeans IDE and then click on the File menu and then select New Project.

Simple Calculator Program in Java Using Swing

  • After that, a window will be opened. From there, select Java in categories and Java Application in projects and then click on the Next Button.

Simple Calculator Program in Java Using Swing

  • After you click on the Next button again a new window will be opened and there you have to give the name of the Project (Calculator in this Example) and also uncheck the create Main class option.
  • Then click on the Finish Button.

Simple Calculator Program in Java Using Swing

  • Now expand your project using the + icon and right-click on the source packages.
  • Then select new>>Java class.

Simple Calculator Program in Java Using Swing

  • A new window will be opened where you have to give the name of your Java class (Calculator in this Example).
  • Then click on the Finish button.

Creating Display Window for Calculator

Now we will create a display window or frame for our calculator.

  • Create an object of the JFrame class and set some of its properties like its title, visibility, background color, layout property etc. using the method of the JFrame class.

Источник

Java Calculator using Swing Example

Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way. So lets see how to create a calculator in java.

1. Introduction

  • A single API is to be sufficient to support multiple look and feel.
  • API is to model driven so that highest level API is not required to have the data.
  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.

2. JAVA Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton , JTextField , JTextArea , JRadioButton , JCheckbox , JMenu , JColorChooser etc.

2.1 MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • A Model represents component’s data.
  • View represents visual representation of the component’s data.
  • Controller takes the input from the user on the view and reflects the changes in Component’s data.
  • Swing component have Model as a separate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Every user interface considers the following three main aspects:

  • UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
  • Behavior: These are events which occur when the user interacts with UI elements.

2.2 Swing Features

  • Light Weight – Swing component are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
  • Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
  • Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
  • Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.

2.3 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

2.4 Class and description

  • Component: A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation.
  • Container: A Container is a component that can contain other SWING components.
  • JComponent: A JComponent is a base class for all swing UI components. In order to use a swing component that inherits from JComponent, component must be in a containment hierarchy whose root is a top-level Swing container.

3. Swing Java Calculator Example

This tutorial is about how to make a calculator in Java. Below I have shared the simple calculator program in java using swing. It is a simple calculator in Java which can perform basic arithmetic operations.

import java.awt.*; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JTextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Calculator extends JFrame implements ActionListener < JButton addButton,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,BACKSPACE,CE,C,MC,div,sqrt,MR,mul,per,MS,sub,prop,M,pm,dot,eq; JTextField mainTextField, memoryTextField; double result=0,memory=0,n1=0; //Mark the first number for easy calculation int first=1; //First number for percentage calculation double num; //Flag for appending digits or starting a new number /*1->Appending a digit to the existing number 2->Taking a new number as input*/ int opt=2; //Flag to mark binary operation for '=' button /*0->No Operation 1->Addtion 2->Subtraction 3->Division 4->Multiplication*/ int oper1=0,oper2=0; Calculator() < setTitle("Calculator"); setSize(300,300); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); initComponents(); >//Function for creating User Interface void initComponents() < mainTextField = new JTextField(32); mainTextField.setText("0"); add(mainTextField,BorderLayout.NORTH); mainTextField.setHorizontalAlignment(JTextField.RIGHT); JPanel panel7 = new JPanel(); //Panel 1 JPanel panel1 = new JPanel(); memoryTextField = new JTextField(5); memoryTextField.setText(" "); panel1.add(memoryTextField); MC = new JButton("MC"); MC.setForeground(Color.BLACK); panel1.add(MC); MR = new JButton("MR"); MR.setForeground(Color.BLACK); panel1.add(MR); M = new JButton("M+"); M.setForeground(Color.BLACK); panel1.add(M); MS = new JButton("MS"); MS.setForeground(Color.BLACK); panel1.add(MS); panel7.add(panel1); //Panel 2 JPanel panel2 = new JPanel(); CE= new JButton("CE"); CE.setForeground(Color.BLACK); panel2.add(CE); C = new JButton("C"); panel2.add(C); C.setForeground(Color.BLACK); BACKSPACE = new JButton("BACKSPACE"); BACKSPACE.setForeground(Color.BLACK); panel2.add(BACKSPACE); sqrt = new JButton("sqrt"); sqrt.setForeground(Color.BLUE); panel2.add(sqrt); panel7.add(panel2); //Panel 3 JPanel panel3 = new JPanel(); b7 = new JButton("7"); b7.setForeground(Color.BLUE); panel3.add(b7); b8= new JButton("8"); b8.setForeground(Color.BLUE); panel3.add(b8); b9 = new JButton("9"); b9.setForeground(Color.BLUE); panel3.add(b9); div = new JButton("/"); div.setForeground(Color.BLACK); panel3.add(div); per = new JButton("%"); per.setForeground(Color.BLUE); panel3.add(per); panel7.add(panel3); //Panel 4 JPanel panel4 = new JPanel(); b4= new JButton("4"); b4.setForeground(Color.BLUE); panel4.add(b4); b5 = new JButton("5"); b5.setForeground(Color.BLUE); panel4.add(b5); b6= new JButton("6"); b6.setForeground(Color.BLUE); panel4.add(b6); mul = new JButton("*"); mul.setForeground(Color.BLACK); panel4.add(mul); prop = new JButton("1/x"); prop.setForeground(Color.BLUE); panel4.add(prop); panel7.add(panel4); //Panel 5 JPanel panel5 = new JPanel(); b1 = new JButton("1"); b1.setForeground(Color.BLUE); panel5.add(b1); b2= new JButton("2"); b2.setForeground(Color.BLUE); panel5.add(b2); b3 = new JButton("3"); b3.setForeground(Color.BLUE); panel5.add(b3); sub = new JButton("-"); sub.setForeground(Color.BLACK); panel5.add(sub); pm= new JButton("+/-"); pm.setForeground(Color.BLUE); panel5.add(pm); panel7.add(panel5); //Panel 6 JPanel panel6 = new JPanel(); b0= new JButton("0"); b0.setForeground(Color.BLUE); panel6.add(b0); dot= new JButton("."); dot.setForeground(Color.BLUE); panel6.add(dot); addButton = new JButton("+"); addButton.setForeground(Color.BLACK); panel6.add(addButton); eq = new JButton("="); eq.setForeground(Color.BLACK); panel6.add(eq); panel7.add(panel6); panel1.setBackground(Color.blue); panel7.setBackground(Color.LIGHT_GRAY); //Adding all individual panels to main panel7 add(panel7,BorderLayout.CENTER); //Add events addButton.addActionListener(this); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); BACKSPACE.addActionListener(this); CE.addActionListener(this); C.addActionListener(this); MC.addActionListener(this); div.addActionListener(this); sqrt.addActionListener(this); MR.addActionListener(this); mul.addActionListener(this); per.addActionListener(this); MS.addActionListener(this); sub.addActionListener(this); prop.addActionListener(this); M.addActionListener(this); pm.addActionListener(this); dot.addActionListener(this); eq.addActionListener(this); per.addActionListener(this); >//Method when ActionListener calls its corresponding routine public void actionPerformed(ActionEvent evt) < String str; //Action Corresponding to + button if(evt.getSource()== addButton) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=1; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=1; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to * button if(evt.getSource()==mul) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=4; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=4; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to / button if(evt.getSource()==div) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=3; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=3; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to - button else if(evt.getSource()==sub) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=2; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=2; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to = button else if(evt.getSource()==eq) < double n1=Double.parseDouble(mainTextField.getText()); if(oper1==1) result=result+n1; else if(oper1==2) result=result-n1; else if(oper1==3) result=result/n1; else if(oper1==4) result=result*n1; else result=Double.parseDouble(mainTextField.getText()); num=result; str=String.valueOf(result); mainTextField.setText(str); >//Action Corresponding to MS button else if(evt.getSource()==MS) < memory=Double.parseDouble(mainTextField.getText()); str=String.valueOf("M"); memoryTextField.setText(str); >//Action Corresponding to M button else if(evt.getSource()==M) < memory=memory+Double.parseDouble(mainTextField.getText()); >//Action Corresponding to MC button else if(evt.getSource()==MC) < memory=0; mainTextField.setText("0"); memoryTextField.setText(" "); >//Action Corresponding to MR button else if(evt.getSource()==MR) < str=String.valueOf(memory); mainTextField.setText(str); >//Action Corresponding to +/- button else if(evt.getSource()==pm) < double n1=Double.parseDouble(mainTextField.getText()); n1=-n1; str=String.valueOf(n1); mainTextField.setText(str); >//Action Corresponding to 0 button else if(evt.getSource()==b0) < if(opt==1) str=String.valueOf(mainTextField.getText())+0; else str=String.valueOf(" ")+0; opt=1; mainTextField.setText(str); >//Action Corresponding to 1 button else if(evt.getSource()==b1) < if(opt==1) str=String.valueOf(mainTextField.getText())+1; else str=String.valueOf(" ")+1; opt=1; mainTextField.setText(str); >//Action Corresponding to 2 button else if(evt.getSource()==b2) < if(opt==1) str=String.valueOf(mainTextField.getText())+2; else str=String.valueOf(" ")+2; opt=1; mainTextField.setText(str); >//Action Corresponding to 3 button else if(evt.getSource()==b3) < if(opt==1) str=String.valueOf(mainTextField.getText())+3; else str=String.valueOf(" ")+3; opt=1; mainTextField.setText(str); >//Action Corresponding to 4 button else if(evt.getSource()==b4) < if(opt==1) str=String.valueOf(mainTextField.getText())+4; else str=String.valueOf(" ")+4; opt=1; mainTextField.setText(str); >//Action Corresponding to 5 button else if(evt.getSource()==b5) < if(opt==1) str=String.valueOf(mainTextField.getText())+5; else str=String.valueOf(" ")+5; opt=1; mainTextField.setText(str); >//Action Corresponding to 6 button else if(evt.getSource()==b6) < if(opt==1) str=String.valueOf(mainTextField.getText())+6; else str=String.valueOf(" ")+6; opt=1; mainTextField.setText(str); >//Action Corresponding to 7 button else if(evt.getSource()==b7) < if(opt==1) str=String.valueOf(mainTextField.getText())+7; else str=String.valueOf(" ")+7; opt=1; mainTextField.setText(str); >//Action Corresponding to 8 button else if(evt.getSource()==b8) < if(opt==1) str=String.valueOf(mainTextField.getText())+8; else str=String.valueOf(" ")+8; opt=1; mainTextField.setText(str); >//Action Corresponding to 9 button else if(evt.getSource()==b9) < if(opt==1) str=String.valueOf(mainTextField.getText())+9; else str=String.valueOf(" ")+9; opt=1; mainTextField.setText(str); >//Action Corresponding to BACKSPACE button else if(evt.getSource()==BACKSPACE) < int len; str= mainTextField.getText(); len=str.length(); if(len>=1) str=str.substring(0,len-1); mainTextField.setText(str); > //Action Corresponding to CE button else if(evt.getSource()==CE) < result=0; first=1; opt=2; str=String.valueOf('0'); mainTextField.setText(str); >//Action Corresponding to C button else if(evt.getSource()==C) < result=0; memory=0; first=1; opt=2; mainTextField.setText("0"); memoryTextField.setText(" "); >//Action Corresponding to . button else if(evt.getSource()==dot) < str=String.valueOf(mainTextField.getText())+"."; mainTextField.setText(str); >//Action Corresponding to 1/x button else if(evt.getSource()==prop) < double n1=Double.parseDouble(mainTextField.getText()); n1=1/n1; str=String.valueOf(n1); mainTextField.setText(str); >//Action Corresponding to sqrt button else if(evt.getSource()==sqrt) < double n1=Double.parseDouble(mainTextField.getText()); n1=Math.sqrt(n1); str=String.valueOf(n1); mainTextField.setText(str); >//Action Corresponding to % button else if(evt.getSource()==per) < double n1=Double.parseDouble(mainTextField.getText()); n1=(n1*num)/100; str=String.valueOf(n1); mainTextField.setText(str); >> //Add called according to previous operator void add1() < if(first==0) result=num=result+n1; String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) < oper1=oper2; oper2=0; >first=0; > //Sub called according to previous operator void sub() < if(first==0) result=num=result-n1; String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) oper1=oper2; first=0; >//Div called according to previous operator void div() < if(first==0) < if(n1==0) mainTextField.setText("Cannot divide by zero"); else result=num=result/n1; >String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) oper1=oper2; first=0; > //Mul called according to previous operator void mul() < if(first==0) result=num=result*n1; String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) oper1=oper2; first=0; >public static void main(String args[]) < Calculator obj = new Calculator(); obj.setVisible(true); >>

3.1 Output

Output of code will be like the one below.

Java Calculator - Calculator result

3.2 Different keys usage:

  • MC = Memory Clear sets the memory to 0
  • MR = Memory Recall uses the number in memory
  • MS = Memory Store puts the number on the display into the memory
  • M+ = Memory Add takes the number on the display, adds it to the memory, and puts the result into memory
  • mainTextField for integer calculation
  • memoryTextField for marking memory operations.

Method of calculating in calculator has been kept simple as Standard Microsoft Calculators.

Event Handling has been used where a source generates an event and a listener is notified when an event occurs say when a button is pressed using a mouse.

4. Download the Source Code

This was an example of java calculator example.

Download
You can download the full source code of this example here: Java Calculator using Swing Example

Last updated on Sept. 29, 2019

Источник

Оцените статью