使用 WindowsFileChooserUI 时出现 NullPointerException

aba*_*ned 2 java jfilechooser nullpointerexception

我收到此运行时错误,我正在尝试使 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)
Run Code Online (Sandbox Code Playgroud)

代码:

JFileChooser fico = new JFileChooser();
WindowsFileChooserUI wui = new WindowsFileChooserUI(fico);
wui.installUI(fico);
int returnVal = fico.showOpenDialog(null);
Run Code Online (Sandbox Code Playgroud)

pru*_*nge 5

当 UI 对象初始化时,它会尝试从它期望存在的 UI 管理器(FileChooser.viewMenuIcon属性)中读取一些 UI 默认值,这些默认值始终存在于 Windows L&F 下,但不存在于 Metal 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();
Run Code Online (Sandbox Code Playgroud)

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

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

//Second chooser uses default L&F
anotherChooserWithOriginalLaf.showOpenDialog(null);
Run Code Online (Sandbox Code Playgroud)