这是我的代码,但错误显示实现的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);
}
}
答案 0 :(得分:1)
的onClick:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
答案 1 :(得分:1)
我认为您应该将ExitBtn.addActionListener(this)调用移动到MyFrame类的构造函数,以便它看起来像这样:
JButton ExitBtn = new JButton();
ExitBtn.setText("Exit");
ExitBtn.addActionListener(this)
和actionPermormed方法如下所示:
@Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}