Adding Event Handler Code

See Also

In this section, you use the IDE's Source Editor.

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. From the Source Editor toolbar, select main from the combo box of methods.

    The cursor appears at the beginning of the main method declaration.

  2. Move the cursor to the line below the variable declaration section (on or about line 74) and declare a new variable:
    private java.awt.Color currentColor = java.awt.Color.lightGray; 
    
    Tip The cursor's location in the Source Editor window is indicated by the line and column numbers found in the bottom left corner of the window. The format is line:column.

    Use the dynamic code completion feature in the Source Editor by typing a few characters of an expression and a list of possible classes, methods, variables, and so on appears. Pick from the list to automatically complete the expression and hit enter. For example, type private java.awt.C and pause. A list of all possible AWT methods that begins with C appears. Select Color from the list of possible methods to automatically complete the expression, hit enter, and the code expression is completed for you.

  3. Select jButton1MouseClicked from the list of methods, place the cursor after //Add your handling code here: line (on or about line 55), and 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);
    
    Tip Note that the last line is jLabel with the number one ("1") before the period and not the letter "l".
  4. Save the file by right-clicking anywhere in the Source Editor and selecting Save from the contextual menu.

Next:  Compiling and Running Your Program
Back:  Setting Up the Button to Switch Color
See Also
Editing Source Files
Using Code Completion
Managing Component Events

Legal Notices