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.”

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)