I want to do some work when I choose a color from JColorChooser. Not after pressing OK button.
For example: When I press Red color, I want to display a message saying "You picked red". What I really want to achieve is present some kind of preview to user.
QUESTION: How to set Listener when pressed color from JColorChooser?
"How to set Listener when pressed color from JColorChooser"
When in doubt, refer to the tutorial. It states:
A color chooser uses an instance of
ColorSelectionModel
to contain and manage the current selection. The color selection model fires a change event whenever the user changes the color in the color chooser.
Example code from tutorial
tcc.getSelectionModel().addChangeListener(this);
. . .
public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
banner.setForeground(newColor);
}
UPDATE
The color chooser tutorial has a ColorChooserDemo program that should be fairly easy to follow, but here's an even simpler program that should be even easier to follow.
import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DemoColorChooser {
public static void main(String[] args) {
final JColorChooser chooser = new JColorChooser();
chooser.setColor(Color.BLUE);
chooser.getSelectionModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
Color color = chooser.getColor();
System.out.println(color);
}
});
JDialog dialog = JColorChooser.createDialog(null, "Color Chooser",
true, chooser, null, null);
dialog.setVisible(true);
System.exit(0);
}
}
You should keep in mind that a JColorChooser is just a normal component, it is a not a dialog window. It may seem that way because you may be used to using JColorChooser.showDialog()
which automatically wraps it in in a dialog. But as you can see in the code above, I wrap it myself. Knowing this allows you to add other viewing components to the dialog, as you say you "want to present some kind of preview", you can do so in the dialog