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

时间:2016-07-28 16:32:08

标签: java button applet

我正在填写过去的纸质考试问题,并要求创建一个小程序,在中心显示绿色方块,有三个按钮+-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;
    }
}

2 个答案:

答案 0 :(得分:0)

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

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

另一种选择是检查按钮的字符串,例如

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

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

答案 1 :(得分:0)

您可以使用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){
            }

即使在开关案例陈述中也是如此