4 package net.sf.openrocket.gui.components;
6 import javax.swing.JButton;
7 import javax.swing.JColorChooser;
8 import javax.swing.JDialog;
9 import javax.swing.JLabel;
10 import javax.swing.JPanel;
11 import javax.swing.JTextField;
12 import javax.swing.SwingUtilities;
13 import javax.swing.colorchooser.ColorSelectionModel;
14 import javax.swing.event.ChangeEvent;
15 import javax.swing.event.ChangeListener;
16 import java.awt.Color;
17 import java.awt.event.ActionEvent;
18 import java.awt.event.ActionListener;
21 * A panel implementation of a color chooser. The panel has a label and a textfield. The label identifies
22 * what the color is to be used for (the purpose), and the textfield is uneditable but has its background set
23 * to the currently chosen color as a way of visualizing the color.
25 * The chosen color may be retrieved via a call to getCurrentColor.
27 public class ColorChooser extends JPanel {
29 private static final String COLOR_CHOOSER_BUTTON_LABEL = "Color";
31 // The currently selected color
32 private Color curColor;
34 final JColorChooser chooser;
36 final JTextField field;
40 * Construct a color chooser as a panel.
42 * @param parent the parent panel to which this component will be added
43 * @param theChooser the delegated color chooser; the initial color taken from this chooser
44 * @param theLabel the label used as the 'purpose' of the color; placed next to a textfield
46 public ColorChooser (JPanel parent, JColorChooser theChooser, final String theLabel) {
49 chooser.setPreviewPanel(this);
50 // Initialize the currently selected color
51 curColor = chooser.getColor();
52 label = new JLabel(theLabel + ":");
54 parent.add(label, "align right");
55 field = new JTextField();
56 field.setEditable(false);
57 field.setBackground(curColor);
58 parent.add(field, "width 50:100:100");
60 final JButton button = new JButton(COLOR_CHOOSER_BUTTON_LABEL);
62 ActionListener actionListener = new ActionListener() {
63 public void actionPerformed (ActionEvent actionEvent) {
66 final JDialog dialog = JColorChooser.createDialog(null,
71 // Wait until current event dispatching completes before showing
73 Runnable showDialog = new Runnable() {
78 SwingUtilities.invokeLater(showDialog);
81 button.addActionListener(actionListener);
82 parent.add(button, "wrap");
84 // Add listener on model to detect changes to selected color
85 ColorSelectionModel model = chooser.getSelectionModel();
86 model.addChangeListener(new ChangeListener() {
87 public void stateChanged (ChangeEvent evt) {
88 ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
89 // Get the new color value
90 curColor = model.getSelectedColor();
91 field.setBackground(curColor);
97 * Get the user-selected color.
99 * @return the current color
101 public Color getCurrentColor () {