如何修改100个对象而无需编写100行代码?(Java)



我有很多JButton名称为a, b, c, d,…的对象

我想根据我拥有的布尔数组设置它们的所有状态。例如,如果布尔数组为[true, false, true],我想将a的状态设为true, b的状态设为false, c的状态设为true。(使用JButton.setEnabled(布尔))

问题是我有太多的对象,如果我必须一个一个地改变它们的状态,代码将变得冗长和冗余。

我如何用一种简单的方式做到这一点?

我在Netbeans编程,Java与Ant, JFrame Form。

编辑)Netbeans不会让您更改创建对象的代码。private javax。swing。jbutton "这部分是不可更改的。

拥有那么多单独的jbutton似乎是你应该不惜一切代价避免的事情,特别是当你有需要处理它们的场景时,但如果你被困住了,你可以这样做:

JButton a = new JButton();
JButton b = new JButton();
//Etc for all the buttons you make

JButton[] list = {a,b}; //Manually insert the JButtons into an array

for(int i=0; i < list.length; i++) //For loop through all of the buttons in the list
{
list[i].addNotify(); //Then just use list[i] and that will be whatever JButton is at index i in the list (so in my example, i=0 is button a, i=1 is button b)
}

在上面的代码中,您将所有按钮插入到数组中,然后像我所示的那样执行相同的函数,其中我对列表中的每个按钮调用.addNotify()函数。

如果你有机会从头开始,这将使事情更容易,我建议把所有的按钮放入一个数组开始,如下面的代码:

JButton[] list = new JButton[10]; //Manually insert the JButtons into an array

for(int i=0; i < list.length; i++) //For loop through all of the buttons in the list
{
list[i] = new JButton();
list[i].addNotify(); //Then just use list[i] and that will be whatever JButton is at index i in the list (so in my example, i=0 is button a, i=1 is button b)
}

数组对于有许多相同类型的对象并对它们进行相同操作的场景特别有用,因此根据您的描述,它可能是一个很好的应用

最新更新