|Getting Started With Java|
|Written by Mike James|
Page 3 of 3
Adding Some Code
To make something happen when the button is clicked we can make use of the JOptionPane object which has a range of methods that can be used to make message boxes pop up.
There are lots of objects supplied by the Java framework and they all have names like JOptionPane that usually only make sense when you know what the object is for.
Before we can use JOptionPane we have to tell the compiler that we are intending to use it and you need to add:
to the start of the file. To do this click the Source tab - if you can't already see the code - and scroll to the very top of the file. Type or copy and paste the line in before the line starting public class NewJFrame:
With the import statement in place we can now write a line of code that makes a message box pop up.
Edit the click event handler to read
Don't worry too much about the actual instruction but if you read it then it should make reasonable sense.
The "Hello Swing World" appears as the message and "Hello" as the window title. The JOptionPane.INFOMATION_MESSAGE simply sets the type of pop up box. You may also notice that as you type NetBeans attempts to help you by showing you possible completions of what you are typing, by adding quotes automatically and generally trying to second guess and provide information. The easiest way to find out how all this works is to simply try it out.
If you want to run the program as it is then click the Run icon.
The first time you run the program you will be asked to set the "Main Class" this is just the where the project starts executing code in this case set it to NewJFrame our JFrame class.
You only have to do this once, if you select Remember Permanently, but you can change a project's main class anytime you need to.
When you run the project you should see the JFrame complete with button and when you click the button the Hello Swing World message box should pop up.
Now that you have created and run your first Swing Java application it is time to move on and learn some Java.
Which is the subject of the next part.