/* GUI10.java CIS 160 David Klick 2011-09-24 Adding a listener to the calc button */ 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 GUI10 extends JFrame { // these must be visible beyond the constructor JTextField txtLength, txtWidth, txtArea, txtPerim; public GUI10() { 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 txtLength = new JTextField(20); txtWidth = new JTextField(20); txtArea = new JTextField(20); txtArea.setEditable(false); 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 btnCalc.addActionListener(new MyCalcListener()); 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 MyCalcListener implements ActionListener { public void actionPerformed(ActionEvent e) { // get length and width from textboxes String strLength = txtLength.getText(); double length = Double.parseDouble(strLength); String strWidth = txtWidth.getText(); double width = Double.parseDouble(strWidth); // calculate area and perimeter double area = length * width; double perimeter = 2 * (length + width); // display area and perimeter txtArea.setText(String.format("%3.1f", area)); txtPerim.setText(String.format("%3.1f", perimeter)); } } public class MyExitListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } public static void main(String[] args) { GUI10 app = new GUI10(); } }