☆코딩개발

11월 27일 수업

과라나 2012. 11. 27. 11:56
반응형

쓰레드를 이용해서 시계 만들기..ㅋ / 타이머도 같이 / 버튼두개로 스위칭[테이머 또는 시계전환]

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;

public class Test extends Applet implements ActionListener, Runnable {
 Calendar c;
 Font font;
 int h, m, s;
 Thread t1;
 Button bt1, bt2;
 int n = 0;
 boolean one = false, two = false;

 public void init() {
  setLayout(null);
  resize(700, 500);
  font = new Font("Serif", Font.BOLD, 50);
  t1 = new Thread(this);
  t1.start();
  bt1 = new Button("시계");
  bt2 = new Button("타이머");
  bt1.addActionListener(this);
  bt2.addActionListener(this);
  bt1.setBounds(400,100,50,50);
  bt2.setBounds(400,150,50,50);
  add(bt1); add(bt2);
 }

 public void paint(Graphics g) {
  if (one) {
   c = Calendar.getInstance(); // 현재시간을 얻는다. 이 때 Calendar 를 사용할 수 있다
   h = c.get(Calendar.HOUR);
   m = c.get(Calendar.MINUTE);
   s = c.get(Calendar.SECOND);
   g.setFont(font); // 글자체,크기 바꾸기
   g.setColor(Color.green);
   // 시, 분 , 초 출력
   g.drawString(Integer.toString(h), 50, 100);
   g.drawString(" : ", 90, 100);
   g.drawString(Integer.toString(m), 130, 100);
   g.drawString(" : ", 170, 100);
   g.drawString(Integer.toString(s), 210, 100);
  } else {
   g.setFont(font);
   g.setColor(Color.gray);
   g.drawString(Integer.toString(n), 200, 150);
   n++;
  }
 }

 public void run() {
  while (true) {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    System.out.println(e.getMessage());
   }
   repaint();
  }
 }

 @Override
 public void actionPerformed(ActionEvent e) {
  if (e.getSource() == bt1) {
   one = true;
   two = false;
   n=0;
  } else {
   two = true;
   one = false;
  }
 }
}

 

g11_27_1.zip

========================================

 

작은 타원이 위로 점점 이동한다

 

import java.applet.Applet;
import java.awt.*;

public class Test extends Applet implements Runnable {
 
 Thread t1;
 int x=100,y=400;

 public void init() {
  setLayout(null);
  resize(400, 500);
  t1 = new Thread(this);
  t1.start();
 }

 public void paint(Graphics g) {
  if(y<=0){
   x+=20;
   y=400;
  }
  g.setColor(Color.yellow);
  g.fillOval(x, y, 30, 30);
  y-=35;
 }

 public void run() {
  while (true) {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    System.out.println(e.getMessage());
   }
   repaint();
  }
 }
}

 

g11_27_1 (2).zip


 

 

반응형