I have a fairly basic JFrame here, and I want to make the window close automatically when the user clicks outside it. Is it possible to make the window close when the user clicks outside it (by somehow detecting clicks outside the window?).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExampleJFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("How can I make this window close when I click outside it?");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JLabel jlbempty = new JLabel("");
jlbempty.setPreferredSize(new Dimension(200, 200));
frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Detecting a click outside the frame is difficult, as it can be a click on any other application to which java has no access.
You could try with a
FocusListeneras shown belowThis works for this simple use-case. Not yet sure what will happen if you put e.g. a
JTextFieldin the frame and the textfield gets focus. If that causes theJFrameto loose focus as well, your application will rather be useless.Edit
A bit more robust solution might be to attach a listener to the
KeyboardFocusManagerThis allows to switch focus between the different text fields in the frame.