2012-03-07 53 views
1

このランタイムエラーが発生しました.Javaファイルの選択をウィンドウのようにしています。WindowsFileChooserUIを使用しているときにNullPointerExceptionが発生する

エラーコード:

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

答えて

3

UIオブジェクトは、存在することを想定しているUIマネージャからいくつかのUIのデフォルト値(FileChooser.viewMenuIconを読み取るしようとして初期化されますWindows L & Fの下には常に存在しますが、メタルL & Fの下には存在しません。

Firstl y、警告。 Swingで同時に複数のL & Fを混ぜることは危険です。スイングは、一度に1つの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(); 

は、今あなたが使用できる2つの異なるL & Fsを持つ2つのコンポーネントがあります。

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

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

OMG私はあなたが大好きです! +1 – PulsePanda

+0

偉大な答えです、サー! –

関連する問題