2013-10-25 70 views
0

我的函數繪製三個隨機數,並根據此數字爲JLabel的(一,二,三)設置適當的圖標。我需要在2秒後更改此圖標。2秒後的第二個線程

public void random() { 
    Random rand = new Random(); 
    num1 = rand.nextInt(3); 
    num2 = rand.nextInt(3); 
    num3 = rand.nextInt(3); 

    if (num1==0){ 
     one.setIcon(icon7); 
    } 
    if (num1==1){ 
     one.setIcon(icon8); 
    } 
    if (num1==2){ 
     one.setIcon(icon9); 
    } 

    if (num2==0){ 
     two.setIcon(icon7); 
    } 
    if (num2==1){ 
     two.setIcon(icon8); 
    } 
    if (num2==2){ 
     two.setIcon(icon9); 
    } 

    if (num3==0){ 
     three.setIcon(icon7); 
    } 
    if (num3==1){ 
     three.setIcon(icon8); 
    } 
    if (num3==2){ 
     three.setIcon(icon9); 
    }} 

2秒後我想改變這樣的圖標:

one.setIcon(icon10); 
    two.setIcon(icon10); 
    three.setIcon(icon10); 

我不知道,如何做到這一點,請幫我:)

回答

3
final Timer timer = new Timer(2000, null); 
ActionListener listener = new ActionListsner() { 

@Override 
public void actionPerformed(ActionEvent e) { 

     one.setIcon(icon10); 
     two.setIcon(icon10); 
     three.setIcon(icon10); 
} 
}; 
timer.addActionListener(listener); 
timer.start(); 

這代碼每2秒調用一次setIcon函數,但是如果您只想調用一次或兩次,您可以將條件放在actionPerformed函數中...希望它對您有所幫助!..

+0

如果你想打電話給一個確切的時間設置說'timer.setRepeats(假);'它的創作之後。 – Holger

+0

謝謝!有用 :) – user1950221

0

我有點先改變你的代碼:

private static final Random rand = new Random(); 

//somewhere on init. 
final JLabel[] myLabels = new JLabel[3]; 
for(int i = 0; i < myLabels.length; ++i) { 
    myLabels[i] = new JLabel(); 
    //add to panel or whatever. 
} 

private void setIcon(final int value, final JLabel label) { 
    switch(value) { 
     case 0: 
      label.setIcon(icon7); 
      break; 
     case 1: 
      label.setIcon(icon8); 
      break; 
     case 2: 
      label.setIcon(icon9); 
      break; 
     default: 
      throw new IllegalArgumentException("Value must be between 0 and 2."); 
    } 
} 

public void random() { 
    for(int i = 0; i < myLabels.length; ++i) { 
     setLabel(rand.nextInt(3), myLabels[i]); 
    } 
    scheduleReset(); 
} 

然後,我會寫scheduleReset方法使用非重複擺動Timer

public void scheduleReset() { 
    final Timer timer = new Timer((int) TimeUnit.SECONDS.toMillis(2), new ActionListener() { 
     @Override 
     public void actionPerformed(final ActionEvent ae) { 
      resetIcons(); 
     } 
    }); 
    timer.setRepeats(false); 
    timer.start(); 
} 

public void resetIcons() { 
    for(int i = 0; i < myLabels.length; ++i) { 
     myLabels[i].setIcon(icon10); 
    } 
} 
相關問題