import javax.swing.JFrame; import javax.swing.JTextField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JButton; import java.awt.Color; public class MyFrame extends JFrame implements ActionListener { private JTextField operand1; private JTextField operand2; private JButton aButton; public MyFrame() { initializeWidgets(); setSize (400,300); addWidgets(); setLayout(null); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public void addWidgets() { add(operand1); add(operand2); add(aButton); } // The is listener for button events but the button event // can change the state of the container (MyFrame) because // the container is the listener of button events. public void actionPerformed(ActionEvent anEvent) { double number1 = Double.parseDouble(operand1.getText()); double number2 = Double.parseDouble(operand2.getText()); double sum = number1 + number2; String resultExpression; JButton aButton = (JButton) anEvent.getSource(); resultExpression = Double.toString(number1) + " + " + Double.toString(number2); if (sum > 0) aButton.setBackground(Color.RED); else if (sum < 0) aButton.setBackground(Color.GREEN); resultExpression = resultExpression + " = " + Double.toString(sum); this.setTitle(resultExpression); } public void initializeWidgets() { operand1 = new JTextField("0.0"); operand1.setBounds(50,50,100,20); operand2 = new JTextField("0.0"); operand2.setBounds(200,50,100,20); aButton = new JButton("Add"); aButton.setBounds(100,100,150,30); aButton.addActionListener(this); } }