如何调用 Jbutton 的变量名



我正在做一个学校项目,我正在使用netbeans IDE。在这个项目中,我的程序有很多按钮使用相同的代码,但名称不同。与其每次都重新键入变量名称,有没有办法调用按钮本身的名称?

sa1++;
    if(sa1 % 2 == 0) {
        A1.setEnabled(true);
        A1.setBackground(Color.green);
        A1.setOpaque(false);
    }
    else {
        A1.setEnabled(false);
        A1.setBackground(Color.red);
        A1.setOpaque(true);
    }

请注意,按钮按字母顺序向下排列,最多为 5 个。与其重新输入它,有没有办法让它像:

[Jbutton 变量名称].setEnabled(true(;

这样花费的时间更少?

我的老师对此也很好奇,这对未来的项目也有帮助。 编辑:老师知道如何做到这一点,我的意思是他想看看我会如何弄清楚。你们有点苛刻,不是吗?

将按钮放在一个数组中:

//change the 5 to however many buttons you want to have
JButton[] buttons = new JButton[5];

然后初始化它们:

buttons[0] = new JButton();
//add any other initialization, like event handlers

然后像这样遍历它们:

for (int i = 0; i < buttons.length; i++) {
    //replace the line below with whatever you want to do with each button
    performSomeAction(buttons[i]);
}

结合下面的另一个很好的答案,您还可以制作一种方法来封装您想要对按钮执行的所有操作:

private void performSomeAction(JButton button) {
    if(sa1 % 2 == 0) {
        button.setEnabled(true);
        button.setBackground(Color.green);
        button.setOpaque(false);
    }
    else {
        button.setEnabled(false);
        button.setBackground(Color.red);
        button.setOpaque(true);
    }
}

在这个项目中,我的程序有很多使用相同的代码的按钮, 但名称不同。而不是重新键入变量名称 每次,有没有办法调用按钮本身的名称?

将其重构为方法。

例:

public void TestMethod(JButton button)
    if(sa1 % 2 == 0) {
        button.setEnabled(true);
        button.setBackground(Color.green);
        button.setOpaque(false);
    }
    else {
        button.setEnabled(false);
        button.setBackground(Color.red);
        button.setOpaque(true);
    }
}

然后,只需每次调用该方法并传入相应的按钮引用即可。

例:

TestMethod(A1);
TestMethod(A2);
TestMethod(A3);
TestMethod(A4);
将它们

添加到List并执行foreach循环。

最新更新