用JFrame写的java小应用是直接带有窗口的,在main()中加上setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)。
如果想写点击事件来实现关闭窗口,试试 System.exit(0);
添加按钮侦听器addActionListener(),当按下按钮之后,就退出程序。
button.addActionListener(new ActionLister(){
void actionPerformed(ActionEvent e)
{System.exit(0);} );
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
退出程序的窗口事件监听
/////////////源码加注释...................>>>>>>>>>>>>>>>>>
package GUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class TestButtonExit {
private JButton exitButton;
private JFrame frame;
private JPanel panel;
public TestButtonExit() {
//初始化组件
frame = new JFrame();
panel = new JPanel();
exitButton = new JButton("测试退出程序");
//添加组件
frame.add(panel);
panel.add(exitButton);
frame.setVisible(true);//设置窗口可见
frame.setSize(400,400);//设置大小
frame.setLocationRelativeTo(null);//相对居中显示...
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭动作
//为按钮添加监听器
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null,"程序即将退出...");
System.exit(0);
}
});
}
public static void main(String[] args) {
new TestButtonExit();
}
}