这个事件监听哪里错了,怎么搞不了?有错误,一直报错,怎么回事?

这个事件监听哪里错了,怎么搞不了?有错误,一直报错,怎么回事?

img

回答:书写的有问题,把你的代码发一下,或者你简单按照这样书写试试

img

package test;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author bbyh
 * @date 2022/12/25 0025 12:25
 * @description
 */
public class Test extends JFrame {

    public Test() {
        new JButton().addActionListener(new MyActionListener());
    }

    private static class MyActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("测试");
        }
    }

    public static void main(String[] args) {

    }
}

你这应该存在两个问题

  1. 创建类应该是 new 类名(),你第一个报错没有加括号。
  2. 内部类应该定义在方法外面,你这个写到方法体里面了。