Question

I'm trying to create a JColorChooser dialog box with a JLabel above it, so that the JLabel text color will change to the color chosen with JColorChooser by the user. Here's what I have so far, but it is not compiling for me.

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

public class JColorChooserExample extends JFrame
{       
private JColorChooser colorChooser;                                // instance variables          
private JLabel banner;

public JColorChooserExample()                                             // constructor
{
    add(banner = new JLabel("Welcome to the Tutorial Zone!", JLabel.CENTER), BorderLayout.NORTH);
  banner.setForeground(Color.BLACK);
    add(colorChooser = new JColorChooser(banner.getForeground()), BorderLayout.SOUTH);

    ListenerClass listener = new ListenerClass();
    colorChooser.addChangeListener(listener);
}

public static void main(String[] args)
{       
    JColorChooserExample frame = new JColorChooserExample();   // new frame object 
    frame.setTitle("JColorChooser Example");                   // set frame title
    frame.pack();                                                             // sizes the frame so components fit frame  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      // ends program on frame closing
    frame.setLocationRelativeTo(null);                                // centre frame
    frame.setVisible(true);                                    // make frame visible
}

private class ListenerClass implements ChangeListener
{   
    public void stateChanged(ChangeEvent e) 
    {
        Color newColor = colorChooser.getColor();
        banner.setForeground(newColor);
    }
}
}
Was it helpful?

Solution

A ChangeListener should be registered with a JColorChooser's ColorSelectionModel rather than directly with the JColorChooser itself.

colorChooser.getSelectionModel().addChangeListener(listener);

How to Use Color Choosers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top