簡體   English   中英

如何將JColorChooser添加到contentpane / Jpanel?

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

我正在嘗試將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();

}

}

我正在使用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類名稱應按約定大寫,並取決於您的教授的挑剔程度,您需要在擺動線程(事件調度線程)上顯示JFrame。 無論如何 ,您都應該這樣做,以實現良好的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