1

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!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84
  • 2
    Do you really want to show a file chooser when the user places its cursor in a text field. That is totally unexpected behavior. Why not make it a button ? – Robin Jul 22 '12 at 10:34

1 Answers1

2

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    @denshaotoko an example of mouse listener: http://stackoverflow.com/questions/4323773/java-how-do-i-do-a-onclick-for-textfield. if you only want to implement part of the methods in the interface, check the accepted answer in the following post use mouse adapter. it shows example of just what is needed : http://stackoverflow.com/questions/10133366/how-to-clear-jtextfield-when-mouse-clicks-the-jtextfield –  Jul 22 '12 at 07:06