![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e878. Customizing the Preview Panel of a JColorChooser DialogThe preview panel shows the selected color in a particular context. The default preview panel colors some text with the selected color.It may be desirable to change the preview panel to a more relevant setting. For example, if the color chooser is used to color an image, a miniature version of the image can be shown in the preview panel. JColorChooser chooser = new JColorChooser(); chooser.setPreviewPanel(new MyPreviewPanel(chooser)); // This preview panel simply displays the currently selected color. public class MyPreviewPanel extends JComponent { // The currently selected color Color curColor; public MyPreviewPanel(JColorChooser chooser) { // Initialize the currently selected color curColor = chooser.getColor(); // Add listener on model to detect changes to selected color ColorSelectionModel model = chooser.getSelectionModel(); model.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { ColorSelectionModel model = (ColorSelectionModel)evt.getSource(); // Get the new color value curColor = model.getSelectedColor(); } }) ; // Set a preferred size setPreferredSize(new Dimension(50, 50)); } // Paint current color public void paint(Graphics g) { g.setColor(curColor); g.fillRect(0, 0, getWidth()-1, getHeight()-1); } }
© 2002 Addison-Wesley. |