O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.5. Choosing Custom Colors

You made provision in the status bar for showing a custom color. It would be a shame not to make use of this, so let's add a dialog to enable any color to be chosen. This is going to be a lot easier than you imagine.

To keep it simple, you'll implement this as a facility on the general pop-up menu, although in practice you would probably want it accessible from the main menu and the toolbar. You can add a member to the SketchFrame class for the menu item:

private JMenuItem customColorItem;

You should add this to the pop-up and add an action listener for it. This requires two statements in the SketchFrame constructor:

customColorItem = popup.add(new JMenuItem("Custom Color...")); // Add the item
customColorItem.addActionListener(this);         // and add its listener

You can add these statements following the others that set up the pop-up menu. Selecting this menu item will now cause the actionPerformed() method in the SketchFrame class to be called so you will implement the custom color choice in there. Let's put that together and try it out.

Try It Out: Choosing a Custom Color

You'll use the facilities provided by the javax.swing.JColorChooser class that does precisely what you want. Here's how you can use it in the actionPerformed() method:

// Handle About menu action events public void actionPerformed(ActionEvent e) { if(e.getSource() == aboutItem) { // Create about dialog with the menu item as parent JOptionPane.showMessageDialog(this, // Parent "Sketcher ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required