Iam trying to set the directory which my JFileChooser
should show. Iam trying to work with the method 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);
}
}
}
Here is the weird part:
When I run my program everything works. But when I try to run it again, it sometimes throws a NullPointerException
. This can happen after the first re-run, or it can work 10 times in a row. There is no pattern. Iam not modifying my C:
directory.
This is the whole code , this is no snipped.
The full stacktrace:
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)
When I try to set the directory via the constructor JFileChooser(String currentDirectoryPath)
, everything works. Even if I try it 100 times in a row (trust me, I tried it 100 times). Code:
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();
}
}
So there has to be something wrong with chooser.setCurrentDirectory(new File("C:\\\\"));
There is no way for me to work with the constructor. I do have to set the currentDirectory.
When the Exception
is thrown, getCurrentDirectory()
returns C:\\
, even if my FileChooser
is not showing this directory.
Does anyone have an idea whats going on here?
Thanks to Andrew Thompson , I got it working. I had to replace
chooser.setCurrentDirectory(file);
with
SwingUtilities.invokeLater(() -> chooser.setCurrentDirectory(new File("C:\\")));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.