[英]How to change jButton value when clicked
我在編譯時不斷出錯。
我不知道如何使用列表生成的整數,並在單擊后將其顯示到jButton中。
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);
}
}
}
}
因此,這里有兩個問題:
alist僅可在您的Random方法內部訪問,因為它是一個局部變量,並且已在其中聲明。 為了解決此問題,您需要使聲明的列表具有更大的作用域, 這里是對局部變量的解釋。
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 } } } }
我希望這可以幫助你!
首先,列表的生成效率不高。您創建了一個從0到48的數組,然后使用流將每個值加1,然后將結果收集在List
以對其進行隨機排序...
你可以
for(int i = 1; i < 50; ++i){
aList.add(i);
}
Collections.shuffle(aList);
或者,如果您真的想要使用Stream
List<Integer> list = IntStream.range(1, 50).boxed().collect(Collectors.toList());
Collections.shuffle(list);
然后,您需要從操作中訪問該列表,您可以
我更喜歡第二版
public static List<Integer> Random(){
List<Integer> list = IntStream.range(1, 50).boxed().collect(Collectors.toList());
Collections.shuffle(list);
return list;
}
完美,您可以在方法中訪問列表。 現在,您只需要迭代每個按鈕的每個值並將Integer
轉換為String
。 我喜歡串聯。
@Override
public void actionPerformed(ActionEvent event)
{
//Shuffle the values on each buttons
if(event.getSource() == shuffleButton){
List<Integer> list = random();
for(JButton btn : jbArray){
btn.setText("" + list.remove(0)); //Removing the item is a security to be sure the value will not be used later by mistake.
}
}
}
只需單擊按鈕“隨機播放”, jbArray
存在的每個按鈕jbArray
將獲得自己的值。 可以將其修改為創建動態值長度,例如,按鈕的動態數量。
List<Integer> list = random(jbArray.length);
for(JButton btn : jbArray){
btn.setText("" + list.remove(0)); //Removing the item is a security to be sure the value will not be used later by mistake.
}
random
變為:
public static List<Integer> random(int range){
List<Integer> list = IntStream.range(1, range).boxed().collect(Collectors.toList());
Collections.shuffle(list);
reutrn list;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.