是否可以随机设置按钮/按钮文本,例如
案例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);
答案 0 :(得分:3)
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()));