使用WindowsFileChooserUI时出现NullPointerException

时间:2012-03-07 03:22:51

标签: java nullpointerexception jfilechooser

我遇到这个运行时错误,我试图让java文件选择器看起来像windows一样。

错误代码:

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

1 个答案:

答案 0 :(得分:4)

当UI对象正在初始化时,它正在尝试从UI管理器中读取它预期存在的一些UI默认值(FileChooser.viewMenuIcon属性),该默认值始终存在于Windows L& F下但不在金属L& F.

首先是警告。在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();

现在您有两个组件,可以使用两个不同的L& Fs。

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

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