Most of you should know the program Hello, world! Well, lets do this again, but total revamp it. Type what I have below, and then we will go over it.
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello, world!");
}
}
Alright! When you run that, a box should appear saying Hello, world! with an i off to the side, and a button labeled OK below the text. The title of your box should be message. If its not, just let me know any errors you get. But now to the meaning of the code. We all know the imports, class, main blah blah blah. But what about the code in the main method? Well, this is the GUI version of System.out.println(). The null part is just testing where to put it, in case it is from a bigger component, and we will look at that later. But back to the showMessageDialog. It comes from the JOptionPane class, which was imported from javax.swing. Now, lets make our messageDialog look nicer. Change the original showMessageDialog to this
JOptionPane.showMessageDialog(null, "Hello, world!", "Hello!", JOptionPane.PLAIN_MESSAGE);
There. All we did is add 2 more arguments. The 3rd argument is the title of the box, which you should have seen as Hello! The last part says to set the image to PLAIN_MESSAGE, or nothing.
I/O with JOptionPane
We all remeber our odd even program, right? Well, just like hello world we are going to do it again with a GUI. Here we go!
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
int num = JOptionPane.showInputDialog(null, "Enter a number");
if(num == 0) {
JOptionPane.showMessageDialog(null, "You entered 0.");
} else if(num % 2 == 0) {
JOptionPane.showMessageDialog(null, "Even.");
} else {
JOptionPane.showMessageDialog(null, "Odd.");
}
}
}
There you have it! A working odd even program, with a GUI! We only intruduced one new concept here. showInputDialog will prompt the user to input smoething. And that can return and int, a double, a float or a string. We chose to work with ints.
Well, that was fun! You can now go and make some basic I/O programs with this. But don't go to far, because next time we learn how to make a GUI that works the exact way we want it to, and all that good stuff! Thanks!
-Steve
YOU ARE READING
Java Swing GUI Development
Non-FictionLearn all the necessities of Java Swing GUI development right here, from me, not some huge cooperate company, that can't find a good way to get the message across. Learn it here, learn it once.
