2014-02-09 4 views
2

그래서 탁구와 같은 특정 속도에 따라 원을 이동하고 싶습니다. 하지만 서클의 위치를 ​​업데이트하는 데 문제가 있습니다. 옆에 원과 직사각형을 그릴 코드가 있습니다.JFrame에서 원의 위치 업데이트

import java.awt.*; 
import javax.swing.*; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class Game extends JFrame{ 
    public Game(){ 
     GameScreen p1 = new GameScreen(); 
     add(p1); 
     Timer t = new Timer(1000, new ReDraw()); 
     t.start(); 
    } 

    public static void main(String[] args){ 
     Game g = new Game(); 
     g.setLocation(400, 200); 
     g.setSize(700, 600); 
     g.setVisible(true); 
    } 
} 

class ReDraw implements ActionListener{ 
    static int count = 0; 
     static int posX = 603; 
     static int posY = 210; 
     static int velX = 50; 
     static int velY = 50; 
    public void actionPerformed(ActionEvent e){ 
     count++; 

     posX -= velX; 
     posY -= velY; 
     System.out.println("Flag 1: " + posX + " " + posY); 

     if (count == 2) 
      ((Timer)e.getSource()).stop(); 
    } 
} 

class GameScreen extends JPanel{ 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     g.setColor(Color.orange); 
     g.fillRect(654, 200, 30, 100); 

     g.setColor(Color.red); 
     g.fillOval(ReDraw.posX, ReDraw.posY, 50, 50); 
    } 
} 

나는 스윙에서 Timer 클래스를 사용하고 싶지만 다른 방법이 있다면 듣고 싶습니다.

편집 : 원의 위치를 ​​업데이트하려고 시도했습니다.

+0

@AndrewThompson 내 시도를 추가했습니다. –

답변

1

repaint() 해당 구성 요소가 필요하므로 paintComponent(Graphics) 메서드가 다시 호출됩니다. 이를 위해 청취자는 애니메이션 패널에 대한 참조가 필요합니다. 이는 코드의 다른 부분을 변경하지 않고이를 수행하는 한 가지 방법입니다.

import java.awt.*; 
import javax.swing.*; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class Game001 extends JFrame { 

    public Game001() { 
     GameScreen p1 = new GameScreen(); 
     add(p1); 
     Timer t = new Timer(1000, new ReDraw(p1)); 
     t.start(); 
    } 

    public static void main(String[] args) { 
     Game001 g = new Game001(); 
     g.setLocation(400, 200); 
     g.setSize(700, 600); 
     g.setVisible(true); 
    } 
} 

class ReDraw implements ActionListener { 

    static int count = 0; 
    static int posX = 603; 
    static int posY = 210; 
    static int velX = 50; 
    static int velY = 50; 
    GameScreen gameScreen; 

    ReDraw(GameScreen gameScreen) { 
     this.gameScreen = gameScreen; 
    } 

    public void actionPerformed(ActionEvent e) { 
     count++; 

     posX -= velX; 
     posY -= velY; 
     System.out.println("Flag 1: " + posX + " " + posY); 
     gameScreen.repaint(); 

     if (count == 4) { 
      ((Timer) e.getSource()).stop(); 
     } 
    } 
} 

class GameScreen extends JPanel { 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     g.setColor(Color.orange); 
     g.fillRect(654, 200, 30, 100); 

     g.setColor(Color.red); 
     g.fillOval(ReDraw.posX, ReDraw.posY, 50, 50); 
    } 
} 
+1

오케이. 그거야. 정말 고맙습니다! 한동안 붙어있어. –