是的,這是作業。是的,我完全卡住了。Swing,Java和多線程以及着色按鈕
這是要點。我創建了一個JFrame。有3個面板(頂部,中部,底部)。在底部面板中有3個按鈕,稱爲:紅色,綠色和藍色。在頂部面板中有3個文本字段,它們給了我們點擊相應按鈕的次數。我們允許的最大數量爲每個按鈕10個。在中間面板是一個8×8的Jbuttons網格,編號從0到63.到目前爲止,這麼好。
每當我們點擊一個按鈕,一個線程就開始了。沒有線程死亡當線程開始時,隨機選擇一個從0到63的數字。與該號碼對應的JButton被塗上了被點擊的顏色。所以如果點擊紅色按鈕,我們應該看到一個白色背景的框變爲紅色。但是那個JButton的顏色開始消失,直到它變成白色。這個過程大概需要8秒。
您創建的線程應該無權訪問任何Swing組件。相反,必須維護一個數據結構,並根據執行週期由線程進行更新。另一方面,定期從主線程調用repaint()方法來邀請Swing Event Dispatcher線程最終訪問數據結構的內容並相應地顯示GUI組件。
........我已經獲得了所有創建和顯示的對象。您無法在按鈕上點擊10次以上。這裏是我的位置:
我有兩個數組:一個是大小爲64的字符串數組。它們表示按鈕。我也有一系列整數。這是爲了讓我知道線程創建的順序。我點擊了一個按鈕創建了線程,並且已經啓動了它們。下面是我對線程的run方法:
public void run() {
Random num = new Random(new Date().getTime());
while (true) {
Thread j = Thread.currentThread();
int randInt = num.nextInt(64);
synchronized (lock) {
if ((array[randInt].compareTo("red") == 0
|| array[randInt].compareTo("blue")
== 0 || array[randInt].compareTo("green") == 0))
{
randInt = num.nextInt(64);
}
for (int k = 0; k < 10; k++) {
if (threadarray[k] == -1) {
threadarray[k] = randInt;
break;
}
}
}
}
}
即使我們還沒有涉及,我曾嘗試使用Timer對象立即熄滅外面鎖段。這將我帶到actionPerformed方法。我已經添加了所有適當的註冊。
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < threadarray.length; i++) {
int num = threadarray[i];
if (num != -1) {
System.out.println(num);
String s = array[num];
System.out.println(s + "is ");
if (s.compareTo("red") == 0) {
button[num].setOpaque(true);
button[num].setBackground(Color.red);
while (button[num].getBackground() != Color.white) {
System.out.println("not white yet");
int g = button[num].getBackground().getGreen();
int b = button[num].getBackground().getBlue();
if (255 - (g + 1) >= 0) {
Color c = new Color(255, g + 1, b + 1, 1);
button[num].setOpaque(true);
button[num].setBackground(c);
System.out.println(c + " " + " c is");
} else {
button[num].setBackground(Color.white);
}
}
}
System.out.println(i + " i is " + button[num].getBackground()); //just some debugging info
threadarray[i] = -1; //clear the thread array
array[num] = "0"; //clear the string array
}
}
}
actionPerformed方法由Event Dispatch Thread處理。 (請注意,上面的代碼僅適用於紅色線程,想法是通過增加綠色和藍色,直到它變成白色來淡化顏色。
問題:單擊紅色按鈕時沒有任何按鈕會改變顏色(是的,已經完成了適當的註冊)我也不知道如何通過多線程來控制時間,我是否會在這裏走上正確的道路?
如果是家庭作業,然後把'家庭作業'標籤。 – Tudor 2012-02-29 11:38:32
更好地幫助您更快地編輯您的問題[SSCCE](http://sscce.org/) – mKorbel 2012-02-29 11:44:38
也請解釋更多問題是什麼?你沒有看到按鈕顏色的變化,但你看到actionPerformed的文本輸出嗎? – toto2 2012-02-29 11:55:48