I have a Java Swing application where some data are presented in editable combo boxes. The combo boxes are displayed in a separate frame. The frame is opened ad hoc when a button is clicked. The frame has no window decoration and is closed/disposed when it loses its focus (i.e., the user clicks outside the window). When the frame is closed, the combo box contents are saved.
This works well, except for the last edited combo box. For the last combo box, the contents are still being edited when the window loses focus. The #getSelectedItem()
method of the JComboBox
returns null because the editing was not completed before the window lost focus. At least I assume that is what is happening.
How can I finish the editing and select the edited text when the window loses focus before disposing the frame?
Here is a minimal reproducible example:
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
class Example extends JFrame {
public static void main(String[] args) {
new Example();
}
public Example() {
Container c = getContentPane();
JPanel panel = new JPanel();
JComboBox<String> box1 = new JComboBox<String>();
box1.setEditable(true);
panel.add(box1);
JComboBox<String> box2 = new JComboBox<String>();
box2.setEditable(true);
panel.add(box2);
c.add(panel);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.addWindowFocusListener(new WindowAdapter() {
public void windowLostFocus(WindowEvent e) {
System.out.println("Field 1: " + box1.getSelectedItem() + ". Field 2: " + box2.getSelectedItem() + ".");
System.exit(0);
}
});
}
}
The example class will display a frame with two editable combo boxes. If you click outside of the frame, the application will exit after printing the contents of the two combo boxes. You will notice that the last edited combo box prints null
if it was visited only once.
Add a FocusListener
to the combo box text field that is used as the editor. An event should be generated when the text field loses focus.
See the getEditor()
method of the JComboBox
for access to the editor component.