JColorChooser不会更改JLabel的文本颜色

时间:2013-04-04 22:13:00

标签: java swing jlabel jcolorchooser

我正在尝试创建一个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);
    }
}
}

1 个答案:

答案 0 :(得分:1)

ChangeListener应该在JColorChooser的{​​{1}}注册,而不是直接与ColorSelectionModel本身注册。

JColorChooser

How to Use Color Choosers