//IntCheck.java //howto input an int without program-terminating error //1. via a JTextField //2. via JOptionPane //try catch blocks used import java.awt.*; import java.awt.event.*; import javax.swing.*; public class IntCheck implements ActionListener { JFrame outputFrame; Container container; JLabel intLabel; JTextField intTextField; JButton interactiveButton; JLabel goodIntLabel; public static void main(String[] args) { IntCheck demoIntCheck = new IntCheck(); //create object of this class } //constructor public IntCheck() { outputFrame = new JFrame(); outputFrame.setSize(800,300); outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); container = outputFrame.getContentPane(); container.setLayout( new FlowLayout() ); intLabel = new JLabel("Enter an integer:"); container.add(intLabel); intTextField = new JTextField( "", 10 ); container.add( intTextField ); intTextField.addActionListener( this ); interactiveButton = new JButton( "use JOptionPane" ); container.add( interactiveButton ); interactiveButton.addActionListener( this ); goodIntLabel = new JLabel("integer is: "); //will include int value container.add(goodIntLabel); outputFrame.setVisible(true); } public void actionPerformed( ActionEvent event ) { int num; if ( event.getSource() == intTextField ) { //test the text in the textfield to see if it is integer try { num = Integer.parseInt( intTextField.getText() ); //happens if no parseInt error: goodIntLabel.setText("good int: " + num); //and could now use the int... } catch (NumberFormatException e) { //happens if parseInt error: goodIntLabel.setText("bad attempt: " + intTextField.getText()); } } else if ( event.getSource() == interactiveButton ) { num = getInt(); //interactively using JOptionPane get int goodIntLabel.setText("good int: " + num); //and could now use the int... } } //JOptionPane dialog box interactively input an int without runtime exception public int getInt() { String input; int num=0; //initialize to fake out compiler boolean goodInt; goodInt = false; //not gotten good int yet do { try { input = JOptionPane.showInputDialog( "Enter an integer" ); num = Integer.parseInt( input ); goodInt = true; //if get this far, is a good int } catch (NumberFormatException e) { //some message to user: //System.out.println("oops, do you really mean that?"); JOptionPane.showMessageDialog(null, "Invalid integer. Try again"); } } while (!goodInt); return num; } }