Vin*_*ash 1 java swing listener actionlistener windowlistener
当我按下取消按钮时,我希望窗口关闭,但它不起作用.
码:
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();
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果代码需要更改,请告诉我.
btnCancel.addActionListener()
所以当我按下取消按钮时,我的代码将工作并关闭应用程序.
不要使用窗口列表器,它在关闭时给出事件,尝试
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
Run Code Online (Sandbox Code Playgroud)
无需重写WindowListener方法,
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17880 次 |
| 最近记录: |