NullPointerException when using WindowsFileChooserUI

此生再无相见时 提交于 2019-12-11 08:16:32

问题


I get this run-time error, i am trying to make the java file chooser look like the windows one.

error code:

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)

Code:

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

回答1:


When the UI object is initializing, it is trying to read some UI defaults from the UI manager that it expects to exist (the FileChooser.viewMenuIcon property), which always exists under the Windows L&F but not under the Metal L&F.

Firstly, a warning. Mixing multiple L&F at the same time in Swing is hazardous. Swing is really only meant to be run with one L&F at a time.

A better way to set up a 'special' file chooser is to initialize everything through the UI manager when your application starts up.

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

Now you have two components with two different L&Fs which you can use.

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

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


来源:https://stackoverflow.com/questions/9595358/nullpointerexception-when-using-windowsfilechooserui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!