/* InClassGUI1.java CIS 160 2014-10-28 David Klick Demonstration of a GUI including a button listener. This GUI computes the average of three numbers. */ import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; 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.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class InClassGUI1 extends JFrame implements ActionListener { // Create globals so widgets can be referenced in two methods. private JLabel lblResult = new JLabel("Result"); private JTextField txt1 = new JTextField(""); private JTextField txt2 = new JTextField(""); private JTextField txt3 = new JTextField(""); // Create an object out of ourself when program starts. public static void main(String[] args) { new InClassGUI1(); } // Create thread to setup GUI when the EDT has time. public InClassGUI1() { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } // This method sets up the GUI and displays it. public void createAndShowGUI() { // Create containers. Container c = getContentPane(); JPanel pnlCenter = new JPanel(); JPanel pnlSouth = new JPanel(); // Set layout managers. c.setLayout(new BorderLayout()); pnlCenter.setLayout(new GridLayout(3, 2)); pnlSouth.setLayout(new FlowLayout()); // Create widgets. JButton btnCalc = new JButton("Calc Avg"); JLabel lbl1 = new JLabel("Score 1"); JLabel lbl2 = new JLabel("Score 2"); JLabel lbl3 = new JLabel("Score 3"); // Add listener to widget. btnCalc.addActionListener(this); // Add widgets to containers. pnlCenter.add(lbl1); pnlCenter.add(txt1); pnlCenter.add(lbl2); pnlCenter.add(txt2); pnlCenter.add(lbl3); pnlCenter.add(txt3); pnlSouth.add(lblResult); c.add(btnCalc, BorderLayout.NORTH); c.add(pnlCenter, BorderLayout.CENTER); c.add(pnlSouth, BorderLayout.SOUTH); // Set close operation and display GUI. setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setVisible(true); } // This method handles clicks on the Calc button. public void actionPerformed(ActionEvent e) { try{ // Get text from text fields and convert to double values. double n1 = Double.parseDouble(txt1.getText()); double n2 = Double.parseDouble(txt2.getText()); double n3 = Double.parseDouble(txt3.getText()); // Calculate average of three numbers from text fields. double avg = (n1 + n2 + n3) / 3.0; // Format and display the average in the result label. String result = String.format("%.2f", avg); lblResult.setText(result); } catch (NumberFormatException e2) { // Display an error message if input doesn't parse. lblResult.setText("Error"); } } }