public void init() {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e){
String name =
((JButton)e.getSource()).getText();
t.setText(name + " Pressed");
}
};
b1.addActionListener(al);
add(b1);
b2.addActionListener(al);
add(b2);
add(t);
}
RT,新建了ActionListener对象后,为什么在后面更了一个方法,还用{}括起来了?
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e){
String name =
((JButton)e.getSource()).getText();
t.setText(name + " Pressed");
}
};
b1.addActionListener(al);
add(b1);
b2.addActionListener(al);
add(b2);
add(t);
}
RT,新建了ActionListener对象后,为什么在后面更了一个方法,还用{}括起来了?
就是一个继承或实现了ActionListener的无名称的类
Interface i=new Interface(){};大括号里要写Interface未实现的方法
new Interface(){};相当于是Interface的子实现,但是没有名字,因此叫匿名类
new Interface(){};因为继承了Interface,Interface的引用可以指向它