我正在尝试创建一个JColorChooser对话框,在其上方带有JLabel,以便JLabel文本颜色将更改为用户使用JColorChooser选择的颜色。这是我到目前为止的内容,但尚未为我编译。

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

最佳答案

ChangeListener应该在JColorChooserColorSelectionModel中注册,而不是直接在JColorChooser本身中注册。

colorChooser.getSelectionModel().addChangeListener(listener);


How to Use Color Choosers

08-08 01:02