2014-04-14 37 views
0

代碼:的Java GUI按鈕unpressable

public void actionPerformed(ActionEvent evt) 

    { 
....... 


while(true) 
{ 
if (source==button1) 

        { 
        //button1 code      
        } 


if(source==button2) 

        { 
        // button2 code 
        } 
} //while true 


..... 
    //some other code that I don't want it to execute until while breaks 
}//action performed 

所以問題是執行上面的代碼時,GUI被卡住,沒有按鈕可以被按下。如果我刪除了無限循環,其餘的代碼將被執行並停止我的算法。有沒有解決這個問題的方法?

謝謝!

回答

1

while循環是一個嚴重的編程錯誤。讓你的程序在Event Dispatcher Thread中執行循環時,它無法發送任何其他事件(其他按鈕按下)。

你必須消除循環。這樣做的actionPerformed方法將運行在每個按鈕單擊(給你按鈕有actionListeners ...)。