如何修改附加到几个JButton的动作侦听器的参数?

时间:2019-04-30 01:57:20

标签: java arrays jbutton actionlistener

我有一个作业,我必须为绘画应用程序项目创建和按钮数组,并且一切都已完成,但是我一直在分配/引用/修改动作监听器。

(据说)它的工作方式是我有一个循环,该循环创建,分配名称并将名为myShapes的JButton数组添加到动作侦听器。由此,我应该将动作侦听器命名为listener();。给每个jbutton一个int 1-6,设置当前的actionPerformed状态。

int actionNum = 1;

ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        currentAction = actionNum;
    }
};  


//........................................................................

String[] myShapesName = {"brushBut", "lineBut", "ellipseBut", "rectBut", "strokeBut", "fillBut"};
//String[] myLisName = {"brushButL", "lineButL", "ellipseButL", "rectButL", "strokeButL", "fillButL"};

JButton[][] myShapes = new JButton[3][2];
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        myShapes[i][j] = new JButton();
        myShapes[i][j].setBounds(0, 0, 50, 50);//(100, 200);
        myShapes[i][j].setName(myShapesName[i+j]);
        myShapes[i][j].setBackground(null);
        myShapes[i][j].putClientProperty("id",

        String.valueOf(myShapesName[i+j]).concat(String.valueOf(j)));
        MyShapesBox.add(myShapes[i][j]);
        System.out.println(listener);
    }
}

问题是我不知道如何更改动作侦听器,以便它为所有6个Jbutton提供不同的actionPerformed状态,因为每个状态代表不同的笔刷。我尝试了几种方法,例如尝试制作一个动作列表数组并重命名它们,但是这样会产生错误或循环中断,这是分配所需要的,并最终尝试结束。不幸的是,这目前超出了我的范围。如果已经呆了2天而我感到难过。

1 个答案:

答案 0 :(得分:1)

我的第一个想法是创建一个动作类,该动作类将int值作为其构造函数的一部分,为简单起见,我将其设为内部类,但您可以使用外部类,但是您需要向其传递更多详细信息,例如...

public class TestPane extends JPanel {

    private int currenAction;

    public TestPane() {
        String[] myShapesName = {"brushBut", "lineBut", "ellipseBut", "rectBut", "strokeBut", "fillBut"};
        //String[] myLisName = {"brushButL", "lineButL", "ellipseButL", "rectButL", "strokeButL", "fillButL"};

        setLayout(new GridLayout(3, 2));
        JButton[][] myShapes = new JButton[3][2];
        int action = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++) {
                myShapes[i][j] = new JButton();
                myShapes[i][j].setBounds(0, 0, 50, 50);//(100, 200);
                myShapes[i][j].setName(myShapesName[i + j]);
                myShapes[i][j].setBackground(null);
                myShapes[i][j].putClientProperty("id",
                        String.valueOf(myShapesName[i + j]).concat(String.valueOf(j)));

                myShapes[i][j].addActionListener(new ButtonAction(action));
                action++;
                add(myShapes[i][j]);
            }
        }
    }

    public class ButtonAction implements ActionListener {

        private int actionNum;

        public ButtonAction(int actionNum) {
            this.actionNum = actionNum;
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            currenAction = actionNum;
            System.out.println(actionNum);
        }

    }

}