如何提供单个按钮处理程序对象

How do I provide a single button handler object

我正在完成一个过去的试卷问题,它要求创建一个在中心显示绿色方块的小程序,其中包含三个按钮 +-reset,但是,我试图使当单击任何按钮时,程序基本上应该弄清楚按下了哪个按钮。我知道您会使用 e.getSource() 但我不确定该怎么做。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Square extends JApplet {

int size = 100;

public void init() {
    JButton increase = new JButton("+");
    JButton reduce = new JButton("-");
    JButton reset = new JButton("reset");

    SquarePanel panel = new SquarePanel(this);
    JPanel butPanel = new JPanel();

    butPanel.add(increase);
    butPanel.add(reduce);
    butPanel.add(reset);

    add(butPanel, BorderLayout.NORTH);
    add(panel, BorderLayout.CENTER);

    ButtonHandler bh1 = new ButtonHandler(this, 0);
    ButtonHandler bh2 = new ButtonHandler(this, 1);
    ButtonHandler bh3 = new ButtonHandler(this, 2);

    increase.addActionListener(bh1);
    reduce.addActionListener(bh2);
    reset.addActionListener(bh3);
}
}

class SquarePanel extends JPanel {
Square theApplet;

SquarePanel(Square app) {
    theApplet = app;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.green);
    g.fillRect(10, 10, theApplet.size, theApplet.size);
}
}

class ButtonHandler implements ActionListener {
Square theApplet;
int number;

ButtonHandler(Square app, int num) {
    theApplet = app;
    number = num;
}

public void actionPerformed(ActionEvent e) {
    switch (number) {
        case 0:
            theApplet.size = theApplet.size + 10;
            theApplet.repaint();
            break;
        case 1:
            if (theApplet.size > 10) {
                theApplet.size = theApplet.size - 10;
                theApplet.repaint();
            }
            break;
        case 2:
            theApplet.size = 100;
            theApplet.repaint();
            break;
    }
}

这不是最好的方法,但根据您当前的代码,您可以简单地比较对象引用。您需要传递对按钮的引用或以其他方式访问它们。例如

if(e.getSource() == increase) { \do something on increase}

另一种方法是检查按钮的字符串,例如

if(((JButton)e.getSource()).getText().equals("+")){ \do something on increase}

您可以在 Java 8 的 switch 语句中使用字符串,但如果您使用的是 Java 7 或更低版本,则它必须是 if 语句。

您可以在下面的示例中使用 if then else 语句

            if(e.getSource()==bh1){
                    //your codes for what should happen
            }else if(e.getSource()==bh2){

            }else if(e.getSource()==bh3){

            }else if(e.getSource()==bh4){
            }

或者甚至在 switch case 语句中