当用户单击它时,我JFrame
想要关闭它。我有两个JTextFields
和一个JButton
(用户名、密码、提交)。当我给他们所有的FocusListener
时候,只要用户从一个字段转到另一个字段,窗口就会关闭。如何允许用户从一个字段转到另一个字段,并且只有在用户单击弹出窗口的任何位置时才关闭它?
public class LoginForm {
static JTextField userName;
static JTextField password;
static JButton submit;
JFrame main;
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
UserSession session;
public LoginForm(){
Handler handle = new Handler(); //inner class
LoginFormFocusListener fl = new LoginFormFocusListener(); //inner class
main = new JFrame("Please Login");
main.setUndecorated(true);
main.setBounds((dim.width/2) - (500/2),(dim.height/2) - (150/2),500,150);
main.setVisible(true);
main.setAlwaysOnTop(true);
main.setResizable(false);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
userName = new JTextField(10);
password = new JTextField(10);
main.setLayout(new GridLayout(0,1));
JPanel panel = new JPanel();
main.add(panel);
panel.add(new JLabel("Username: "));
panel.add(userName);
panel.add(new JLabel("Password: "));
panel.add(password);
submit = new JButton("Submit");
panel.add(submit);
userName.addFocusListener(fl);
password.addFocusListener(fl);
submit.addFocusListener(fl);
submit.addActionListener(handle);
}
}
...(不重要的方法和“处理程序”类省略)
public class LoginFormFocusListener implements FocusListener{
public void focusGained(FocusEvent fe) {
System.out.println("focus gained...");
System.out.println("click off of this window to close...");
}
public void focusLost(FocusEvent fe){
System.out.println("focus lost...");
WindowEvent winEvt = new WindowEvent(main, 0);
winEvt.getWindow().dispose();
}
}
//test
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new LoginForm();
}
});
}