[英]Java: Cancel Button does not close the window for JFrame
I want the window to close when I press on Cancel button, but it's not working. 我希望在我按下“取消”按钮时关闭窗口,但是它不起作用。
Code: 码:
public class FirstClass{
private JFrame frame;
private JButton btnCancel;
public FirstClass() {
frame = new JFrame("GRIIS Data Transfer [Mobile to PC]");
frame.setBounds(200,200,900,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
btnCancel = new JButton("Cancel");
btnCancel.setBounds(800, 5, 85, 25);
frame.add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
});
}//end of constructor
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
FirstClass window = new FirstClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Please let me know in case of changes needed in the code. 如果代码需要更改,请告诉我。
btnCancel.addActionListener()
btnCancel.addActionListener()
so my code will work and close the application when I press on Cancel button. 因此,当我按“取消”按钮时,我的代码将起作用并关闭应用程序。
Dont use window listner it gives event at time of closing, try 不要在关闭时使用窗口列表器给它事件,请尝试
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
No need to override WindowListener method, 无需重写WindowListener方法,
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.