2012-12-03 2 views
0

나는 JLabel을 가지고 있습니다. 처음에는 텍스트를 설정했습니다.타이머 추가 및 레이블 텍스트 표시

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

j.setText("Hello"); 

Hello 만 5 초 동안 표시하고 싶습니다. Bye라는 텍스트를 표시하고 싶습니다.

어떻게하면됩니까?

내 작업; 하지만 그것은 한 번에 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

스윙 당신이 이제까지 포함하여 어떤 방식으로 (에서 이벤트 발송 쓰레드를 차단하지해야하는 이벤트 중심의 환경, 당신은 스탠드 아래에 필요한 가장 중요한 개념의 하나이지만, 루프에 국한되지 , 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

한 좋은 예를 들어 –

관련 문제