所以我有点想要掌握听众和诸如此类的概念 在我的代码中我得到错误:
The type eventHandle.ButtonListener must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)
为什么会这样?
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class eventHandle extends JApplet{
private JButton onebutton;
private JButton twobutton;
private JLabel label;
private int flax;
private JPanel panel;
public void init(){
flax = 0;
onebutton = new JButton("click to add 1");
onebutton.addActionListener(new ButtonListener());
twobutton = new JButton("click to add 2");
twobutton.addActionListener(new ButtonListener());
label = new JLabel("count: " + flax);
panel = new JPanel();
panel.setLayout(new GridLayout(1,2));
panel.add(onebutton);
panel.add(twobutton);
Container contain = getContentPane();
contain.setLayout(new GridLayout(2,1));
contain.add(label);
contain.add(panel);
setSize(400,300);
}
public class ButtonListener implements ActionListener{
public void actionPerformed(Action event){
if (event == onebutton){
flax += 1;
}
if (event == twobutton){
flax += 2;
}
label.setText("count: " + flax);
}
}
}
答案 0 :(得分:1)
你没有完全覆盖ActionListener接口,你必须这样做
public void actionPerformed(ActionEvent event){
而不是
public void actionPerformed(Action event){
答案 1 :(得分:1)
使用ActionEvent
代替Action
并比较JButton
对象使用event.getSource()
。
public void actionPerformed(ActionEvent event){
if (event.getSource() == onebutton){
flax += 1;
}
if (event.getSource() == twobutton){
flax += 2;
}
label.setText("count: " + flax);
}
更多https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html