How can I make a text field lose focus before application quits?

287 Views Asked by At

I have an application with a JFrame containing text fields. When text in a field is modified, and the field gets a focusLost event, it immediately writes its contents to an external database.

However, if the user quits the application while a field is still focused, the focusLost message is not sent and the modified data is not saved.

How can I force the loss of focus on a field, perhaps in a windowClosing method in my WindowListener? I tried using requestFocusInWindow() in that method, but it did not help.

3

There are 3 best solutions below

2
On

Why not just call the same method that writes the contents to the external database from within the windowClosing method of your window listener?

@Override
public void windowClosing(WindowEvent e) {
    // call write to DB method
    System.exit(0);
} 
1
On

Another way of going about it:
Change the setDefaultCloseOperation of the JFrame to DO_NOTHING_ON_CLOSE, and show a confirmation dialog when the user wants to close the window. The dialog will receive focus, triggering the focusLost method on the textfield's FocusListener.

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            int result = JOptionPane
                    .showConfirmDialog(null, "Are you sure?", 
                            "Confirm exit", JOptionPane.YES_NO_OPTION);
                if(result == 0) {
                    System.exit(0);
                }
            }              
        }
    });

(Note: If you go with this method, be sure you don't exit in the middle of writing to the DB.)

0
On

Pending a better answer that may be forthcoming from someone more experienced that I am, here's what I'm doing.

In my windowClosing() method in my WindowListener, I put:

dispatchEvent(new FocusEvent(getFocusOwner(), FocusEvent.FOCUS_LOST));