0
這是我的代碼,但錯誤顯示實現的ActionListener不正確。我還聲明瞭這些按鈕,那麼如何讓系統退出?我做錯了什麼?在此先感謝如何實現ActionListener以使「退出」按鈕正常工作
import javax.swing.*;
import java.awt.*;
import java.awt.FlowLayout;
public class MyFrame extends JFrame implements ActionListener {
public MyFrame() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout());
JButton ExitBtn = new JButton();
ExitBtn.setText("Exit");
JButton Find = new JButton("Find");
JButton Clear = new JButton("Clear");
// add buttons to frame
add(ExitBtn);
add(Find);
add(Clear);
}
public void actionPerformed(ActionEvent e){
System.exit(0);
ExitBtn.addActionListener(this);
}
public static void main(String[] args) {
MyFrame mf = new MyFrame();
mf.pack();
mf.setVisible(true);
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
'Window#dispose'會是一個更好更簡單的選擇,假設該框架的defaultCloseOperation設置爲EXIT_ON_CLOSE – MadProgrammer
+1,使用這種方法,您將獲得與用戶單擊「關閉」按鈕時相同的行爲的框架,我認爲這是一件好事。有關更多信息,請參閱[關閉應用程序](http://tips4java.wordpress.com/2009/05/01/closing-an-application/)。您可以使用'ExitAction'作爲更通用的方式來創建「退出」按鈕。 – camickr