简体   繁体   中英

JColorChooser won't change text color of JLabel

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);
    }
}
}

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

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