Skip to main content
Engineering LibreTexts

10.6: From the Java Library- javax.swing.JOptionPane

  • Page ID
    15124
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    [pg-sec-dialogs]

    is a window that can be opened by a program to communicate in some way with the user. Dialog boxes come in many varieties and have many uses in a GUI environment. You’ve undoubtedly encountered them when using your own computer.

    For example, a file dialog is opened whenever you want to open or save a file. It provides an interface that lets you name the file and helps you search through the computer’s directory structure to find a file.

    A warning dialog or error dialog is opened whenever a program needs to notify or warn you that some kind of error occurred. It usually presents an error message and an OK button that you click to dismiss the dialog.

    Dialogs are easy to create and use in Java. The Swing component set provides several different kinds of basic dialogs that can be incorporated into your program with one or two lines of code. For example, the IntFieldTester class makes use of a simple message dialog to report an input error to the user. This dialog was created by the following code segment in the program (see Figure [fig-intbound]):

    catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(this,
        "The input must be an integer.  Please reenter.");
    }

    This method call displays the window shown in Figure [fig-errmsg]. It contains the error message and an OK button that is used to close the window. The showMessageDialog() method is a static method of the javax.swing.JOptionPane class. This class provides a collection of similar methods for creating and displaying basic dialog boxes.

    A dialog differs from other kinds of top-level windows—such as JApplet and JFrame—in that it is associated with another window (Fig. 1024). The first parameter in this version of the showMessageDialog() method is a reference to the dialog’s parent window. The second parameter is a String representing the message.

    The basic message dialog used in this example is known as a modal dialog. This means that once it’s been displayed, you can’t do anything else until you click the OK button and dismiss the dialog. It’s also possible to create nonmodal dialogs. These can stay around on the screen while you move on to other tasks.

    Note that the dialog box also contains an icon that symbolizes the purpose of the message (Fig. [fig-errmsg2]). The icon

    is representative of the dialog’s message type. Among the basic types available in JOptionPane are the following:

    JOptionPane.PLAIN_MESSAGE
    JOptionPane.INFORMATIONAL_MESSAGE     // Default
    JOptionPane.WARNING_MESSAGE
    JOptionPane.QUESTION_MESSAGE
    JOptionPane.ERROR_MESSAGE

    To set the dialog to anything other than the default (informational) type, you can use the following version of showMessageDialog():

    showMessageDialog(Component comp, Object message, 
                      String title, int msgType);

    The first parameter is a reference to the parent window. The second is the message string. The third is a string used as the dialog window’s title, and the fourth is one of the five dialog types. For example, we can change our dialog to an error dialog with the following statement:

    catch (IntOutOfRangeException e) {
        JOptionPane.showMessageDialog(this,
                e.getMessage(),
                "Error dialog",
                JOptionPane.ERROR_MESSAGE);
    }

    This would produce the dialog shown in Figure [fig-errmsg2].

    The other kinds of basic dialogs provided by the JOptionPane class are listed in Table 10.4. All of the dialogs listed there can be created with a line or two of code. In addition to these, it’s also possible to create sophisticated dialogs that can be as customized as any other GUI interface you can build in Java.

    ll
    Dialog&Description

    Message Dialog&Presents a simple error or informational message Confirm Dialog&Prompts the user to confirm a particular action Option Dialog&Lets the user choose from some options Input Dialog&Prompts and inputs a string

    In this chapter, you have learned how to handle exceptional conditions that occur in programs. You now know that Java has a default exception handler that can take of many situations, and you also understand that proper program design using Java excpetion-handling elements helps deal with many other situations. This chapter continues the emphasis on good program design for creating useful, stable programs.

    catch block

    catch an exception

    checked exception

    dialog box

    dynamic scope

    error dialog

    exception

    exception handling

    finally block

    method call stack

    method stack trace

    modal dialog

    static scope

    throw an exception

    try block

    unchecked exception

    The try/catch/finally statement has the following syntax:

    try {
        // Block of statements
        // At least one of which may throw an exception
    
        if ( * Some condition obtains */ )
            throw new ExceptionName();
    } catch (ExceptionName ParameterName) {
        // Block of statements to be executed
        // If the ExceptionName exception is thrown in try
    }
    ..
    } catch (ExceptionName2 ParameterName) {
        // Block of statements to be executed
        // If the ExceptionName2 exception is thrown in try
    } finally {
        // Optional block of statements that is executed
        // Whether an exception is thrown or not
    }

    The try block is meant to include a statement or statements that might throw an exception. The catch blocks—there can be one or more—are meant to handle exceptions that are thrown in the try block. A catch block will handle any exception that matches its parameter class, including subclasses of that class. The finally block is optional. It will be executed whether an exception is thrown or not. If an exception is thrown in the try block, the try block is exited permanently.

    The throw statement inside the try block is there to illustrate how throw can be used. You will usually not see a throw statement in a try block, because most throws are done from within Java library methods, which are called from a try block.

    In Java, when an error or exceptional condition occurs, you throw an Exception, which is caught by special code known as an exception handler. A throw statement—throw new Exception()—is used to throw an exception.

    A try block is a block of statements containing one or more statements that may throw an exception. Embedding a statement in a try block indicates your awareness that it might throw an exception and your intention to handle the exception.

    Java distinguishes between checked and unchecked exceptions. Checked exceptions must either be caught by the method in which they occur or you must declare that the method containing that statement throws the exception.

    Unchecked exceptions are those that belong to subclasses of RuntimeException. If they are left uncaught, they will be handled by Java’s default exception handlers.

    A catch block is a block of statements that handles the exceptions that match its parameter. A catch block can only follow a try block, and there may be more than one catch block for each try block.

    The try/catch syntax allows you to separate the normal parts of an algorithm from special code meant to handle errors and exceptional conditions.

    A method stack trace is a trace of the method calls that have led to the execution of a particular statement in the program. The Exception.printStackTrace() method can be called by exception handlers to print a trace of exactly how the program reached the statement that threw the exception.

    Static scoping refers to how the text of the program is arranged. If a variable is declared within a method or a block, its static scope is confined to that method or block.

    Dynamic scoping refers to how the program is executed. A statement is within the dynamic scope of a method or block if it is called from that method or block, or if it is called by some other method that was called from that method or block.

    When searching for a catch block to handle an exception thrown by a statement, Java searches upward through the statement’s static scope and backward through its dynamic scope until it finds a matching catch block. If none is found, the Java Virtual Machine will handle the exception itself by printing an error message and a method stack trace.

    Many Java library methods throw exceptions when an error occurs. These throw statements do not appear in the program. For example, Java’s integer division operator will throw an ArithmeticException if an attempt is made to divide by zero.

    Generally, there are four ways to handle an exception: (1) Let Java handle it; (2) fix the problem that led to the exception and resume the program; (3) report the problem and resume the program; and (4) print an error message and terminate the program. Most erroneous conditions reported by exceptions are difficult or impossible to fix.

    A finally statement is an optional part of a try/catch block. Statements contained in a finally block will be executed whether an exception is raised or not.

    A well-designed program should use exception handling to deal with truly exceptional conditions, not as a means of normal program control.

    User-defined exceptions can be defined by extending the Exception class or one of its subclasses.

    1. Integer.parseInt("26.2"); ==> NumberFormatException
    2. String s; s.indexOf(’a’); ==> NullPointerException
    3. String s = "hello"; s.charAt(5); ==> StringIndexOutOfBoundsException

    The unchecked exceptions are IndexOutOfBoundsException, NumberFormatException, and NullPointerException, because these are subclasses of RuntimeException. The others are checked exceptions.

    An ArrayIndexOutOfBoundsException could be handled by the handlers in a, c, or d, because their classes are all superclasses of ArrayIndexOutOfBoundsException.

    If Math.random() in MyClass2 returns 0.98 and then 0.44, the program will generate the following output:

    0.98 is out of range

    Note that because the out-of-range error occurs in method1(), method2() is not called at all.

    If Math.random() in MyClass2 returns 0.98 and then 0.44, the following stack trace would be printed:

    java.lang.ArithmeticException: 0.98 is out of range
        at MyClass2.method1(MyClass2.java:3)
        at MyClass2.main(MyClass2.java:15)

    If Math.random() in MyClass2 returns 0.44 and then 0.98, the program will generate the following output:

    Hello 0.44
    0.98 is out of range

    If Math.random() in MyClass2 returns 0.44 and then 0.98, the following stack trace would be printed:

    java.lang.ArithmeticException: 0.98 is out of range
        at MyClass2.method2(MyClass2.java:8)
        at MyClass2.main(MyClass2.java:16)

    The divide-by-zero error in BadDivide occurs in the expression n/d in Method2(). It would generate the following stack trace:

    java.lang.ArithmeticException: divide by zero
        at BadDivide.method2(BadDivide.java:7)
        at BadDivide.method1(BadDivide.java:3)
        at BadDivide.main(BadDivide.java:13)

    The following version of BadDivide.method2() will handle the divide-by-zero error itself:

    public void method2 (int n, int d) {
        try {
            System.out.println(n / d);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.exit(0);
        }
    }

    If someValue equals 1000, the code segment will print

    Entering try block
    ERROR: 1000 is too large

    If someValue equals 50, the code segment will print

    Entering try block
    Exiting try block
    try {
     if (X < 0)
        throw new Exception(
               "ERROR: Negative value in X coordinate");
    } catch (Exception e) {
     System.out.println( e.getMessage() );
    }
    1. It depends. This is a computer game, so one way to handle this problem would be to generate a message into a log file and resume the game. If the GUI element is crucial to the game, it’s hard to see how it could be successfully handled.
    2. It depends. You would have to decide whether it would be more harmful or dangerous to continue production than not.
    3. The program could report the security violation to the user and to the system manager and then keep accepting user input.
    public class FieldIsEmptyException extends Exception {
        public FieldIsEmptyException () {
            super("The input field is empty ");
        }
    }
    public int getInt() {
        int num = 0;
        try {
            String data = getText();
            if (data.equals(""))
                throw new FieldIsEmptyException();
            num = Integer.parseInt( getText() );
            if (num > bound)
                throw new IntOutOfRangeException(bound);
        } catch (FieldIsEmptyException e) {
            System.out.println("Error: " + e.getMessage() );
        } catch (NumberFormatException e) {
          System.out.println("Error: You must input an integer.  
                                           Please try again.");
        } catch (IntOutOfRangeException e) {
            System.out.println(e.getMessage());
            return 0;
        }
        return num;
    }

    Explain the difference between the following pairs of terms:

    Throwing an exception and catching an exception.

    Try block and catch block.

    Catch block and finally block.

    Try block and finally block.

    Dynamic scope and static scope.

    Dialog box and top-level window.

    Checked and unchecked exception.

    Method stack and method call.

    Fill in the blanks.

    =14pt


    an exception is Java’s way of signaling that some kind of abnormal situation has occurred.

    The only place that an exception can be thrown in a Java program is within a


     .

    The block of statements placed within a catch block is generally known as an


     .

    To determine a statement’s


    scope, you have to trace the program’s execution.

    To determine a statement’s


    scope, you can just read its definition.

    When a method is called, a representation of the method call is placed on the


     .

    The root of Java’s exception hierarchy is the


    class.

    A


    exception must be either caught or declared within the method in which it might be thrown.

    An


    exception can be left up to Java to handle.

    =11pt

    Compare and contrast the four different ways of handling exceptions within a program.

    Suppose you have a program that asks the user to input a string of no more than five letters. Describe the steps you’d need to take in order to design a StringTooLongException to handle cases where the user types in too many characters.

    Exceptions require more computational overhead than normal processing. Explain.

    Suppose the following ExerciseExample program is currently executing the if statement in method2():

    public class ExerciseExample {
      public void method1(int M) {
        try {
          System.out.println("Entering try block");
          method2( M );
          System.out.println("Exiting try block");
        } catch (Exception e) {
          System.out.println("ERROR: " + e.getMessage());
        }
      } // method1()
    
      public void method2(int M) {
        if (M > 100)
          throw new ArithmeticException(M + " is too large");
      }
    
      public static void main(String argv[]) {
        ExerciseExample ex = new ExerciseExample();
        ex.method1(500);
      }
    } // ExerciseExample

    Draw a picture of the method call stack that represents this situation.

    Repeat the previous exercise for the situation where the program is currently executing the second println() statement in method1().

    Draw a hierarchy chart that represents the static scoping relationships among the elements of the ExerciseExample program.

    What would be printed by the ExerciseExample program when it is run?

    What would be printed by the ExerciseExample program, if the statement in its main method were changed to ex.method1(5)?

    Consider again the ExerciseExample program. If the exception thrown were Exception rather than ArithmeticException, explain why we would get the following error message: java.lang.Exception must be caught, or it must be declared….

    Write a try/catch block that throws an Exception if the value of variable X is less than zero. The exception should be an instance of Exception and, when it is caught, the message returned by getMessage() should be “ERROR: Negative value in X coordinate.”

    Look at the IntFieldTester program (Fig. [fig-intbound]) and the IntField class definition (Fig. [fig-intfield2]). Suppose the user inputs a value that’s greater than 100. Show what the method call stack would look like when the IntField.getInt() method is executing the num > bound expression.

    As a continuation of the previous exercise, show what the program’s output would be if the user input a value greater than 100.

    As a continuation of the previous exercise, modify the IntOutOfRangeException handler so that it prints the message call stack. Then show what it would print.

    Define a subclass of RuntimeException named InvalidPasswordException, which contains two constructors. The first constructor takes no parameters and an exception thrown with this constructor should return “ERROR: invalid password” when its getMessage() is invoked. The second constructor takes a single String parameter. Exceptions thrown with this constructor should return the constructor’s argument when getMessage() is invoked.

    Extend the IntField class so that it will constrain the integer JTextField to an int between both a lower and upper bound. In other words, it should throw an exception if the user types in a value lower than the lower bound or greater than the upper bound.

    Design Issue: One of the preconditions for the InsertionSort() method (Fig. 9.13) is that its array parameter not be null. Of course, this precondition would fail if the array were passed a null array reference. In that case, Java would throw a NullPointerException and terminate the program. Is this an appropriate way to handle that exception?

    With respect to the previous exercise, suppose you decide that it is more appropriate to handle the NullPointerException by presenting an error dialog. Modify the method to accommodate this behavior.

    Design Issue: Another possible way to design the sequentialSearch() method (Fig. 9.16) would be to have it throw an exception when its key is not found in the array. Is this a good design? Explain.


    This page titled 10.6: From the Java Library- javax.swing.JOptionPane is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.