// TEST CODES FOR CATCHING EXCEPTION (FRAME VERSION) /* A simple applet that accepts a number and prints it at System.out. If no input is given, a JOption message is displayed. If the entry is non-numeric, a catch block catches the error and causes another JOption message to be displayed. */ /* To test the codes, compile this file using the command javac ExJFrame.java and run it using the command java ExJFrame. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ExJFrame extends JFrame implements ActionListener { JPanel panel; JLabel labQty; JTextField txtQty; JButton btnOk; GridBagLayout gbl; GridBagConstraints gbc; public ExJFrame() // Buid the panel and add to frame { panel= new JPanel(); labQty = new JLabel("Qty"); txtQty = new JTextField(5); btnOk = new JButton("OK"); gbl = new GridBagLayout(); gbc = new GridBagConstraints(); panel.setLayout(gbl); getContentPane().add(panel); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridx = 0; gbc.gridy = 0; gbl.setConstraints(labQty, gbc); panel.add(labQty); gbc.gridx = 1; gbc.gridy = 0; gbl.setConstraints(txtQty, gbc); panel.add(txtQty); gbc.gridx = 1; gbc.gridy = 1; gbl.setConstraints(btnOk, gbc); panel.add(btnOk); btnOk.addActionListener(this); } public void checkQty() // Check what value we got { int num; String tmp = txtQty.getText(); if(tmp.length() == 0) // Is Qty empty? { JOptionPane.showMessageDialog( null, "Qty should not be empty.", "Opps", JOptionPane.ERROR_MESSAGE ); } else { try { num = Integer.parseInt(tmp); System.out.println("\nQty is " + num); } catch(NumberFormatException x) { JOptionPane.showMessageDialog( null, "Qty should be numeric.", "Opps", JOptionPane.ERROR_MESSAGE ); } } } public void actionPerformed(ActionEvent e) // OK button listener { if(e.getSource() == btnOk) { checkQty(); } } public static void main(String args[]) { ExJFrame ef = new ExJFrame(); ef.setSize( 200, 200 ); ef.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) // Exit on Close { System.exit(0); } }); ef.setVisible( true ); } } /* Modify the code so that a message dialog containing the message Command Successful is displayed if the user entered integer numbers in the Quantity field. */