繁体   English   中英

JFileChooser设置目录

[英]JFileChooser set directory

我试图设置我的JFileChooser应该显示的目录。 我试图使用方法setCurrentDirectory

public class FileChooser {
    public static void main(String[] args) {        
        JFrame jf = new JFrame();
        JFileChooser chooser = new JFileChooser();

        jf.add(chooser);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();

        File file = new File("C:\\");

        if(file.exists() && chooser != null) {
            chooser.setCurrentDirectory(file);
        }
    }
}

这是奇怪的部分:

当我运行程序时,一切正常。 但是,当我尝试再次运行它时,有时会抛出NullPointerException 第一次重新运行后可能会发生这种情况,也可能连续运行10次。 没有模式。 我没有修改我的C:目录。

这是整个代码 ,这是不完整的。

完整的堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1368)
at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1311)
at javax.swing.plaf.basic.BasicListUI.getCellBounds(BasicListUI.java:952)
at javax.swing.JList.getCellBounds(JList.java:1637)
at javax.swing.JList.ensureIndexIsVisible(JList.java:1149)
at sun.swing.FilePane.ensureIndexIsVisible(FilePane.java:1708)
at sun.swing.FilePane.doDirectoryChanged(FilePane.java:1631)
at sun.swing.FilePane.propertyChange(FilePane.java:1681)
at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
at java.awt.Component.firePropertyChange(Component.java:8434)
at javax.swing.JFileChooser.setCurrentDirectory(JFileChooser.java:598)
at filechooser.FileChooser.main(FileChooser.java:21)

当我尝试通过构造函数JFileChooser(String currentDirectoryPath)设置目录时,一切正常。 即使我连续尝试了100次(相信我,我也尝试了100次)。 码:

public class FileChooser {
    public static void main(String[] args) {        
        JFrame jf = new JFrame();
        JFileChooser chooser = new JFileChooser("C:\\");

        jf.add(chooser);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
    }
}

所以chooser.setCurrentDirectory(new File("C:\\\\"));有问题chooser.setCurrentDirectory(new File("C:\\\\")); 我没有办法使用构造函数。 我必须设置currentDirectory。

抛出Exception ,即使我的FileChooser没有显示此目录, getCurrentDirectory()也会返回C:\\

有人知道这里发生了什么吗?

多亏了Andrew Thompson ,我才开始工作。 我不得不更换

chooser.setCurrentDirectory(file);

SwingUtilities.invokeLater(() -> chooser.setCurrentDirectory(new File("C:\\")));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM