Adding Event Handler Code

Now that the jButton1MouseClicked() method has been created, you can add custom code for handling this event. You want a click of the button to change the color of the label.

To add the code:

  1. In the Source Editor, after the comment //End of variables declaration (on or about line 76), declare a new variable:
    private java.awt.Color currentColor = java.awt.Color.lightGray; 
    

    To use the dynamic code completion feature in the Source Editor, type the first few characters. Select the completed term from the displayed list of classes, methods, and variables, and press Enter.

  2. After //Add your handling code here: (on or about line 57), type the following:
    if (currentColor == java.awt.Color.lightGray)
        currentColor = java.awt.Color.gray;
    else if (currentColor == java.awt.Color.gray)
        currentColor = java.awt.Color.black;
    else
        currentColor = java.awt.Color.lightGray;
    jLabel1.setBackground (currentColor);
    
  3. Save the file by choosing File and chooose Save from the main window.

Next:  Compiling and Running Your Program
Back:  Setting Up the Button to Switch Color

Legal Notices