Message Boxes

A message box can be used to announce a significant event, such as a user input error.  One place where this might occur is when the program attempts to get an input number from a numeric entry field.  If the userÕs input text cannot be converted to a number, the getNumber method displays a 0 in the field and retruns a 0.  A robust application can check for a bad number format by calling the isValidNumber method on the field. If this method returns false, the program can pop up a message box with an error message and allow the user to try again.  The messageBox method, which takes a string as an argument, can be run anywhere within the main window class. The next code segment shows the event handler from the temperature conversion program, updated to recover gracefully from number format errors.


    // Uses if/else statement to determine which button is clicked

    // Checks inputs for format errors

    public void buttonClicked(JButton buttonObj){

        double fahrenheit, celsius;

        if (buttonObj == fToCButton){

            if (! degreesFahrenheitField.isValidNumber()){

                messageBox("Error: bad number format in Fahrenheit field!");



            fahrenheit = degreesFahrenheitField.getNumber();

            celsius = (fahrenheit  - 32) * 5.0 / 9.0;

            degreesCelsiusField.setNumber (celsius);


        else {

            if (! degreesCelsiusField.isValidNumber()){

                messageBox("Error: bad number format in Celsius field!");



            celsius = degreesCelsiusField.getNumber();

            fahrenheit = celsius * 9.0 / 5.0 + 32;

            degreesFahrenheitField.setNumber (fahrenheit);





Here is a screen shot of the programÕs main window and the message box resulting from an input error (an o was typed instead of a 0 in the Fahrenheit field):



Back to tutorial Next topic: Drop-down menus