我有一个名为CharMove的类,其中有paint(Graphics g)方法和一些自定义方法。类(class)应该创建一个正方形,然后在屏幕上随机移动该正方形。然而,当我在我的世界类中创建该类的两个实例时,只出现一个方 block 。首先,方 block 不移动,但会显示新坐标,然后运行 5 次后,方 block 开始随机移动。我认为该程序陷入了 Graphics 方法,因为只创建了一个正方形,而 CharMove 类应该创建 Graphics 的另一个实例。我已经在线搜索,但找不到一种创建不同 Graphics 实例的方法。谢谢提前。
CharMove 类
import java.awt.*;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import java.util.Random;
public class CharMove extends JPanel {
int x = 250;
int y = 250;
public void paint(Graphics g) {
Graphics pane = (Graphics2D) g;
pane.setColor(Color.blue);
pane.fillRect(x, y, 10, 10);
}
public void movement(JFrame frame) {
for (int i=0;i<5;i++) {
try {
TimeUnit.SECONDS.sleep(1);
this.x = Getx(this.x,frame);
this.y = Gety(this.y,frame);
frame.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public int Getx(int a, JFrame frame) {
Random rn = new Random();
int xnum = rn.nextInt(10)-5;
a += xnum;
System.out.println("x:" + a);
return a;
}
public int Gety(int b, JFrame frame){
Random rn = new Random();
int ynum = rn.nextInt(10)-5;
b += ynum;
System.out.println("y:" + b);
return b;
}
}
世界级
import java.awt.*;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import java.util.Random;
public class World {
public static void main(String[] args) {
JFrame game = new JFrame();
game.setTitle("Matrix");
game.setSize(500, 500);;
game.getContentPane().setBackground(Color.white);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
CharMove char1 = new CharMove();
CharMove char2 = new CharMove();
game.add(char1);
game.add(char2);
char1.movement(game);
char2.movement(game);
}
}
最佳答案
在 swing 中,所有的绘画都应该放在paintComponent(Graphics g) 中(重命名你的方法)
要制作动画,您应该使用 Swing Timer(带有 ActionListener)来更新动画项目的位置。一旦完成,计时器应该调用 repaint();
public void actionPerformed(ActionEvent ae) {
this.x = Getx(this.x,frame);
this.y = Gety(this.y,frame);
frame.repaint();
}
关于java - 如何让一个类创建自己的 Graphics 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203737/