2014-02-09 25 views
2

所以我想按照一定的速度移动一个圆圈,比如pong。但我在更新圈子的位置时遇到问题。这是我的代码,只会在一边绘制圆形和矩形。更新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

好的。这样可行。非常感谢!被卡住了一段时间。 –