如何在将 JComponent 的实例化添加到 JContainer 时添加 ActionListener?

How to add an ActionListener while adding an Instantiation of a JComponent to a JContainer?

我想通过这样做来添加组件:

frame.add(new JButton("Click here"));

但是我该如何添加一个 ActionListener 呢?我认为这可能与 AbstractButton 实例化有关?

我不想实例化 JButton 变量,所以我不确定这是否是正确的方法:

    frame.add(new JButton("Click here"), new AbstractButton() {
        public void addActionListener(ActionListener l) {
            // do stuff
        }
    });

如果可行,我需要将其添加到 actionPerformed() 中,如下所示:

JButton button = new JButton("Click here");
button.addActionListener(this);

请注意,我并不是要为 ActionListener 做匿名内部 class,而只是将组件添加到 actionPerformed() 的代码简化。

有什么办法吗?

谢谢

三个选项:

选项一:我认为最干净

    JFrame frame = new JFrame();

    JButton button = new JButton("Click Here");
    frame.add(button);
    button.addActionListener(this);

选项 2 匿名 class

    JFrame frame = new JFrame();

    JButton button = new JButton("Click Here");
    frame.add(button);

    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked");
        }
});

选项 3

不推荐这样做,丑陋并且有意想不到的副作用(想象再次调用添加)。但是您要求一种直接在 add.

中执行此操作的方法
    JFrame frame = new JFrame();

    JButton button = new JButton("Click Here");
    frame.add(new JButton("Click Here"){
        @Override
        public void addActionListener(ActionListener l) {
            super.addActionListener(YourClass.this);
        }
    });