ProblemYou want to allow the user to select a color from all the colors available on your computer. SolutionUse Swing's JColorChooser. DiscussionOK, so it may be just glitz or a passing fad, but with today's displays, the 13 original AWT colors are too limiting. Swing's JColorChooser lets you choose from zillions of colors. From a program's view, it can be used in three ways:
We use the last method since it's the simplest and the most likely to be used in a real application. The user has several methods of operating the chooser, too:
Figure 14-11. JColorChooser: HSB view in action
Example 14-7 contains a short program that makes it happen. Example 14-7. JColorDemo.javaimport com.darwinsys.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /* * Colors - demo of Swing JColorChooser. * Swing's JColorChooser can be used in three ways: * <UL><LI>Construct it and place it in a panel; * <LI>Call its createDialog( ) and get a JDialog back * <LI>Call its showDialog( ) and get back the chosen color * </UL> * <P>We use the last method, as it's the simplest, and is how * you'd most likely use it in a real application. * * Originally appeared in the Linux Journal, 1999. */ public class JColorDemo extends JFrame { /** A canvas to display the color in. */ JLabel demo; /** The latest chosen Color */ Color lastChosen; /** Constructor - set up the entire GUI for this program */ public JColorDemo( ) { super("Swing Color Demo"); Container cp = getContentPane( ); JButton jButton; cp.add(jButton = new JButton("Change Color..."), BorderLayout.NORTH); jButton.setToolTipText("Click here to see the Color Chooser"); jButton.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent actionEvent) { Color ch = JColorChooser.showDialog( JColorDemo.this, // parent "Swing Demo Color Popup", // title demo.getForeground( )); // default if (ch != null) demo.setForeground(ch); } }); cp.add(BorderLayout.CENTER, demo = new MyLabel("Your One True Color", 200, 100)); demo.setToolTipText("This is the last color you chose"); pack( ); addWindowListener(new WindowCloser(this, true)); } /** good old main */ public static void main(String[] argv) { new JColorDemo( ).setVisible(true); } } See AlsoThis program introduces setToolTipText( ), a method to set the text for pop-up "tooltips" that appear when you position the mouse pointer over a component and don't do anything for a given time (initially half a second). Tooltips originated with Macintosh Balloon Help and were refined into ToolTips under Microsoft Windows.[2] Tooltips are easy to use; the simplest form is shown here. For more documentation, see Chapter 3 of Java Swing.
|