2012-04-17 33 views
0

我正在嘗試將一個JColorChooser添加到面板中,或者直接添加到主內容面板中,以製作一個簡單的繪圖程序(作爲任務的一部分)。如何將JColorChooser添加到contentpane/Jpanel?

我試圖找到使用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();" 

任何幫助,這都將不勝感激!

回答

3

看起來jcc永遠不會初始化。

JColorChooser jcc = new JColorChooser(); 

和一對指針。 Java類名應該按照慣例大寫,並且根據教授的挑剔程度,您需要在swing線程(Event Dispatch Thread)上顯示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); 
     } 
}); 
+0

很好的答案+1 – mKorbel 2012-04-17 17:06:38

+0

嘎,我實際上在其他點初始化它,但它給了我另一個錯誤。不過,我現在又重新初始化了它,它的工作方式就像塗油的機器。 我通常大寫類,它只是一個快速的東西扔在一起粘貼在這裏,但感謝指針反正! 謝謝! – user1339253 2012-04-17 17:12:00

+0

這是你點擊綠色複選標記的部分;-) – Jim 2012-04-17 20:02:18