반응형
주제 : 생성 메서드와 필드 변수
변수의 유효범위는 다음 코드를 통해 알 수 있다.
import java.awt.Graphics;
public class Scope {
private double d = 3.14;
public Scope() {
System.out.println(s);
System.out.println(d);
int d = 2;
System.out.println(d);
System.out.println(s);
}
private String s = "X" + d;
public void printComponent(Graphics g) {
System.out.println(d + " " + s);
}
public static void main(String[] args) {
new Scope();
}
}
위를 실행시키면
X3.14
3.14
2
X3.14
이라는 결과값이 나온다. 전역변수가 먼저 선언되는 것을 볼 수 있다.
이제 아날로그 시계로 돌아오자
import java.awt.Color;
import java.awt.Graphics;
import java.time.LocalTime;
import javax.swing.*;
public class ClockWriter extends JPanel{
private final int SIZE;
public ClockWriter(int _s) {
SIZE = _s;
JFrame frame = new JFrame();
frame.setTitle("Clock");
frame.setSize(SIZE+50, SIZE+150);
frame.getContentPane().add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
g.drawString("TIME IS GOLD", 105, 50);
g.setColor(Color.LIGHT_GRAY);
g.fillOval(25, 100, 250, 250);
LocalTime now = LocalTime.now();
int radius = SIZE/2;
int x1 = 25 + radius;
int y1 = 100 + radius;
radius -=30;
double minute_angle = (now.getMinute()-15) * Math.PI / 30;
int x2 = x1 + (int)(radius*Math.cos(minute_angle));
int y2 = y1 + (int)(radius*Math.sin(minute_angle));
g.setColor(Color.red);
g.drawLine(x1, y1, x2, y2);
}
public static void main(String[] args) {
new ClockWriter(250);
return;
}
}
다음과 같이 작성하면 아날로그 시계의 분침을 만들 수 있다.
위의 코드에서 now.getMinute()에 -15를 해준 이유는 원의 시작이 15분이기 때문에 돌려준 것이다.
import java.awt.Color;
import java.awt.Graphics;
import java.time.LocalTime;
import javax.swing.*;
public class ClockWriter extends JPanel{
private final int SIZE;
public ClockWriter(int _s) {
SIZE = _s;
JFrame frame = new JFrame();
frame.setTitle("Clock");
frame.setSize(SIZE+50, SIZE+150);
frame.getContentPane().add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
g.drawString("TIME IS GOLD", 105, 50);
g.setColor(Color.LIGHT_GRAY);
g.fillOval(25, 100, 250, 250);
LocalTime now = LocalTime.now();
int radius = SIZE/2;
int x1 = 25 + radius;
int y1 = 100 + radius;
radius -=30;
double minute_angle = (now.getMinute()-15) * Math.PI / 30;
int x2 = x1 + (int)(radius*Math.cos(minute_angle));
int y2 = y1 + (int)(radius*Math.sin(minute_angle));
g.setColor(Color.red);
g.drawLine(x1, y1, x2, y2);
radius -= 30;
double hour_angle = (now.getHour() - 3) * Math.PI / 6 + now.getMinute() * Math.PI / 30/12;
x2 = x1 + (int)(radius*Math.cos(hour_angle));
y2 = y1 + (int)(radius*Math.sin(hour_angle));
g.setColor(Color.yellow);
g.drawLine(x1, y1, x2, y2);
}
public static void main(String[] args) {
new ClockWriter(250);
return;
}
}
위의 코드는 분침을 그리는 코드를 시침에도 응용하여 작성한 것이다.
그러면 다음과 같이 시침과 분침이 모두 나오는 것을 확인할 수 있었다.
728x90
반응형