IT_Programming/Java

현재시간을 알려주는 Swing시계 java.swing.Timer클래스 사용.

JJun ™ 2007. 2. 6. 10:09

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

public class TimerTest extends JPanel implements ActionListener

{
      Calendar calendar1 = Calendar.getInstance(); 
      int hour = calendar1.get(Calendar.HOUR_OF_DAY); 
      int min = calendar1.get(Calendar.MINUTE); 
      int sec = calendar1.get(Calendar.SECOND);

      javax.swing.Timer timer; 
      JLabel lbPresent;

      public TimerTest()

      {
            timer = new javax.swing.Timer(1000, this);
            timer.setInitialDelay(0);
            timer.start();

            lbPresent = new JLabel("현재 : " + hour + "시" + min + "분 " + sec + "초",
                                               Label.RIGHT);
            add(lbPresent);
      }

      public void actionPerformed(ActionEvent e)

      {
            ++sec;
            Calendar calendar2 = Calendar.getInstance();
            hour = calendar2.get(Calendar.HOUR_OF_DAY);
            min = calendar2.get(Calendar.MINUTE);
            sec = calendar2.get(Calendar.SECOND);
            lbPresent.setText("현재 : " + hour + "시" + min + "분 " + sec + "초");
      }

      private static void createAndShowGUI()

      {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("TimerTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            TimerTest timerTest = new TimerTest();
            timerTest.setOpaque(true);
            frame.setContentPane(timerTest);
            frame.pack();
            frame.setVisible(true);
      }

      public static void main(String[] args)

      {
            javax.swing.SwingUtilities.invokeLater(new Runnable()

                                                                   {public void run(){createAndShowGUI();}});
      }
}

 

/*

    현재 시간을 알려주는 시계입니다. Timer클래스는 1초마다 이벤트를 일으켜서 알려줍니다.

    actionPerformed에서 시간을 보여줍니다. 앞써 했었던 시간이 증가/감소하는 예제와 이 예제를

    응용하면 스탑워치'를 만들 수 있습니다.

*/