如何随机设置按钮文字?

时间:2014-02-12 15:43:58

标签: java swing random

是否可以随机设置按钮/按钮文本,例如

案例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);

3 个答案:

答案 0 :(得分:3)

<案例1
String []texts = {"X","Y","Z"};
Random r = new Random();
JButton button = new JButton(texts[r.nextInt(texts.length)];
<案例2
text = "I was chosen";
JButton button1 = new Jbutton("");
JButton button2 = new Jbutton("");
JButton button3 = new Jbutton("");
List<JButton> buttons = Arrays.asList(button1, button2, button3);
Random r = new Random();
buttons.get(r.nextInt(buttons.size())).setText(text);

编辑答案

String text = "text";
JButton[] arr = {button1, button2, button3};
Random r = new Random();
JButton b = arr[r.nextInt(arr.length)];
b.setText(text);
b.setEnabled(false);

答案 1 :(得分:1)

您可以在两种情况下使用数组来实现您想要的效果,使用随机数来选择文本。

对于每个例子的案例一:

String[] arr = {"Lucky", "Not lucky", "BadLuck, press the button again"};
Random r = new Random();
JButton button = new JButton(arr[r.nextInt(arr.length)]; 

对于具有JButton数组的案例2,这是相同的过程。

答案 2 :(得分:0)

List<JButton> buttons = Arrays.asList(button1, button2, button3);
List<String> texts = Arrays.asList(text1, text2, text3);

Random rand = new Random();
buttons.get(rand.nextInt()).setText(texts.get(rand.nextInt()));