움직이는 자동차
초시계
조그만 창을 띄우고 그 안에 도형으로 자동차를 그렸습니다.
그리고 자동차가 왼쪽 끝에서부터 오른쪽끝까지 움직이고 끝에 다다르면 다시 왼쪽으로 이동하게끔 코드를 짰는데요
루프를 돌려서 repaint()함수를 이용해서 좌표를 왼쪽에서 오른쪽, 다시 오른쪽에서 왼쪽으로 이동하게했는데 루프내에서 repaint()함수가 실행이 안되네요? 쌍방향을 했을때 움직이면서 현재좌표를 출력하게끔 했더니 좌표는 계속 변하면서 출력이 되는데repaint() 함수는 실행이 안되는것 같습니다. 아예 창 자체가 뜨질 않네요. 그래서 이번엔 한쪽 으로만 움직이도록 반쪽 소스를 돌려보니 for 루프문에 다 끝나고나서야 repaint()가 한번 실행되는것 같습니다.
어떻게해야 좌우로 움직이는 자동차 를 제대로 구현할 수 있을까요? ===================================================================
import java.awt.*;
import javax.swing.*;
import java.util.Calendar;
public class RacingCar extends JFrame{
private CarPanel c = new CarPanel();
public RacingCar(){
add(c);
while(true){
if(c.getCurrentX()==0){
for(int i=c.getCurrentX(); i295; i++){
//time-delay
delay(500);
c.setCurrentX(i);
c.repaint();
System.out.println(c.getCurrentX());
}//end for-loop
}
else{
for(int i=c.getCurrentX(); i=0; i--){
//time-delay
delay(500);
c.setCurrentX(i);
c.repaint();
System.out.println(c.getCurrentX());
}//end for-loop
}
}//end while
}//end RacingCar()
public void delay(int delay_time){
Calendar time = Calendar.getInstance();
double currentTime = time.getTimeInMillis();
currentTime+= delay_time;
while(true)
{
if(currentTime=time.getTimeInMillis())break;
time = Calendar.getInstance();
}
}
public static void main(String[] ar){
JFrame frame = new RacingCar();
frame.setTitle(Exercise 16_15);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(350, 200);
frame.setVisible(true);
frame.setResizable(false);
}//end main()
static class CarPanel extends JPanel{
private int currentX=0, currentY=170 ;
private int[] topOfCarX = new int[]{currentX+10, currentX+20, currentX+30, currentX+40};
private int[] topOfCarY = new int[]{currentY-20, currentY-30, currentY-30, currentY-20};
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(currentX, currentY-20, 50, 10);
g.setColor(Color.black);
g.fillOval(currentX+10, currentY-10, 10, 10);
g.fillOval(currentX+30, currentY-10, 10, 10);
g.setColor(Color.red);
g.fillPolygon(topOfCarX, topOfCarY, 4);
}
public void setCurrentX(int i){
this.currentX = i;
this.topOfCarX = new int[]{i+10, i+20, i+30, i+40};
}
public int getCurrentX(){
return this.currentX;
}
}
}
==============================================================================
-
분홍이
조언감사합니다 ^^
-
상큼한캔디
생성자는 객체를 만드는것 또는 객체를 생성하는것 , 객체를 초기화시키는것 이라고 아주 간단하게 이해하기 쉽게 말할수 있습니다. 생성자에서 루프를 돌리시는 것보다는 매소드를 만드셔서 그 안에서 루프를 돌리시는게 더 좋은것 같습니다. 또한 main에서 부르시게 되면 RacingCar 객체를 생성하시고 매소드를 호출하시는 형식으로 하시는게 더 좋은것 같습니다...ㅎㅎ
-
가람
아....성공했습니다...!! ^^헌데 새로운 질문이 생겼습니다...RacingCar() constructor 내의 소스를 main 함수안으로 옮겨넣고(옮겨넣으면서 생기는 잡다한 에러해결) RacingCar() constructor 는 아예 없애버렸습니다. 그러니까 아무 문제없이 잘 실행되네요. 왜 constructor내에 소스를 넣어놓고 constructor를 불렀을때는 루프내에서 repaint()가 되지 않은건지 모르겠습니다.