所以我试图在我的代码中理解侦听器的概念,我得到了错误:
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);
}
}
}发布于 2015-12-06 03:49:18
您没有很好地覆盖ActionListener接口,您必须这样做
public void actionPerformed(ActionEvent event){而不是
public void actionPerformed(Action event){发布于 2015-12-06 04:08:23
使用ActionEvent代替Action,并使用event.getSource()比较JButton对象。
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
https://stackoverflow.com/questions/34109839
复制相似问题