在类中定义和ActionListener扩展Button

时间:2018-05-30 16:17:19

标签: java swing

如何将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个几乎相同但略有不同的按钮,因此匿名内部太长

1 个答案:

答案 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
    }

}

话虽如此,我想到了其他问题:

  • 通常最好赞成合成而不是继承。我敢打赌你真正想要的是某种工厂方法,用听众创建你的按钮
  • 为什么在20岁以上的时候使用AWT组件,例如java.awt.Button类?为什么不使用Swing JButton?
  • 如果您使用Swing JButtons,最好是创建自定义Action而不是扩展JButton。操作可以保存和更改许多按钮属性,包括监听器,显示的文本,图标,工具提示文本(在悬停时显示)....
  • 就此而言,如果这是一个新项目,您应该支持JavaFX,因为这是当前支持最佳的Java GUI库。

例如,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));