[英]why won't ButtonListener work?
所以我有点试图掌握侦听器的概念,但在我的代码中却出现了这样的错误:
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);
}
}
}
您不能很好地覆盖ActionListener接口,您必须做
public void actionPerformed(ActionEvent event){
代替
public void actionPerformed(Action event){
使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.