简体   繁体   English

JColorChooser不会更改JLabel的文本颜色

[英]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. 我正在尝试创建一个JColorChooser对话框,在其上方带有JLabel,以便JLabel文本颜色将更改为用户使用JColorChooser选择的颜色。 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. ChangeListener应该向JColorChooserColorSelectionModel注册,而不是直接向JColorChooser本身注册。

colorChooser.getSelectionModel().addChangeListener(listener);

How to Use Color Choosers 如何使用颜色选择器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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