1

私が作成している単純な描画プログラムのために、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();

}

}

私は日食を使用していますが、コード (赤い線) にエラーは返されませんが、実行しようとすると、次のようになります。

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

これに関する助けがあれば大歓迎です!

4

1 に答える 1

3

初期化されていないようjccです。

JColorChooser jcc = new JColorChooser();

そしていくつかのポインタ。Java クラス名は慣例により大文字にする必要があり、教授のこだわりに応じて、swing スレッド (イベント ディスパッチ スレッド) で JFrame を表示する必要があります。とにかく、GUI スレッドの適切な処理のためにこれを行う必要があります。

public static void main(String[] args) 
{
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Test test = new Test();
            test.setVisible(true);
        }
});
于 2012-04-17T17:04:26.917 に答える