gpt4 book ai didi

java - 使用 WindowsFileChooserUI 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 03:49:03 25 4
gpt4 key购买 nike

我遇到这个运行时错误,我试图让 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);

最佳答案

当 UI 对象正在初始化时,它会尝试从 UI 管理器中读取一些它期望存在的 UI 默认值(FileChooser.viewMenuIcon 属性),这些默认值始终存在于 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();

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

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

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

关于java - 使用 WindowsFileChooserUI 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com