Chapter 14 Exception Handling 815 25 // get
Chapter 14 Exception Handling 815 25 // get content pane and set its layout 26 Container container = getContentPane(); 27 container.setLayout( new GridLayout( 3, 2 ) ); 28 29 // set up label and inputField1 30 container.add( 31 new JLabel( “Enter numerator “, SwingConstants.RIGHT ) ); 32 inputField1 = new JTextField( 10 ); 33 container.add( inputField1 ); 34 35 // set up label and inputField2; register listener 36 container.add( 37 new JLabel( “Enter denominator and press Enter “, 38 SwingConstants.RIGHT ) ); 39 inputField2 = new JTextField( 10 ); 40 container.add( inputField2 ); 41 inputField2.addActionListener( this ); 42 43 // set up label and outputField 44 container.add( 45 new JLabel( “RESULT “, SwingConstants.RIGHT ) ); 46 outputField = new JTextField(); 47 container.add( outputField ); 48 49 setSize( 425, 100 ); 50 setVisible( true ); 51 } 52 53 // process GUI events 54 public void actionPerformed( ActionEvent event ) 55 { 56 DecimalFormat precision3 = new DecimalFormat( “0.000″ ); 57 58 outputField.setText( “” ); // clear outputField 59 60 // read two numbers and calculate quotient 61 try { 62 number1 = Integer.parseInt( inputField1.getText() ); 63 number2 = Integer.parseInt( inputField2.getText() ); 64 65 result = quotient( number1, number2 ); 66 outputField.setText( precision3.format( result ) ); 67 } 68 69 // process improperly formatted input 70 catch ( NumberFormatException numberFormatException ) { 71 JOptionPane.showMessageDialog( this, 72 “You must enter two integers”, 73 “Invalid Number Format”, 74 JOptionPane.ERROR_MESSAGE ); 75 } 76 Fig. 14.2A simple exception-handling example with divide by zero (part 2 of 3). Fig. 14.2
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.