ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Creating Dialogs with Java’s Swing Class

Updated on September 13, 2013
Jealous Integer.
Jealous Integer. | Source

Creating Dialogs in Java using JOptionPane


Most applications that are used today use some kind of graphical interface. The days of getting input from a dos console are long gone. Therefore, more and more programs are creating applications with a graphical interface in mind. In fact, many legacy programs have been upgraded to have a better look and feel.

The creators of Java also understood this early on and eventually, they too incorporated a way into Java to create dialogs, web forms, application forms and menus. Originally it was the AWT framework; however, it was later found out that this API did not port very well between different platforms. So, they decided to create a new API. The result was the creation of the Java Swing API. Now, the Swing GUI is part of the Java Foundation Classes (JFC) that comes bundled with the Java programming language. It can be accessed by importing the javax.swing class into your program.

In this article, I am going to touch on one particular class known as JOptionPane. The two main methods I will cover are, “showInputDialog,” to get input from the user and “showMessageDialog,” to show the results of that input.

What does the JOptionPane Class Do?

JOptionPane is a class that allows access to methods which invoke dialogs. These dialogs can be used for user input or to show a message to the user for a certain event. For example, to show an error message, you could use the “showMessageDialog,” method to tell the user that an error has occurred in the program. Secondly, if you want the user to enter input you can use the “showInputDialog,” to read that input. Both are commonly used methods for creating dialogs in a program. If you want more detail information on JOptionPane, you can visit Oracle’s web site at http://docs.oracle.com/.

The Code:

The following code was created using a basic Java console project in the NetBeans IDE. It creates two dialog boxes that take in integer input from the user. It then adds that input to create a sum and later shows a dialog with the results. So, here is the code:

Code:

//**********************************************************
//
// Author: Bink
//
// Description: Ask the user to input numbers into 
//              two dialogues and then add the numbers for input 
//              to a third java dialogue.
//              If input is not a number, show the error to the user
//
//***************************************************************
package addtiondialogues;

//This program uses JOptionPane
import javax.swing.JOptionPane;

public class AddtionDialogues {

    public static void main(String[] args) {
        
       boolean done = false;//Control Variable for the while loop
       
       //repeat until a valid input is entered
       while(!done)
       {
       
            //Obtain user input using two JOption Pane dialogues
            String firstNumber = JOptionPane.showInputDialog("Enter first integer");
            String secondNumber = JOptionPane.showInputDialog("Enter second integer");
        
            //convert String input to int values to use in a calculation
            //Catch an error if input was not a number
            try{
            double number1 = Double.parseDouble(firstNumber);//change to double
            double number2 = Double.parseDouble(secondNumber);//change to double
            
            //Add input values (number1 + number2) to sum variable
            double sum = number1 + number2;
            
            //Show results in a new JOptionPane dialogue
            JOptionPane.showMessageDialog(null, "The sum is " + sum,
                    "Sum of Two Integers",JOptionPane.PLAIN_MESSAGE);
            //exit while loop
            done = true;
            } //Catch error if input was not a number and repeat while loop.
            catch ( NumberFormatException e){
                JOptionPane.showMessageDialog(null, 
                        "Error: You have to enter two numbers!",
                        "Error Message",JOptionPane.ERROR_MESSAGE);
                }//end try/catch block       
       }//end while loop
    }//end main
}//end AdditionDialogues Class


So, what is going on in this code?

The program first imports the javax.swing API that allows the program to have access to JOptionPane methods and in turn allows you to create dialogs. The first two string variables creates the dialog dynamically (on the fly) using the showInputDialog method. When each dialog box is created and shown on the screen, the user can enter a number and then press “OK.” The next two double variables convert each input from Strings to double (i.e. to a decimal number) so that the addition calculations can be done. Finally, everything was put into a while loop (using the done Boolean variable) and a try/catch block to make sure the program keeps running if the user makes the mistake of inputting something besides a number.

Try/Catch what is that all about?

The try/catch block is used by programmers to control input or event errors during runtime. In this case, we want make sure that the user actually inputs two numbers instead of characters. The try/catch block is for Exception handling and is beyond the scope of this article, however, it is always a good idea to use try/catch blocks in your code where you think that there is a possibility that something may go wrong. Not to mention that it is not a bad idea to use it if you are debugging a program.

Little More Explanation of the showMessageMethod:

As you can see above, the showMessageDialog takes in four parameters. The first parameter is null and all it is telling the program is to make sure the dialog is centered on the screen. The second creates a message within the dialog. In this case, it shows the result after adding the two integers. The third parameter is a string that gives the dialog its title. Finally, the last parameter tells the program what kind of dialog this is. What I mean by that is that the constant that you use (i.e. PLAIN_MESSAGE, ERROR_MESSAGE, etc.) determines what icon appears in the dialog.

Below are some of the constants that you can pass as a parameter to showMessageIcon:

Table of Common Constants:

 
 
 
Constant
Icon
Remarks
ERROR_MESSAGE
Stop Sign with X
Indicates an error to the user
INFORMATION_ERROR
Circle with an i
Indicates an information message
WARNING_MESSAGE
Yield Sign with Exclamation Mark
Warns user of potential problem
QUESTION_MESSAGE
Circle with a Question Mark
Ask a question with Yes/No Buttons
PLAIN_MESSAGE
No icon
Basic Message.


Conclusion:

So, that is it for JOptionPane. The Java Swing GUI is a good way to create a user GUI using Java. Now you can create dialogs that not only ask for input, but gives messages warnings to the user if something goes wrong. This is especially helpful if you have created a program using “Exception Handling.”

Please add Coments Below.

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article