Java - 如何使 jButton# 索引获取 int 变量的值?
Java - How do you make a jButton# index take the value of an int variable?
我需要对数百个按钮执行操作。我正在寻找一种为 jButton 索引使用循环的方法,而不是仅仅为了更改多个按钮的颜色而编写数百行代码。
我想要这样的东西:
for(int i = 1; i < 100; i++){
jButton("i").setForeground(Color.red)
}
例如n=18,执行的命令是:
jButton18.setForeground(Color.red)...
这显然行不通,但必须有比为每个按钮写一行更简单的方法!
创建后,将所有 JButton
实例放入 List
中,然后您可以迭代它们:
for (JButton jButton : myJButtons) {
jButton.setForeground(Color.red))
}
如果您尝试实例化数百个按钮,您需要将它们放在 array 中。那可能看起来像这样:
JButton[] array = new JButton[100]
.
然后您可以使用 for 循环遍历数组并像这样更改每个按钮的颜色:
array[i].setForground(Color.red))
.
您可以通过像这样设置每个索引的值来以类似的方式初始化按钮:array[i] = JButton("textHere")
。
如果您想对它们进行不同的编号,post here 介绍了如何将数字转换为字符串,以便您可以在循环中完成。
干杯!
我需要对数百个按钮执行操作。我正在寻找一种为 jButton 索引使用循环的方法,而不是仅仅为了更改多个按钮的颜色而编写数百行代码。 我想要这样的东西:
for(int i = 1; i < 100; i++){
jButton("i").setForeground(Color.red)
}
例如n=18,执行的命令是:
jButton18.setForeground(Color.red)...
这显然行不通,但必须有比为每个按钮写一行更简单的方法!
创建后,将所有 JButton
实例放入 List
中,然后您可以迭代它们:
for (JButton jButton : myJButtons) {
jButton.setForeground(Color.red))
}
如果您尝试实例化数百个按钮,您需要将它们放在 array 中。那可能看起来像这样:
JButton[] array = new JButton[100]
.
然后您可以使用 for 循环遍历数组并像这样更改每个按钮的颜色:
array[i].setForground(Color.red))
.
您可以通过像这样设置每个索引的值来以类似的方式初始化按钮:array[i] = JButton("textHere")
。
如果您想对它们进行不同的编号,post here 介绍了如何将数字转换为字符串,以便您可以在循环中完成。
干杯!