简体   繁体   English

如何实现ActionListener以使Exit Button工作

[英]How to implement the ActionListener to get the Exit Button to work

Here is my code, but the error shows that the implemented ActionListener is not correct. 这是我的代码,但错误显示实现的ActionListener不正确。 I also declared the buttons so how do I make the system exit? 我还宣布了按钮,我该如何让系统退出? What did I do wrong? 我做错了什么? Thanks in advance 提前致谢

 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);

    }
    }

的onClick:

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

I think you should move the ExitBtn.addActionListener(this) call to the constructor of MyFrame class so that it looks like this: 我认为您应该将ExitBtn.addActionListener(this)调用移动到MyFrame类的构造函数,以便它看起来像这样:

    JButton ExitBtn = new JButton();
    ExitBtn.setText("Exit");
    ExitBtn.addActionListener(this)

and actionPermormed method looks like this: 和actionPermormed方法看起来像这样:

@Override
public void actionPerformed(ActionEvent e){
    System.exit(0);   
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM