爪哇 - 如何使一个JButton#指数采取一个int变量的值? [英] Java - How do you make a jButton# index take the value of an int variable?
问题描述
我需要在上百个按钮执行操作。我正在寻找一种方式来使用循环对JButton指数,而不是写数百$ C $行C的只是更改多个按钮的颜色。
我想是这样的:
I need to perform actions on hundreds of buttons. I'm looking for a way to use a loop for the jButton index, instead of writing hundreds of lines of code just to change the color of multiple buttons. I want something like this:
for(int i = 1; i < 100; i++){
jButton("i").setForeground(Color.red)
}
因此,例如,当n = 18,执行的命令是:
So for example for n=18, the command executed is:
jButton18.setForeground(Color.red)...
这显然是不行的,但必须有比写为每个按钮的线路更简单的方法!
Which obviously does not work, but there has to be a simpler way than to write a line for each button!
推荐答案
如果你试图实例数百按钮你会想什么是有他们在的阵列。这可能会是这个样子:的JButton []数组=新的JButton [100]
。
If you're trying to instantiate hundreds of buttons what you'll want is to have them in an array. That would probably look something like this:
JButton[] array = new JButton[100]
.
您可以然后使用遍历数组的for循环,改变这样每个按钮的颜色:数组[我] .setForground(Color.red))
。
You can then loop through the array using your for loop and change the colour of each button like this:
array[i].setForground(Color.red))
.
您可以通过设置各指标的值这样的初始化方式类似的按钮:数组[我] =的JButton(textHere)
You can initialize the buttons in a similar way by setting the values of each index like this: array[i] = JButton("textHere")
.
如果要编号它们都存在不同这里是一个岗位如何将数字转换成字符串,因此您可以在循环内做到这一点。
If you want to number them all differently there's a post here on how to convert numbers to strings so you can do it inside your loop.
干杯!
这篇关于爪哇 - 如何使一个JButton#指数采取一个int变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!