Tutorial Tutorial Step 07

Building a Java text editor

Step 6: Attaching menu item events to JColorChooser

Now let's create Edit|Foreground and Edit|Background menu events, and connect them to a Swing JColorChooser dialog.

Since you don't need to set any of the properties for JColorChooser in the designer, there's no need to add it to the UI in the designer. You can just call it directly from a menu item's actionPerformed() event handler as follows:

  1. Switch back to the designer for TextEditFrame.java.

  2. Select the second menu item in the component tree under Edit (jMenuItem6) which has "Foreground Color" in its actionCommand property.

  3. Click the Events tab in the Inspector and triple-click the actionPerformed() event to create the following event handler:

    void jMenuItem6_actionPerformed(ActionEvent e) {
    }
    
  4. Insert the following code into the stub of the event handler (including comments if you wish):
    //Handle the "Foreground Color" menu item
    Color color = JColorChooser.showDialog(this,"Foreground Color",jTextArea1.getForeground());
    if (color != null) {
    jTextArea1.setForeground(color);
    }
    //repaints menu after item is selected
    this.repaint();
    
  5. Switch back to the designer.

  6. Select the third menu item in the component tree under Edit (jMenuItem7), which should have "Background Color" in its actionCommand property. Create an actionPerformed() event for it as you did for jMenuItem6.

  7. Insert the following code into the actionPerformed() event for jMenuItem7:
    // Handle the "Background Color" menu item
    Color color = JColorChooser.showDialog(this,"Background Color",jTextArea1.getBackground());
    if (color != null) {
    jTextArea1.setBackground(color);
    }
    //repaints menu after item is selected
    this.repaint();
    
  8. Save your file, then compile and run your application. Type in text and play around with the foreground and background colors. Here is what it looks like if you set the foreground to white and the background to black:

    TextEdit UI

  9. Close the "Text Editor" application.

Tutorial Tutorial Step 07