Search code examples
javaswingjava-7look-and-feeljfilechooser

JFileChooser does not react on pressing enter since java 7


I have a problem with the JFileChooser embedded in a JFrame. If I type a filename or regex into the textfield and press "enter" key nothing happens.

If I use the "open" button instead of enter it works. This problem occures since java 7 and only if I use the JFileChooser embedded. In the JFileChooser OpenDialog the "enter" key works.

It also works embedded if I use the Nimbus look and feel, using other look and feels it will not work.

I can reproduce this error on Windows and Linux system look and feels and on the CrossPlatformLookAndFeel (I think its called Metal).

Has anyone a solution for this problem?


Solution

  • After submitting a bug report to Oracle, but since this really annoying, I've been trying to figure this out for hours (over a course of several days). Ended up browsing the OpenJDK and Oracle source code for differences between my use of the JFileChooser component and their built-in showOpenDialog, etc, methods.

    I believe I have a reliable workaround that seems to work well for our application. Just a little background: we're using the JFileChooser component within a customized subclass of JDialog inside a JPanel (with GridBagLayout) and the "System" look and feel.

    Here's the single line of code that does the trick:

    dialog.getRootPane().setDefaultButton(chooser.getUI().getDefaultButton(chooser));
    

    Where

    • dialog is an instance of JDialog containing the JFileChooser component
    • chooser is an instance of JFileChooser

    The sample code above was used in the code demonstrating the issue (just before showing the modal dialog), but we have later moved the code to the constructor of our dialog subclass to make things easier. As of JRE 1.7.0_45, we're still facing the issue so hopefully this will be helpful if anyone else struggles with this.