/* GUI09.java CIS 160 David Klick 2011-09-24 Adding a button listener (event handler) */ import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class GUI09 extends JFrame { public GUI09() { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private void createAndShowGUI() { // set title, size, and close operation setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create labels JLabel lblLength = new JLabel("Length:", JLabel.RIGHT); JLabel lblWidth = new JLabel("Width:", JLabel.RIGHT); JLabel lblArea = new JLabel("Area:", JLabel.RIGHT); JLabel lblPerim = new JLabel("Perimeter:", JLabel.RIGHT); // create textboxes JTextField txtLength = new JTextField(20); JTextField txtWidth = new JTextField(20); JTextField txtArea = new JTextField(20); txtArea.setEditable(false); JTextField txtPerim = new JTextField(20); txtPerim.setEditable(false); // create buttons JButton btnCalc = new JButton("Calc"); JButton btnExit = new JButton("Exit"); // add event handlers to exit button btnExit.addActionListener(new MyExitListener()); // add components to this frame's content pane Container c = getContentPane(); c.setLayout(new GridLayout(5, 2)); // rows, columns c.add(lblLength); c.add(txtLength); c.add(lblWidth); c.add(txtWidth); c.add(lblArea); c.add(txtArea); c.add(lblPerim); c.add(txtPerim); c.add(btnCalc); c.add(btnExit); setVisible(true); } public class MyExitListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } public static void main(String[] args) { GUI09 app = new GUI09(); } }