如何为需要不同方法参数的按钮使用一个动作监听器?

How to use one Action Listener for buttons that require different method parameters?

我想通过简单地调用一个动作侦听器来减少按钮动作侦听器的数量:

ActionListener calculatorListener = new ActionListener(){
             @Override
            public void actionPerformed(ActionEvent e) {
                int x = 9;
                calc.calculate(x);
            }
        };

JButton button9 = new JButton("9");
        buttonPanel.add(button9);

        button9.addActionListener(calculatorListener);

JButton button8 = new JButton("8");

buttonPanel.add(button8);

 button8.addActionListener(calculatorListener); //etc.....

我有许多不同的按钮,但需要一个 ActionListener 中的参数(例如 x)对于使用 ActionListener 的每个按钮都不同。有没有一种方法可以让动作侦听器检测到正在使用哪个 JButton?

有很多方法可以实现您的目标。这是一个相当简单明了的方法。

首先,让您的动作侦听器命名为 class,您可以使用参数构造它:

private class CalcListener implements ActionListener {
    private int x;
    private CalcListener(int x){
        this.x = x;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        calc.calculate(x);
    }
}

然后,像这样使用它:

button1.addActionListener(new CalcAction(1));
...
button8.addActionListener(new CalcAction(8));
button9.addActionListener(new CalcAction(9));