I get this run-time error, i am trying to make the java file chooser look like the windows one.
error code:
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)
Code:
JFileChooser fico = new JFileChooser();
WindowsFileChooserUI wui = new WindowsFileChooserUI(fico);
wui.installUI(fico);
int returnVal = fico.showOpenDialog(null);
When the UI object is initializing, it is trying to read some UI defaults from the UI manager that it expects to exist (the FileChooser.viewMenuIcon
property), which always exists under the Windows L&F but not under the Metal L&F.
Firstly, a warning. Mixing multiple L&F at the same time in Swing is hazardous. Swing is really only meant to be run with one L&F at a time.
A better way to set up a 'special' file chooser is to initialize everything through the UI manager when your application starts up.
//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();
Now you have two components with two different L&Fs which you can use.
//First chooser opens with windows L&F
windowsChooser.showOpenDialog(null);
//Second chooser uses default L&F
anotherChooserWithOriginalLaf.showOpenDialog(null);