Search code examples
javaswingjtextfieldmouse-listenersfocuslistener

How to show the Open File dialog box when a user clicks on a JTextField?


I want to show the Open File dialog box when a user clicks on a JTextField. When I added the following code (which I removed for now)...

 this.textField.addFocusListener(new FocusListener() {

    public void focusGained(FocusEvent event) {
      // Show the Open File dialog box.
      // Same as lines 86-93 in the link below.
    }

    public void focusLost(FocusEvent event) {
      // Do nothing.
    }

 }

(Code here.)

...it seems that after the user selects a file and then clicks on the OK button, the Open File dialog box will appear again, because I assume that the focus is still on the JTextField. The same thing happens when the user clicks on the Cancel button.

How do I fix this problem? Your advice will be greatly appreciated!


Solution

  • The problem is when the file chooser dialog appears, it takes focus. When it closes (I assume) you refocus the textfield (or the focus manager is returning focus to it), which triggers the focus event again.

    I can think of two solutions. One, if you only want the file dialog to appear when the user "clicks" the field, use a mouse listener instead.

    Two, use a internal flag to monitor that the current operational state. This might be more difficult to implement given the nature of the events processing