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.
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;
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”;
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
Click on the button to see your creation in action!
The default text is jTextField1. You may wish to remove this by simply double-clicking on the text field and deleting the text.
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.
Note: if you did not resize inputTextField, it may show up on your applet too narrow to be of much use. Simply go back to the design pad and resize the text field to a size to your liking and it will now show up as expected.