【问题标题】:How to set text of a button randomly?如何随机设置按钮的文本?
【发布时间】: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)而不是数组,但数组也可以正常工作。

标签: java swing random


【解决方案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);

【讨论】:

  • @tintinmy,嗨,按钮已经预设,不会使用您的方法创建新按钮。
  • 创建button1,button2... 等等都是无聊的工作,而且会产生更多的 LOC。所以我总是做数组。如果您想使用会使您的工作更难维护的预设按钮。
  • 因为按钮,我正在做多个工作,我必须单独制作所有按钮。是否可以将您的方法与我创建按钮的方式一起使用?
  • @user3288493 我做了一些更改,请参阅。
  • 我看看,还请我帮个忙,你怎么能让上面写着文字的按钮失效?例如如果文本出现在按钮 2 上,我希望按钮 2 被禁用。
【解决方案2】:

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

每个例子的案例一:

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

这与具有JButton 数组的情况二相同。

【讨论】:

    【解决方案3】:
    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()));
    

    【讨论】:

    • GGrec,它在 List "List" 一词上给了我一个错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    相关资源
    最近更新 更多