【发布时间】:2014-03-11 01:17:07
【问题描述】:
是否可以随机设置按钮/按钮文本,例如
案例1;
我有 1 个按钮和 3 个文本,我想在按下按钮时将按钮的文本随机设置为三个文本之一。
String text1 = "Lucky", text2 = "Not lucky", text3 = "BadLuck, press the button again";
JButton button = new Jbutton(""); // I want this button to have one of the text from above randomly.
案例2;
我有 3 个按钮和 1 个文本,我想将文本随机分配给三个按钮之一
String text = "I was chosen";
JButton button = new Jbutton("Press me"); // when this button is pressed, I want at randomly for one of the buttons below to get the text "I was chosen".
JButton button1 = newJbutton("");
JButton button2 = newJbutton("");
JButton button3 = newJbutton("");
提前致谢!
编辑:
String text = "text";
JButton[] arr = {button1, button2, button3};
Random r = new Random();
arr[r.nextInt(arr.length)].setText(text);
【问题讨论】:
-
将字符串放入List,生成随机列表索引并获取该索引。
-
在数组列表中?像这样... arraylist[] list{"String1", "String2", "String3"};
-
我会使用列表(例如 ArrayList)而不是数组,但数组也可以正常工作。