如何在 java 中随机禁用按钮

How to randomly disable buttons in java

我有这个程序,我需要随机禁用一些按钮,这样用户就无法 select 所有按钮。有没有办法禁用 java 中的随机按钮?

我想使用Math.random,但我不知道如何开始或参考.....

这些是按钮。

JButton but1 = new JButton();
JButton but2 = new JButton();
JButton but3 = new JButton();
JButton but4 = new JButton();
JButton but5 = new JButton();
JButton but6 = new JButton();
JButton but7 = new JButton();

您可以将它们全部放在一个列表中,然后打乱列表并禁用索引 0 处的元素,例如...

但请注意:

  • 您可能正在禁用一个已经禁用的按钮,因此您需要做一些检查
  • 打乱列表是一项需要更多时间的操作,这取决于您在列表中有多少个按钮。

List<JButton> items = Arrays.asList(new JButton(), new JButton(), new JButton());
System.out.println(items);
Collections.shuffle(items);
items.get(0).setEnabled(true);

将您的按钮放入 List 并迭代它们。使用 Random.nextBoolean 来确定是启用还是禁用按钮。这将为您提供 50/50 的分配。如果您需要其他东西,请使用 nextInt 和模数。

List<JButton> myButtons = /*whatever*/;

final Random generator = new Random();
for (JButton button : myButtons)
{
    button.setEnabled(generator.nextBoolean());
}

这不能保证在任何时候启用任意数量的按钮。你不清楚这是否重要。

Array/Vararg版本:

public JButton getRandomButton(JButton... buttons) {
    int index = (int) (Math.random() * buttons.length);

    return buttons[index];
}

列表版本:

public JButton getRandomButton(List<JButton> buttons) {
    int index = (int) (Math.random() * buttons.size());

    return buttons.get(index);
}

这两种方法都会return一个随机的 JButton 供您使用。