如何将Action Listener直接放在扩展Button
的类的定义中?
如果创建了类Button
的对象,那么我们可以简单地使用一个无穷的内部类:
b = new Button("Click me");
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("stringToPrint");
}
}
);
how to do the same in below :
class CustomizedButton extends Button{
String customClass;
Button(String stringToPrint){
super(customClass); //customClass is also button name
this customString = stringToPrint;
}
/*this.addActionListener( //don't work this way
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(customClass);//use outer(?) field
}
}
);*/
}
我需要创建20个几乎相同但略有不同的按钮,因此匿名内部太长
答案 0 :(得分:2)
您可以声明一个私有嵌套类,如下所示:
public class CustomizedButton extends Button{
String customClass;
CustomizedButton(String stringToPrint){
super(customClass); //customClass is also button name
this.customString = stringToPrint;
addActionListener(new MyListener());
}
private class MyListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO: listener code here
}
}
}
但它与使用匿名内部类或lambda没有太大区别:
public class CustomizedButton extends Button{
String customClass;
CustomizedButton(String stringToPrint){
super(customClass); //customClass is also button name
this.customString = stringToPrint;
addActionListener(e -> myListenerCode(e));
}
private void myListenerCode(ActionEvent e) {
// TODO: listener code here
}
}
话虽如此,我想到了其他问题:
例如,AbstractAction类可能类似于:
public class CustomizedAction extends AbstractAction{
String text;
CustomizedAction(String text, int mnemonic){
super(text); //text is also button name
this.text = text;
putValue(MNEMONIC_KEY, mnemonic); // for alt-key short cut if desired
}
@Override
public void actionPerformed(ActionEvent e) {
String currentName = getValue(NAME); // same value as the text field
System.out.println(currentName);
// TODO: more listener code here
}
}
可以像这样使用:
JButton button = new JButton(new CustomizedAction("Foo", KeyEvent.VK_F));