繁体   English   中英

如何将JColorChooser添加到contentpane / Jpanel?

[英]How do I add a JColorChooser to a contentpane/Jpanel?

我正在尝试将JColorChooser添加到面板中,或直接添加到主内容窗格中,以实现我正在制作的简单绘图程序(作为分配的一部分)。

我试图使用JColorChooser查找代码示例(例如http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html ),但我似乎无法使其正常工作。

相关代码:

import java.awt.BorderLayout;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class test extends JFrame 
{

JColorChooser jcc;
ColorSelectionModel model = jcc.getSelectionModel();

public test()
{
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocation(100,100);
    this.setSize(900,600);

    getContentPane().add(jcc, BorderLayout.CENTER);

    model.addChangeListener(new ChangeListener() 
    {
    public void stateChanged(ChangeEvent e) {
      System.out.println("Color: " + jcc.getColor());
    }

  });

}

public static void main(String[] args) 
{

    test m=new test();

}

}

我正在使用eclipse,它不会在我的代码(红线)中返回任何错误,但是一旦我尝试运行它,我就会发现:

Exception in thread "main" java.lang.NullPointerException
at test.<init>(test.java:14) --> this is "ColorSelectionModel model = jcc.getSelectionModel();"
at test.main(test.java:38) --> this is "test m=new test();"

任何帮助都将不胜感激!

看来jcc从未初始化。

JColorChooser jcc = new JColorChooser();

和几个指针。 Java类名称应按约定大写,并取决于您的教授的挑剔程度,您需要在摆动线程(事件调度线程)上显示JFrame。 无论如何 ,您都应该这样做,以实现良好的GUI线程处理。

public static void main(String[] args) 
{
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Test test = new Test();
            test.setVisible(true);
        }
});

暂无
暂无

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

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