gpt4 book ai didi

java - JFileChooser 失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:56:07 25 4
gpt4 key购买 nike

在我的代码中某个时候我有这段代码

void selectRoot() {
JFileChooser ch = new JFileChooser();
ch.showOpenDialog((JFrame)this);
}

这会抛出异常:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.Win32FileSystem.normalize(Win32FileSystem.java:164)
at java.io.Win32FileSystem.getUserPath(Win32FileSystem.java:296)
at java.io.Win32FileSystem.resolve(Win32FileSystem.java:312)
at java.io.File.getAbsolutePath(File.java:501)
at sun.awt.shell.Win32ShellFolder2.<init>(Win32ShellFolder2.java:291)
at sun.awt.shell.Win32ShellFolderManager2.createShellFolderFromRelativePIDL(Win32ShellFolderManager2.java:66)
at sun.awt.shell.Win32ShellFolderManager2.createShellFolder(Win32ShellFolderManager2.java:56)
at sun.awt.shell.Win32ShellFolderManager2.getRecent(Win32ShellFolderManager2.java:114)
at sun.awt.shell.Win32ShellFolderManager2.get(Win32ShellFolderManager2.java:251)
at sun.awt.shell.ShellFolder.get(ShellFolder.java:227)
at sun.swing.WindowsPlacesBar.<init>(WindowsPlacesBar.java:64)
at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.updateUseShellFolder(WindowsFileChooserUI.java:505)
at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installComponents(WindowsFileChooserUI.java:196)
at javax.swing.plaf.basic.BasicFileChooserUI.installUI(BasicFileChooserUI.java:136)
at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installUI(WindowsFileChooserUI.java:129)
at javax.swing.JComponent.setUI(JComponent.java:673)
at javax.swing.JFileChooser.updateUI(JFileChooser.java:1763)
at javax.swing.JFileChooser.setup(JFileChooser.java:360)
at javax.swing.JFileChooser.<init>(JFileChooser.java:333)
at javax.swing.JFileChooser.<init>(JFileChooser.java:286)
at my.pack.Main.selectRoot(Main.java:184)

查看 java.io.Win32FileSystem.normalize() 的源代码,(当前)路径似乎为空:

   public String normalize(String path) {
int n = path.length(); // Line: 164
char slash = this.slash;
char altSlash = this.altSlash;

如果我从程序中的另一个点运行 selectRoot(),它运行良好......

更新

伙计们,这真是一本关于编程陷阱的好书!

在我的原始代码中有一个 JTextField 保存实际路径并以这种方式进行初始化:

root = new JTextField();
root.setToolTipText("Root folder");
root.setText(System.clearProperty("user.dir"));

System.clearProperty() 清除系统属性(为空)返回旧值 (arrrghhhhhhh)。 clearProperty() 可能从自动完成中滑落。

谢谢大家。会给你一些投票......

最佳答案

确保从美国东部时间运行 showOpenDialog。如果您从另一个线程调用此方法,它可能会导致各种错误:

SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFileChooser ch = new JFileChooser();
ch.showOpenDialog((JFrame)this);
}
});

关于java - JFileChooser 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6584750/

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