2017-06-01 37 views
1

我想延遲一個gui。我把2 for循環,我重新繪製一個標籤,但這2個for循環執行一個一個,標籤重新繪製到最後。延遲不支持java gui(java)

我該怎麼辦?

for(int i=0; i<100000; i++){ 
    System.out.println(i); 
} 
label.setBackground(Color.RED); 
for(int i=0; i<100000; i++){ 
    System.out.println(i); 
} 
label.setBackground(Color.green); 

回答

0

有幾種方法可以在Java程序中執行延遲。最簡單的選擇是做

Thread.sleep(2000); 

這只是把當前線程睡2秒。取決於你想要完成什麼,但你可能需要考慮一些更復雜的選項。

該選項使您的程序在睡眠時間內無響應。正如你有一個(我假設)swing應用程序,你可以使用Timer

2

你可能想看看

docs.oracle.com/javase/7/docs/api/javax/swing/Timer

它使用計時器的鏈接在Java中,這有助於去除從您的程序循環。

您可以使用它代替:

Timer t = new Timer(2000, YourActionListener); 
    t.start(); 
}//End of method 

public void paintComponent() 
{ 
    super.paintComponent(g); 
    if(c%2==0) 
    { 
     label.setBackground(Color.RED); 
    } 
    else 
    { 
     label.setBackground(Color.GREEN); 
    } 
    c++; 
} 

... 

public void actionPerformed(ActionEvent) // How your YourActionListener method looks like 
{ 
    repaint(); 
}