I'm trying to get an image to paint on the screen using java's Graphics2D. Here is the code I'm using. I want to see an image move steadily across the screen. At the moment I can see the image but it does not move unless I resize the window, in which case it DOES move. I have sketched out the classes below.
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);
}
}
}
The Component object passed to Tester is the following class:
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);
}
I have ensured that this class has only one sprite that I have added. The sprite class is roughly as follows:
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);
}
However, I see only a stationary image of bowser on the screen. He does not move unless the window is resized. I know that the paint(Graphics2D pen) method in the Sprite class is being called at particular intervals (because of the Timer in the Tester class). However, even though the x and y positions are being incremented by 5 each time. The sprite does not move. Why not? How do I fix it? I'm just trying to test some other features of my program at the moment so I really just need to get this up and running. I don't really care how.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…