简体   繁体   中英

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).

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 jcc is never initialized.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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