2012-12-03 29 views
0

我有一個JLabel。最初我已經爲它設置了一些文本。添加一個計時器,顯示標籤文字

JLabel j = new JLabel(); 
// set width height and position 

j.setText("Hello"); 

我只希望文本Hello顯示5秒鐘。那麼我想要顯示文字再見。

我怎麼能做到這一點。

我的工作方式;但我知道這是錯的,因爲它一次只能執行1的if-else塊。我想我需要一個計時器或一個計數器。得到這個工作。幫幫我 ?

long time = System.currentTimeMillis(); 

if (time < (time+5000)) { // adding 5 sec to the time 
    j.setText("Hello"); 

} else { 
    j.setText("Bye"); 

} 

回答

5

Swing是一個事件驅動的環境中,你需要下架的最重要的一個概念是,你必須永遠,永遠,阻斷事件以任何方式(包括調度線程,但不限於,環,I/O或Thread#sleep

話雖如此,有辦法實現你的目標。最簡單的是通過javax.swing.Timer類。

public class TestBlinkingText { 

    public static void main(String[] args) { 

     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException ex) { 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new BlinkPane()); 
       frame.setSize(200, 200); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 

     }); 

    } 

    protected static class BlinkPane extends JLabel { 

     private JLabel label; 
     private boolean state; 

     public BlinkPane() { 
      label = new JLabel("Hello"); 
      setLayout(new GridBagLayout()); 

      add(label); 
      Timer timer = new Timer(5000, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent ae) { 
        label.setText("Good-Bye"); 
        repaint(); 
       } 
      }); 
      timer.setRepeats(false); 
      timer.setCoalesce(true); 
      timer.start(); 
     } 
    } 
} 

退房

欲瞭解更多信息

+0

+1很好的例子 –