import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class HelloJFrame extends JFrame implements ActionListener { private static final int ANSWER_LENGTH = 30; private JTextField ageBox = new JTextField (3); private JLabel ageLabel = new JLabel ("How old are you?"); private JTextField answer = new JTextField (ANSWER_LENGTH); private JButton doItButton = new JButton ("Go ahead!"); public static void main (String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame theFrame = new HelloJFrame ("Hello JFrame"); theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); theFrame.pack(); theFrame.setVisible (true); } private HelloJFrame (String title) { super(title); java.awt.Container contents = this.getContentPane(); contents.setLayout (new java.awt.FlowLayout()); contents.add (this.ageLabel); contents.add (this.ageBox); contents.add (this.doItButton); contents.add (this.answer); this.doItButton.addActionListener (this); } public void actionPerformed (ActionEvent whatHappened) { try { int age = Integer.parseInt (this.ageBox.getText()); if (age >= 18) { this.answer.setText ("" + age + " is old enough to vote. Congratulations!"); } else { this.answer.setText ("" + age + " is NOT old enough to vote."); } } catch (java.lang.NumberFormatException whatsWrong) { this.answer.setText ("I don't understand \"" + this.ageBox.getText() + "\"; it must be an integer."); } } }