I'm making a game/simulator and I'm using the following method to load an Image into my current Java project:
public static Image getImage(String name) { URL url = ImageLoader.class.getClassLoader().getResource("resources/" + name); Image img = Toolkit.getDefaultToolkit().createImage(url); ImageLoader.tracker.addImage(img, 1); try { ImageLoader.tracker.waitForID(1); } catch (InterruptedException e) { e.printStackTrace(); } return img; }
This loads the images into my class that is drawing all items including the player (who has 4 different images for each direction he can face: north, south, east, west):
private Image player = ImageLoader.getImage("playerEast.png"); private Image playerEast = ImageLoader.getImage("playerEast.png"); private Image playerWest = ImageLoader.getImage("playerWest.png"); private Image playerSouth = ImageLoader.getImage("playerSouth.png"); private Image playerNorth = ImageLoader.getImage("playerNorth.png");
The class that loads above images paints them in the area like such:
public class TerritoryPanel extends JPanel implements Observer { @Override protected void paintComponent(Graphics g){ super.paintComponent(g); //Draw player g.drawImage(player, (x, y, this);
}
I'm trying to update the pics with this method in the same class:
public void rotateEast(){ player = playerEast; repaint(); revalidate(); }
..but just calling this rotateEast() does not update the picture immediately, it only gets updated afterwards when my regular Observer update() cycle calls repaint(), this happens every second so the missing repaint of rotateEast is visible:
@Override public void update(Observable o, Object arg) { if (EventQueue.isDispatchThread()) { this.repaint(); } else { // Simulation-Thread SwingUtilities.invokeLater(new Runnable() { @Override public void run() { repaint(); } }); } }
Why does the repaint() from rotateEast seem to have no effect? Thank you very much in forward