--------------------Configuration: JDK version 1.4 <Default>-------------------- D:\Program Files\JCreator Pro\MyProjects\Bath\Counter1\bb.java:28: cannot resolve symbol symbol : class BHandle location: class Test button.addActionListener(new BHandle()); // 增加按键相应 ^ D:\Program Files\JCreator Pro\MyProjects\Bath\Counter1\bb.java:33: local variable button is accessed from within inner class; needs to be declared final button.setBackground(Color.red); ^ 2 errorsProcess completed.
然而你用的很明显是ActionListener,这是对鼠标点击事件的一个简化接口,如果只是简单的点击事件,直接addActionListener就可以了
如果要实现对鼠标其他事件的监听,且你添加的是MouseListener,则必须实现MouseListener接口中的每一个方法
另一种较常用且简便的方法是注册一个继承自MouseAdapter的类,因为MouseAdapter实现了MouseListener接口的所有方法,所以你只需重写特定的方法来实现特定的鼠标操作就可以了.
import java.awt.event.*;public class bb
{
public static void main(String[] args)
{
Test t = new Test("testing");
t.setSize(200, 200);
t.setVisible(true);
}
}class Test extends Frame
{
private Button button;
public Test(String str)
{
super(str);
this.add(button(), BorderLayout.NORTH);
}
private Button button() {
Button button = new Button("well");
button.addActionListener(new BHandle()); // 增加按键相应 class BHandle implements ActionListener {
public void actionPerformed(ActionEvent e)
{
button.setBackground(Color.red);
setBackground(Color.cyan);
}
}
return button;
}// Button button()
}
D:\Program Files\JCreator Pro\MyProjects\Bath\Counter1\bb.java:28: cannot resolve symbol
symbol : class BHandle
location: class Test
button.addActionListener(new BHandle()); // 增加按键相应
^
D:\Program Files\JCreator Pro\MyProjects\Bath\Counter1\bb.java:33: local variable button is accessed from within inner class; needs to be declared final
button.setBackground(Color.red);
^
2 errorsProcess completed.
把class BHandle从private Button button{}拿出来,作为class bb 的 inner class. Button button = new Button("well"); 声明为class bb 的member
Button button = new Button("well");
button.addActionListener(new ActtionListener(){ public void actionPerformed(ActionEvent e)
{
button.setBackground(Color.red);
setBackground(Color.cyan);
}
});
class Test extends Frame implements Actionlistener
import java.awt.event.*;public class bb
{
public static void main(String[] args)
{
Test t = new Test("testing");
t.setSize(200, 200);
t.setVisible(true);
}
}class Test extends Frame
{
private Button button1=new BHandle(this); public Test(String str)
{
super(str);
this.add(button1, BorderLayout.NORTH);
} class BHandle extends Button implements ActionListener {
Frame frame;
BHandle(){
super("well");
addActionListener(this);// 增加按键相应
}
BHandle(Frame f){
super("well");
frame=f;
addActionListener(this);// 增加按键相应
} public void actionPerformed(ActionEvent e)
{
setBackground(Color.red);
frame.setBackground(Color.cyan);
}
}
}
public void actionPerformed(ActionEvent e){
……
}
});