在JFrame中更新圆的位置

时间:2014-02-09 00:10:04

标签: java swing jframe paint repaint

所以我想按照一定的速度移动一个圆圈,比如乒乓球。但是我无法更新圆圈的位置。这是我的代码,只是在侧面绘制圆形和矩形。

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类,但如果你有另一种方式,我很乐意听到它。

编辑:我尝试更新圆圈的位置。

1 个答案:

答案 0 :(得分: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);
    }
}