Programming & Scripting Tutorials

Java: Our First GUI Application



Ok, so now we can get onto the fun stuff, a proper GUI(graphical user interface)!
We can have proper windows, pop-ups, textboxes, buttons and loads more!

Firstly we need to import all of the tools and things we will need.
Luckily java built in a class which has all of these:

import javax.swing.JOptionPane;


Now we are good to go, and we can use GUI stuff.
The first program we are going to build is going to take two numbers, and add them up.
Firstly we can create are two variables, but are going to have to make them strings, as the input method we are going to use accepts input as strings.
The variable declaration and initialisation would look like this:

String input1 = JOptionPane.showInputDialog("Enter Num1");
String input2 = JOptionPane.showInputDialog("Enter Num2");

So we are making the strings 'input1' and 'input2' be input dialogs with different messages, but at the moment they are only strings, and to do things with them we need int's, so we have to convert them:

int num1 = Integer.parseInt(input1);
int num2 = Integer.parseInt(input2);

Note that the parseInt method isnt anything to do with JOptionPane, its just plain java.

Now we need to create the total:

int total = num1 + num2;

Now we can create the pop-up message which shows the total:

JOptionPane.showMessageDialog(null, "Total: " + total, "Answer!", JOptionPane.PLAIN_MESSAGE);


As you can see the showMessageDialog method takes four parameters.
The first is where to position the pop-up; if you put null it puts it right in the middle of the screen.
The second is what you actually want to be on the pop-up, in our case we want 'Total: ' and then our total.
The third parameter is what we want to appear on our title bar, in this case 'Answer!'
Finally the last parameter is just if you want any icons on your message, at the moment we just want a plain message (as specified).

Congratulations, you have just created your first GUI Java application!

The full code for this lesson is:

String input1 = JOptionPane.showInputDialog("Enter Num1");
String input2 = JOptionPane.showInputDialog("Enter Num2");
int num1 = Integer.parseInt(input1);
int num2 = Integer.parseInt(input2);
int total = num1 + num2;
JOptionPane.showMessageDialog(null, "Total: " + total, "Answer!", JOptionPane.PLAIN_MESSAGE);

Also, don't forget our import statement:

import javax.swing.JOptionPane;



This Java tutorial was written by


Back to Java

Advertisement: