檢測幀外的點擊很困難,因爲它可以是任何其他Java無法訪問的應用程序的點擊。
你可以用FocusListener
嘗試如下圖所示
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class AutoCloseFrameDemo {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.addFocusListener(new FocusListener() {
private boolean gained = false;
@Override
public void focusGained(FocusEvent e) {
gained = true;
}
@Override
public void focusLost(FocusEvent e) {
if (gained){
frame.dispose();
}
}
});
frame.add(new JLabel("testlabel"));
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
這適用於這個簡單的用例。還不確定如果您將例如在框架中的JTextField
和文本字段獲得焦點。如果這導致JFrame
也失去焦點,那麼您的應用程序將毫無用處。
編輯
更多的位健壯的解決方案可能是給收聽者附加到KeyboardFocusManager
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class AutoCloseFrameDemo {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
KeyboardFocusManager.getCurrentKeyboardFocusManager().
addVetoableChangeListener("focusedWindow",
new VetoableChangeListener() {
private boolean gained = false;
@Override
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (evt.getNewValue() == frame) {
gained = true;
}
if (gained && evt.getNewValue() != frame) {
frame.dispose();
}
}
});
frame.add(new JTextField(10), BorderLayout.NORTH);
frame.add(new JTextField(10), BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
這允許在幀中的不同的文本字段之間切換焦點。
我希望這是與我的問題有關:http://stackoverflow.com/questions/5717716/detecting-focus-on-frame-components-in-swing –
其實這個問題包含你需要的確切答案.. –
這不適用於所有情況,但是一旦它失去焦點,您可以關閉相框。 – Aaron