1
我想要使用java的Graphics2D在屏幕上绘制图像。这是我正在使用的代码。我希望看到一个图像稳定地在屏幕上移动。目前我可以看到图像,但除非我调整窗口大小,否则它不会移动,在这种情况下,它会移动。我已经勾画出下面的课程。使用Graphics2D绘制图像
public class Tester extends JFrame {
private static final long serialVersionUID = -3179467003801103750L;
private Component myComponent;
public static final int ONE_SECOND = 1000;
public static final int FRAMES_PER_SECOND = 20;
private Timer myTimer;
public Tester (Component component, String title) {
super(title);
myComponent = component;
}
public void start() {
myTimer = new Timer(ONE_SECOND/FRAMES_PER_SECOND, new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
repaint();
}
});
myTimer.start();
}
@Override
public void paint (Graphics pen) {
if (myComponent != null) {
myComponent.paint(pen);
}
}
}
传递到测试组件对象是以下类:
public class LevelBoard extends Canvas implements ISavable {
private static final long serialVersionUID = -3528519211577278934L;
@Override
public void paint (Graphics pen) {
for (Sprite s : mySprites) {
s.paint((Graphics2D) pen);
}
}
protected void add (Sprite sprite) {
mySprites.add(sprite);
}
我已经确保这个类只有一个,我已经加雪碧。 Sprite类大致如下:
public class Sprite {
private Image myImage;
private int myX, myY;
public Sprite() {
URL path = getClass().getResource("/images/Bowser.png");
ImageIcon img = new ImageIcon(path);
myImage = img.getImage();
}
public void update() {
myX += 5;
myY += 5;
}
public void paint (Graphics2D pen) {
update();
pen.drawImage(myImage, myX, myY,null);
}
但是,我看到屏幕上只有库巴的静止图像。除非调整窗口大小,否则他不会移动。我知道Sprite类中的paint(Graphics2D pen)方法正在以特定间隔被调用(因为Tester类中的Timer)。但是,即使x和y位置每次增加5。精灵不移动。为什么不?我如何解决它?我只是试图测试我的程序的一些其他功能,所以我真的只是需要启动和运行。我真的不在乎如何。
当你覆盖'漆();'请确保调用'super.paint(笔);'。 – Doorknob