gpt4 book ai didi

java - 单击时如何更改 jButton 值

转载 作者:行者123 更新时间:2023-12-02 02:10:13 25 4
gpt4 key购买 nike

我在编译时不断收到错误。

我不知道如何使用列表生成的整数并在单击后将其显示到 jButtons 中。

 public static void Random ()
{
int Rand [] = new int [49];
for (int b = 0; b < 49; b++)
Rand [b] = b;

List<Integer> alist = Arrays.stream(Rand)
.boxed()
.map (x -> x + 1)
.collect (Collectors.toList());

Collections.shuffle(alist);
}

private class HandleTextField implements ActionListener
{
@Override
public void actionPerformed(ActionEvent event)
{
for (int a = 0; a < 49; a++)
{
if (event.getSource() == jbArray[a])
{
//error on this line "alist cannot be resolved to a variable"
jbArray[a].setText(alist);
}
}
}
}

最佳答案

所以,你有两个问题:

  1. alist 只能在 Random 方法中访问,因为它是一个局部变量并且是在那里声明的。为了解决这个问题,你需要使用更大的范围声明 alist here是局部变量的解释。

  2. setText 需要 String 类型输入,而 alist 不是字符串而是列表。如果你想访问 alist 的元素,那么你可以使用 alist.get(yourIndex);

    static List<Integer> alist; //is not in random method so it can be accessed by other methods
    public static void Random ()
    {
    int Rand [] = new int [49];
    for (int b = 0; b < 49; b++)
    Rand [b] = b;

    alist = Arrays.stream(Rand)
    .boxed()
    .map (x -> x + 1)
    .collect (Collectors.toList());

    Collections.shuffle(alist);
    }


    private class HandleTextField implements ActionListener
    {
    @Override
    public void actionPerformed(ActionEvent event)
    {
    for (int a = 0; a < 49; a++)
    {
    if (event.getSource() == jbArray[a])
    {
    jbArray[a].setText(alist.get(a)+"");//uses only the element you want rather than all of the list
    }
    }
    }
    }

希望这对您有帮助!

关于java - 单击时如何更改 jButton 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com