简体   繁体   中英

Java Swing Colour Chooser Throwing Error

So I'm trying to implement a colour chooser that will then take that colour and pass it to another class to be used, but it's throwing up the error

"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.colorchooser.DefaultColorSelectionModel cannot be cast to javax.swing.JColorChooser"

every time I click a colour.

The code I'm using is:

For the actual JColorChooser :

JColorChooser RGB = new JColorChooser(Color.GREEN);
RGB.getSelectionModel().addChangeListener(this);
RGB.setAlignmentX(newPolyButton.LEFT_ALIGNMENT);
RGB.setMinimumSize(new Dimension(50, 25));
RGB.setPreferredSize(new Dimension(125, 25));

And for the listener:

public void stateChanged(ChangeEvent c) {
JColorChooser RGB = (JColorChooser)c.getSource();
Color poly = RGB.getColor();
imagePanel.setColor(poly);
}

And in the other class, imagePanel , I use:

public void setColor(Color poly) {
ImagePanel.poly = poly;
}

Can anyone see where I'm going with this? I was previously using a combo box with some manually input colours to choose from.

Any help greatly appreciated, thanks!

In your stateChanged method, c.getSource() returns a DefaultColorSelectionModel and not the reference to your JColorChooser .

However, JColorChooser is usually used to open a color dialog that returns a Color when closed using the OK button.

Color color = JColorChooser.showDialog(parent, title, initialColor);
if (color != null) {
  // do something with the chosen color
}

From your code

RGB.getSelectionModel().addChangeListener(this);
RGB.setAlignmentX(newPolyButton.LEFT_ALIGNMENT);

You are adding the ChangeListener to the Selection Modal for your RGB instance.

javax.swing.JColorChooser.getSelectionModel() will return an instance of DefaultColorSelectionModel .

Hence, you get a ClassCastException in your call (JColorChooser)c.getSource(); .

UPDATE

From How to Use Color Choosers Java Tutorial :

tcc.getSelectionModel().addChangeListener(this);
. . .
public void stateChanged(ChangeEvent e) {
    Color newColor = tcc.getColor();
    banner.setForeground(newColor);
}

When the state changes, you will want to get the new color as a property of the Color Chooser instead of attempting to get the Source of the ChangeEvent and cast it.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM