简体   繁体   中英

repaint() is not called from run

I have a Jpanel where i draw a level of game. My problem is that the method run not repaint the images. What am i doing wrong? If i call repaint() in the keyLister the jpanel is repainted but runnable not have importance...

Thanks for the help!!!!

public class Board extends JPanel implements Runnable {

private Map map;
private Player player;

public Board(String path) {
    this.map = new Map(path);
    this.jugador = new Jugador();
    addKeyListener(new Al());
    this.setFocusable(true);
}

public void paint(Graphics g) {
    super.paint(g);
    for (int y = 0; y < 23; y++) {
        for (int x = 0; x < 37; x++) {
            if (map.getLab(x, y).equals("f")) {
                g.drawImage(map.getImgFinish(), x * map.getTamImagen(), y * map.getTamImagen(), null);
            }
            if (map.getLab(x, y).equals("g")) {
                g.drawImage(map.getImgGrass(), x * map.getTamImagen(), y * map.getTamImagen(), null);
            }
            if (map.getLab(x, y).equals("w")) {
                g.drawImage(map.getImgWall(), x * map.getTamImagen(), y * map.getTamImagen(), null);
            }
        }
        player.drawPlayer(g, player.getCoorX() * map.getTamImagen(), player.getCoorY() * map.getTamImagen());

    }
}
public void run() {
    while (true) {
      repaint();
    }
}
public class Al extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        if (keyCode == KeyEvent.VK_LEFT) {
            if (!map.getLab(player.getCoorX() - 1, player.getCoorY()).equals("w")) {
                player.move(-1, 0);

            }
        }
        if (keyCode == KeyEvent.VK_RIGHT) {
            if (!map.getLab(player.getCoorX() + 1, player.getCoorY()).equals("w")) {
                player.move(1, 0);

            }}}}}

That's a very tight while loop, one that risks hogging the CPU completely rendering your GUI useless. Instead of looping as you're doing, you're far better off responding to events when they occur. For instance, if you want to change views when a key is pressed, then call repaint() after receiving notification that the key has been pressed, not within a tight while loop. You could use a KeyListener for this as you're doing, but understand that these are very fidgity with respect to component focus, and for this (and other reasons) you're better off using Key Bindings .

If you need to run a game loop for other reasons, don't make one so tight -- without Thread.sleep or any break within it. For the interests of Swing thread safety, you're best off not using that while loop, but rather using a Swing Timer instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM