我一直在努力为按钮设置 Action 监听器,但我不明白为什么。我引用了很多教程,但我一直遇到 must be declared abstract or must implement abstract method ..... 错误。我看过类似的主题来解决这个问题,但没有什么能真正帮助我解决问题。任何帮助都会很棒。这是一个与我正在做的类似的简短示例:
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.*;
public class Kitty {
private static void mainFrame() {
JFrame mainFrame = new JFrame("Kitty");
JPanel mainPanel = new JPanel();
mainFrame.setSize(200,200);
mainFrame.setResizable(false);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
JButton button1 = new JButton("Pet the kitty");
mainPanel.add(button1);
button1.addActionListener(new ActionListener(){
// Line above (Specifically ActionListener) says Class 'Anonymous' must either be declared abstract or
// implement abstract method 'actionPerformed(ActionEvent)' in 'ActionListener'
public void actionPerformed(ActionEvent event){
System.out.println("Purrrrrr....");
}
});
}
public static void main(String[] args) {
mainFrame();
}
}
最佳答案
您导入了错误的 ActionEvent 类。这就是为什么说您没有实现该方法的原因。使用 java.awt.event.ActionEvent。
关于Java 错误 : Class 'Anonymous' must either be declared abstract or implement abstract method 'actionPerformed(ActionEvent)' in 'ActionListener' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831182/