Java 更新圆在JFrame中的位置
所以我想按照一定的速度移动一个圆,比如乒乓球。但是我在更新圆圈的位置时遇到了麻烦。这是我的代码,它将只在侧面绘制圆形和矩形Java 更新圆在JFrame中的位置,java,swing,jframe,paint,repaint,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 Ga
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);
}
}
我想在swing中使用Timer类,但如果你有其他方法,我很乐意听到
编辑:我添加了一个更新圆位置的尝试。有必要对相关组件重新绘制(),这将导致再次调用
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);
}
}
@安德烈·霍姆普森我加入了我的尝试。