import java.awt.*; // for layout managers import java.awt.event.*; // for ActionListener/ActionEvent import javax.swing.*; // JPanel, JFrame public class Ch16_4 // create a simple GUI calculator with JButtons, JLabels and JTextFields { public static void main(String[] args) { JFrame f=new JFrame("calculator"); f.setSize(550,125); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); CalculatorPanel cp=new CalculatorPanel(); f.add(cp); f.setVisible(true); } public static class CalculatorPanel extends JPanel implements ActionListener // for JButtons { private JTextField f1, f2, f3; // f1 and f2 will be for input, f3 for output (could be a JLabel) private JButton add, sub, mul, div; // our JButtons to do the 4 arithmetic operations for the calculator public CalculatorPanel() { add=new JButton("Add"); // create the JButtons sub=new JButton("Subtract"); mul=new JButton("Multiply"); div=new JButton("Divide"); add.addActionListener(this); // add this as their ActionListeners sub.addActionListener(this); mul.addActionListener(this); div.addActionListener(this); JLabel lab1=new JLabel("Number 1"); // create the 3 JLabels for each of the JTextFields JLabel lab2=new JLabel("Number 2"); JLabel lab3=new JLabel("Result"); f1=new JTextField("",10); // create the 3 JTextFields, all initially blank f2=new JTextField("",10); f3=new JTextField("",10); f3.setEditable(false); // f3 will be used for output only so is not editable (could be a JLabel) JPanel p1=new JPanel(); // create a JPanel for the JLabels and JTextFields p1.add(lab1); p1.add(f1); p1.add(lab2); p1.add(f2); p1.add(lab3); p1.add(f3); JPanel p2=new JPanel(); // create a JPanel for the 4 JButtons p2.add(add); p2.add(sub); p2.add(mul); p2.add(div); JPanel p3=new JPanel(new GridLayout(2,1)); // add the two JPanels, one per row p3.add(p1); p3.add(p2); add(p3); // add the last JPanel to this } public void actionPerformed(ActionEvent e) // upon a JButton press { double num1, num2, result; num1=Double.parseDouble(f1.getText()); // get the two input numbers as doubles num2=Double.parseDouble(f2.getText()); if(e.getSource()==add) // perform the arithmetic operation based on the JButton pressed, storing result in result result=num1+num2; else if(e.getSource()==sub) result=num1-num2; else if(e.getSource()==mul) result=num1*num2; else result=num1/num2; f3.setText(""+result); // display the result } } }