java addActionListener不工作
我遵循了一个关于如何做到这一点的教程-以下是我使用的代码:
package soundboard;
import javax.swing.*;
import java.awt.event.*;
public class Soundboard {
JButton Button1;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
Button1 = new JButton("1");
Button1.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(Button1);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent event){
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}
代码似乎不起作用。有人能解释一下原因吗
JPanel
用作背景。问题在于Button1.addActionListener(this);
,因为它说“this”不能转换为ActionListener
或类似的东西
# 1 楼答案
我成功了。下面是我如何实现它的,其他按钮还没有完成一件事。 所有代码都在一个名为Soundboard的类中,该类实现了ActionListener,而javax。荡秋千 JAVAawt。事件*也被导入
# 2 楼答案
如果要将类添加为Onclicklistener:
然后类必须实现适当的接口
ActionListener
,如下所示:编辑
如果您有多个按钮,需要单独实现,您可以使用匿名类:
# 3 楼答案
只能将
ActionListener
添加到带有addActionListener()
的Component
中你的类必须实现
ActionListener
,例如# 4 楼答案
如果要重写
actionPerformed
方法,需要实现ActionListener
接口: