import javax.swing.*; import java.awt.*; import java.awt.event.*; // same structure and functionality as Calculator3, but using Swing class Calculator4 { public static void main(String[] args) { SimpleCalculator4 calculator = new SimpleCalculator4(); } // main } // Calculator4 // --- cut here into separate files --- class SimpleCalculator4 extends JFrame implements ActionListener{ private JPanel[] p = new JPanel[3]; private JButton[] buttons = new JButton[5]; private JTextField opAField = new JTextField(10); private JTextField opBField = new JTextField(10); private JTextField resultField = new JTextField(10); public SimpleCalculator4() { getContentPane().setLayout(new GridLayout(1,3)); // swing adaption ! p[0] = new JPanel(new GridLayout(6,1)); // operands/result fields p[1] = new JPanel(); // empty panel p[2] = new JPanel(new GridLayout(5,1)); // operation buttons p[0].add(new JLabel("operand A")); // preparing left column p[0].add(opAField); p[0].add(new JLabel("operand b")); p[0].add(opBField); p[0].add(new JLabel("result")); p[0].add(resultField); buttons[0] = new JButton("add"); // preparing right column buttons[1] = new JButton("sub"); buttons[2] = new JButton("mul"); buttons[3] = new JButton("int div"); buttons[4] = new JButton("real div"); buttons[0].addActionListener(this); buttons[1].addActionListener(this); buttons[2].addActionListener(this); buttons[3].addActionListener(this); buttons[4].addActionListener(this); for(int i=0;i<5;i++) { p[2].add(buttons[i]); } for(int i=0;i<3;i++) { // assigning the panels to the frame getContentPane().add(p[i]); // swing adaption ! } addWindowListener(new WindowAdapter() { // register for window closing public void windowClosing(WindowEvent e) { System.exit(0); } }); setTitle(" My Simple Calculator, V4 in Swing"); setSize(300,200); setVisible(true); // show(); deprecated } // SimpleCalculator4() public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); int a, b; double db; if (command == "add") { a = Integer.parseInt(opAField.getText()); b = Integer.parseInt(opBField.getText()); resultField.setText((a+b)+" "); } else if (command == "sub") { a = Integer.parseInt(opAField.getText()); b = Integer.parseInt(opBField.getText()); resultField.setText((a-b)+" "); } else if (command == "mul") { a = Integer.parseInt(opAField.getText()); b = Integer.parseInt(opBField.getText()); resultField.setText((a*b)+" "); } else if (command == "int div") { a = Integer.parseInt(opAField.getText()); b = Integer.parseInt(opBField.getText()); resultField.setText((a/b)+" "); } else if (command == "real div") { a = Integer.parseInt(opAField.getText()); db = Integer.parseInt(opBField.getText()); resultField.setText((a/db)+" "); } // if } // actionPerformed } // class SimpleCalculator4