首页 > 解决方案 > 使用外部资源时未解决的编译错误

问题描述

我收到一个未解决的编译错误。收到这些错误:

AbstractButton 类型中的方法 addActionListener(ActionListener) 不适用于参数 (Gui.HandlerClass) AbstractButton 类型中的方法 addActionListener(ActionListener) 不适用于参数 (Gui.HandlerClass) ActionListener 无法解析为 ActionEvent 类型无法解析为类型

import java.awt.*;
import javax.swing.*;
public class Gui extends JFrame{

private JButton reg;
private JButton custom;

public Gui(){
    super("The title");
    setLayout(new FlowLayout());

    reg = new JButton("Regular Button");
    add(reg);

    Icon b = new ImageIcon(getClass().getResource("foto 1.png"));
    Icon c = new ImageIcon(getClass().getResource("foto 2.png"));
    custom = new JButton("Custom", b);
    custom.setRolloverIcon(c);
    add(custom);

    HandlerClass handler = new HandlerClass();
    reg.addActionListener(handler);
    custom.addActionListener(handler);
}

private class HandlerClass implements ActionListener{
    public void actionPerformed(ActionEvent event) {
    JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
    }
}
}

标签: actionlistenereventhandleractionevent

解决方案


避免在导入中使用 *。您的问题是没有导入类ActionListenerActionEvent因此,您必须导入它们:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

另外,你用的是什么IDE?大多数 IDE 会发现问题并建议您进行修复。


推荐阅读