Workshop 2007 JRE Java Support
Installation
Home
CalcTool
Java Applets
Friends/Family
Gardening
Woodworking
Forums

Adding a Button to your Applet

Let’s add a button to your applet and give it some functionality.  So go back to the design pad. You should see the Hello World label that you created previously. 

 

NetBeans automatically generates a mouse listener and the goButtonMouseClicked method to handle any mouse click.

 

private void goButtonMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:

}

 

This is where we’re going to add code that will be executed when the event is fired.

 

Declare the string variable labelString

Do this in the goButtonMouseClicked method. The variable type is String with name is labelString. Most statements in java will end in a semi-colon, so don’t forget to conclude in this fashion.  You should have something like

 

String labelString;

 

Initialize labelString to “Goodbye World”. 

Use the equals sign to set labelString equal to this snippet of text. You must use quotes around the text. Don’t forget the semi-colon! You should now have

String labelString;
labelString=”GoodBye World”;

It’s also possible (and good programming practice) to declare and initialize variables at the same time. You may simply combine the previous two statements into one line.

String labelString=”Goodbye World”;

Set the text from labelString into the helloWorldLabel object. 

We will use the setText(String) method to do this.  Java dictates that methods associated with a particular object should be reference according to the convention

 

object.method();

 

Note the period between the object and method—this is important!  Our object is the helloWorldLabel and the method is the setText method. Its argument must be a String variable.  Thus, you should type

helloWorldLabel.setText(labelString);

If you wish to append other text to the labelString, you may do so using the + sign.  For example

helloWorldLabel.setText(labelString+” Leaders”);

will result in the following output.

Goodbye World Leaders

Compile and run your applet. 

Click on the button to see your creation in action!

 

Adding a TextField to your Applet

Drag/drop a JTextField onto your designer pad.

The default text is jTextField1.  You may wish to remove this by simply double-clicking on the text field and deleting the text.

 

Rename it inputTextField.

 

Edit the goButtonMouseClicked method

Edit this method to take input from the inputTextField and set it into the helloWorldLabel.  You will need to use the getText() method. See if you can figure out how to do this. Hint:  the getText() method returns a String value.  If you need to peek, the code is here.

 

Adding Interactivity to Your Applet