2012-09-11 18 views
3

我有使用Swing的示例代碼。禁用後在jButton上執行的操作

package playerlist; 

import java.awt.FlowLayout; 
import javax.swing.*; 
import java.awt.event.*; 

public class Sample extends JFrame{ 
    private JButton button1; 
    private JButton button2; 

    public Sample(){ 
     super(); 
     setTitle("Sample JFrame"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     button1 = new JButton("Button 1"); 
     button2 = new JButton("Button 2"); 

     button1.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       button1ActionPerformed(e); 
      } 
     }); 
     button2.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       button2ActionPerformed(e); 
      } 
     }); 

     setLayout(new FlowLayout()); 

     add(button1); 
     add(button2); 
     pack(); 
    } 

    private void button1ActionPerformed(ActionEvent ae){ 
     button1.setEnabled(false); 
     button2.setEnabled(false); 
     try{ 
       Thread.sleep(5000); 
     }catch(Exception e){ 

     } 
     System.out.println("*** Button 1 Clicked ***"); 
     button1.setEnabled(true); 
     button2.setEnabled(true); 
    } 

    private void button2ActionPerformed(ActionEvent ae){ 
     button1.setEnabled(false); 
     button2.setEnabled(false); 
     try{ 
      Thread.sleep(5000); 
     }catch(Exception e){ 

     } 
     // I have disabled this button from button 1's action, but still when I click this button within 
     // 5 seconds, actions of this button is performed 
     System.out.println("*** Button 2 Clicked ***"); 
     button1.setEnabled(true); 
     button2.setEnabled(true); 
    } 

    public static void main(String [] args){ 
     new Sample().setVisible(true); 
    } 
} 

我要像 - 當我單擊button(按鈕1的動作開始時),按鈕1和按鈕2應該被禁止(如果我點擊禁用的按鈕,沒有任何行動應被執行)。我已經使用setEnabled(false)禁用了這兩個按鈕。當button1的動作完成時,兩個按鈕都應該啓用。 但在我的代碼中,這是不工作,即使禁用按鈕後,正在禁用按鈕上執行的操作。 在按鈕1的操作中,我禁用了按鈕和使用的睡眠方法,以暫停執行(模擬繁重工作)5秒鐘,但在5秒鐘內如果單擊任何按鈕,則在按鈕1的操作完成後觸發它們的操作。 請幫幫我。我提供了示例代碼,當您運行它時,並且在單擊button1之後,然後立即按下button2之後,將執行兩個按鈕的操作。 我想要按下任何按鈕時,按鈕的點擊操作將完成繁重的工作,同時我將禁用所有按鈕,因此不能執行其他操作。當第一個動作完成時,我將啓用所有按鈕。 請幫幫我。 在此先感謝。代碼

回答

1

我要上新線程點擊按鈕進行這方面的工作運行任務。

3
+0

+1對於在EDT上不睡覺 - 儘管..在定時器的行爲中睡覺並不是更好:會推動你編輯,你實際上意味着很長的延遲(模擬冗長的任務並驗證OP的基本邏輯是好的:-) – kleopatra

+0

+1對於繁重的工作,也可以考慮'SwingWorker';這個[示例](http://stackoverflow.com/a/11372932/230513)在'done()'之前禁用'startButton'。 – trashgod