Following my previous two posts here and another one here, the following code
opens the regular file browser instead of the expanded one:
public class GuiHandler extends javax.swing.JFrame {
// data members
private DataParser xmlParser = new DataParser();
private File newFile;
JFileChooser jfc = new JFileChooser();
// more code
public void launchFileChooser() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
newFile = jfc.getSelectedFile();
}
});
}
// more code
private void XMLfilesBrowserActionPerformed(java.awt.event.ActionEvent evt) {
launchFileChooser();
xmlParser.getNodeListFromFile(newFile);
// here the code has the below problems
Problems:
- The code opens a regular file browser when I hit a button to
open XML file; it still allows me to pick a file. - It throws an exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: File cannot be null
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:198)
Why does it open the regular browser if jfc is a data member, and when it’s a local
variable, the expanded one opens?
Concerning the regular versus expanded file chooser, make sure to call
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());before callingnew JFileChooser();. Actually, unless you allow users to change the look and feel (L&F) during application execution, set the L&F close to the beginning of application execution, like in themainmethod, before creating any Swing components. From my experience, not doing so can cause some odd UI behavior.When you have
JFileChooseras a local variable inlaunchFileChooser,UIManager.setLookAndFeelis called beforenew JFileChooser. WhenJFileChooseris a class member variable (a.k.a. data member),UIManager.setLookAndFeelis called afternew JFileChooser; in the latter case, theJFileChooseris created when an instance ofGuiHandleris instantiated.Concerning the
IllegalArgumentExceptionuseSwingUtilities.invokeAndWaitinlaunchFileChooserinstead ofSwingUtilities.invokeLater. Better yet, if you’re surelaunchFileChooserwill always occur on the event dispatch thread, there’s no need to call eitherSwingUtilities.invokeAndWaitorSwingUtilities.invokeLater.You also may want to use a file filter:
The following is an SSCE that demonstrates the concepts discussed above: