我正在尝试将 JColorChooser 添加到面板中,或直接添加到主内容 Pane 中,以用于我正在制作的简单绘图程序(作为作业的一部分)。
我尝试查找使用 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 类名应大写,并且根据教授的挑剔程度,您需要在 Swing 线程(事件调度线程)上显示 JFrame。你应该do this anyway良好的 GUI 线程处理。
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Test test = new Test();
test.setVisible(true);
}
});
关于java - 如何将 JColorChooser 添加到内容 Pane /Jpanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195419/