Write an application that simulates a calculator, using panel and grid layout, adding a text box, 10 number buttons (0~9), 4 addition, subtraction, multiplication and division buttons, an equal sign button, a clear button, and a square root button. button, a backspace button, requires the calculation formula and results to be displayed in the text box, and the effect is as shown in the figure below.
Java simple calculator code:
import javax.swing.*; import javax.swing.JTextField; import java.awt.*; import java.awt.event.*; import java.lang.*; import java.awt.Color; public class Ex5_2 extends JFrame implements ActionListener { private JPanel p1 = new JPanel(); //Create panel private JPanel p2 = new JPanel(); private JTextField t1; //Text box 1 is used to display input information private JTextField t2; //Text box 2 is used to display result information private JLabel label; //Label information StringBuffer str; //The string displayed on the display screen double x,y ; //x and y are both operands int z; //Z represents which operator was clicked. 0 represents "+", 1 represents "-", 2 represents "*", 3 represents "/" private JButton b[] = new JButton[12]; //Create an array with 12 buttons private JButton b1,b2,b3,b4,b5,b6,b7,b8; //Arithmetic function button public Ex5_2() { super("Simple Calculator" ); //Window name Container c = getContentPane(); //Create content panel object t1 = new JTextField(30); t1.setEditable(false); //Can only be displayed, cannot be edited t2 = new JTextField(30); t2.setEditable(false); //Can only be displayed, cannot be edited label = new JLabel("Welcome to Xiaowu Edition Calculator ^_^o~ Work hard! "); label.setForeground(Color.blue); //Create an empty string buffer str=new StringBuffer(); p2.add(label); //Add a label to the panel p2.add(t2); //Add a text box to the panel p2.add(t1); //Add a text box to the panel p2.setLayout(new GridLayout(4,1)); //Put The panel layout is 4 rows and 1 column for(int i=0;i<10;i++) //Set labels for buttons 0~9 in the array and register listeners { String s=""+i; b [i]= new JButton(s); b[i].addActionListener(this); } //Instantiate each button b[10]= new JButton("-/+"); b[11]= new JButton("."); b1= new JButton("/"); b2= new JButton("Back"); b3= new JButton("*"); b4= new JButton("C"); b5= new JButton("+"); b6= new JButton("Sqrt"); b7= new JButton("-"); b8= new JButton("="); //Set the button foreground color for(int i=0; i<12;i++) { b[i].setForeground(Color.blue); } b1.setForeground(Color.red); b3.setForeground(Color.red); b5.setForeground(Color.red); b7.setForeground(Color.red); b2.setForeground(Color.blue); b4.setForeground(Color.blue); b6.setForeground(Color.red); b8.setForeground(Color .blue); //Add to panel p1.add(b[7]); p1.add(b[8]); p1.add(b[9]); p1.add(b1); p1.add(b2); p1.add(b[4]); p1.add(b[5]); p1.add(b[ 6]); p1.add(b3); p1.add(b4); p1.add(b[1]); p1.add(b[2]); p1.add(b[3]); p1.add(b5); p1.add(b6); p1.add(b[0]); p1.add(b[10]); p1.add(b[11]);p1.add(b7) ;p1.add(b8); p1.setLayout(new GridLayout(4,5,5,5)); //Register listener b[10].addActionListener(this); b[11].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); //Add the panel to the content panel c.add(p2); c.add(p1); c.setLayout(new FlowLayout()); //Set to sequential layout setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set the window to close Action setVisible(true); //Set to visible setResizable(false); //Prohibit adjusting frame size setSize(400,300); //Set window size} //The main method implements creating a window public static void main(String[] args) { Ex5_2 f = new Ex5_2(); } //Button event processing public void actionPerformed(ActionEvent e) { try { if(e.getSource( )==b4) //Select "C" to clear { t1.setText("0"); //Clear the text box t1.setHorizontalAlignment(JTextField.RIGHT); //Align the text to the right str.setLength(0); //Clear the string buffer to prepare to receive new input operands} else if(e.getSource ()==b[10])//Click "+/-" to select whether the input operand is a positive or negative number{ x=Double.parseDouble(t1.getText().trim());//The trim function is to remove spaces in the string t1.setText(""+(-x)); t1.setHorizontalAlignment(JTextField.RIGHT) ; } else if (e.getSource()==b5)//Click the plus button to get the value of x and z and clear the value of y{ x=Double.parseDouble(t1.getText().trim()); str.setLength(0); y=0d; z=0; } else if(e.getSource()==b7)//Click to reduce Button gets the value of x and z and clears the value of y { x=Double.parseDouble(t1.getText().trim()); str.setLength(0); y=0d; z=1; } else if(e.getSource()==b3)//Click the multiplication button to get the value of x and z and clear the value of y{ x =Double.parseDouble(t1.getText().trim()); str.setLength(0); y=0d; z=2; } else if(e.getSource()==b1)//Click the division button to get the value of x and z and clear the value of y{ x=Double.parseDouble(t1.getText().trim()); str .setLength(0); y=0d; z=3; } else if(e.getSource()==b8)//Click the equal sign button to output the calculation result { str.setLength(0); switch(z) { case 0: t1.setText(""+(x+y)); t1.setHorizontalAlignment(JTextField.RIGHT);break; case 1: t1.setText(""+(xy)); t1. setHorizontalAlignment(JTextField.RIGHT);break; case 2: t1.setText(""+(x*y)); t1.setHorizontalAlignment(JTextField.RIGHT);break; case 3: t1.setText(""+(x/y)); t1.setHorizontalAlignment(JTextField.RIGHT) ;break; } } else if(e.getSource()==b[11])//Click the "." button to enter the decimal { if(t1.getText().trim().indexOf('.')!=-1)// Determine whether the string already contains a decimal point { } else //If there is no decimal point { if(t1.getText().trim().equals("0"))//If it is initially displayed as 0 { t1.setText(str.append(e.getActionCommand()).toString()); t1.setHorizontalAlignment(JTextField.RIGHT); } else if(t1.getText().trim().equals(""))/ /If initially displayed as empty, do nothing {} else { t1.setText(str.append(e.getActionCommand()).toString()); t1.setHorizontalAlignment(JTextField.RIGHT); } } y=0d; } else if(e.getSource()==b6) // Find the square root { x=Double.parseDouble(t1.getText().trim()); if(x<0) { t1.setText("Number format exception"); t1.setHorizontalAlignment(JTextField.RIGHT); } else { t1.setText(""+Math.sqrt(x)); t1.setHorizontalAlignment(JTextField.RIGHT); } str .setLength(0); y=0d; } else { if(e.getSource()==b[0])//If the number key "0" is selected { if(t1.getText().trim().equals("0"))//If it is displayed If the screen display is zero, no operation is performed {} else t1.setText(str.append(e.getActionCommand()).toString()); t1.setHorizontalAlignment(JTextField.RIGHT); y=Double.parseDouble(t1.getText().trim()); } else if (e.getSource()==b2) //The back key is selected { if(! t1.getText().trim().equals("0"))//If the display shows not zero{ if(str.length()!=1) { t1.setText(str.delete(str.length()-1,str.length()).toString());//A string out-of-bounds exception may be thrown t1.setHorizontalAlignment(JTextField.RIGHT); } else { t1.setText("0"); t1.setHorizontalAlignment(JTextField.RIGHT); str.setLength(0); } } y=Double.parseDouble(t1.getText().trim()); } else { t1.setText(str.append(e.getActionCommand()).toString()); t1.setHorizontalAlignment(JTextField.RIGHT) ; y=Double.parseDouble(t1.getText().trim()); } } } catch(NumberFormatException e1){ t1.setText("Number format exception"); t1.setHorizontalAlignment(JTextField.RIGHT); } catch(StringIndexOutOfBoundsException e1){t1.setText("String index out of bounds"); t1.setHorizontalAlignment(JTextField.RIGHT);} } }Operation rendering:
This completes the programming of a simple Java calculator. I hope this article can inspire everyone to write calculators. This is just a simple calculator, and you can continue to use it to improve the functions of the calculator.