简体   繁体   English

如何将JColorChooser添加到contentpane / Jpanel?

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

I'm trying to add a JColorChooser to either a panel, or directly into the main contentpane, for a simple drawing program I'm making (as part of an assignment). 我正在尝试将JColorChooser添加到面板中,或直接添加到主内容窗格中,以实现我正在制作的简单绘图程序(作为分配的一部分)。

I've tried to find examples of code using JColorChooser (such as http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html ), but I can't seem to get it to work. 我试图使用JColorChooser查找代码示例(例如http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html ),但我似乎无法使其正常工作。

Relevant code: 相关代码:

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

}

}

I'm using eclipse, and it doesn't return any errors in my code (red lines), but once I try to run it, I get this out: 我正在使用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();"

Any help at all with this would be greatly appreciated! 任何帮助都将不胜感激!

It looks like jcc is never initialized. 看来jcc从未初始化。

JColorChooser jcc = new JColorChooser();

and a couple of pointers. 和几个指针。 Java class names should be capitalized by convention and depending on how picky your professor is, you need to show the JFrame on the swing thread (Event Dispatch Thread). Java类名称应按约定大写,并取决于您的教授的挑剔程度,您需要在摆动线程(事件调度线程)上显示JFrame。 You should do this anyway for good GUI thread handling. 无论如何 ,您都应该这样做,以实现良好的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