2012-03-07 36 views
1

我得到這個運行時錯誤,我想使java文件選擇器看起來像Windows之一。NullPointerException當使用WindowsFileChooserUI

錯誤代碼:

Exception in thread "main" java.lang.NullPointerException 
at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installComponents(WindowsFileChooserUI.java:306) 
at javax.swing.plaf.basic.BasicFileChooserUI.installUI(BasicFileChooserUI.java:173) 
at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installUI(WindowsFileChooserUI.java:150) 
at Main.getImg(Main.java:49) 
at Main.main(Main.java:19) 

代碼:

JFileChooser fico = new JFileChooser(); 
WindowsFileChooserUI wui = new WindowsFileChooserUI(fico); 
wui.installUI(fico); 
int returnVal = fico.showOpenDialog(null); 
+0

我剛剛在你的問題中執行了4行代碼,並沒有例外。你能指定你的問題還是發送更多的代碼? – Juvanis 2012-03-07 03:56:04

回答

3

當UI對象初始化時,它試圖讀取,它預期存在的UI經理(一些用戶界面默認的FileChooser.viewMenuIcon屬性),它總是Windows下的大號& F,但沒有下金屬大號& F.

Firstl存在y,警告。在Swing中同時混合多個L & F是危險的。 Swing實際上一次只能與一個L & F一起運行。

設置「特殊」文件選擇器的更好方法是在應用程序啓動時通過UI管理器初始化所有內容。

//Do this first thing in your application before any other UI code 

//Switch to Windows L&F 
LookAndFeel originalLaf = UIManager.getLookAndFeel(); 
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 

//Create the special file chooser 
JFileChooser windowsChooser = new JFileChooser(); 

//Flick the L&F back to the default 
UIManager.setLookAndFeel(originalLaf); 

//And continue on initializing the rest of your application, e.g. 
JFileChooser anotherChooserWithOriginalLaf = new JFileChooser(); 

現在你有兩個不同的大號& Fs的,您可以使用兩個組件。

//First chooser opens with windows L&F 
windowsChooser.showOpenDialog(null); 

//Second chooser uses default L&F 
anotherChooserWithOriginalLaf.showOpenDialog(null); 
+1

OMG我愛你很多! +1 – PulsePanda 2012-08-08 20:56:17

+0

很好的回答,先生! – 2013-08-15 03:41:30

相關問題