我创建了三个类:
public class Gui extends JFrame {
private final JButton buttonClose = new JButton("Close");
private final MyButtonListener buttonListener = new MyButtonListener(this);
private final MyWindowListener windowListener = new MyWindowListener();
public SwitchGuiExtListeners() {
super("Switch");
setSize(200, 150);
setLayout(new BorderLayout());
add(buttonClose, BorderLayout.EAST);
buttonClose.addActionListener(this.buttonListener);
this.addWindowListener(this.windowListener);
setVisible(true);
}
public JButton getButtonClose() {
return buttonClose;
}
}
public class SwitchGuiWindowListener implements WindowListener{
...
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
...
}
public class MyButtonListener implements ActionListener {
private final Gui gui;
public MyButtonListener (final Gui gui) {
this.gui = gui;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == gui.getButtonClose()){
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//System.exit(0);
}
}
}
如果我使用gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);我的画面没有关闭。但是当我使用System.exit(0)时,它可以工作。为什么我不能使用setDefaultCloseOperation(..)?
答案 0 :(得分:2)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
未关闭JFrame。它只是告诉单击窗口右上角的关闭按钮时JFrame必须退出,即只设置行为但触发退出。
要关闭JFrame,请使用以下内容:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));