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).
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.
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:
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
jccis never initialized.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). You should do this anyway for good GUI thread handling.