user2920177
user2920177

Reputation:

Image blinking in Java

I have a problem with a game I am programming in Java. Here is the code.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class Game extends JFrame {
    private static final long serialVersionUID = 1L;

    Graphics dbg;
    Image dbImage;
    static Image block;
    static Block block1 = new Block();
    static Image player1;
    static Player player = new Player(193, 143);

    public Game() {
        Image playerIcon = new ImageIcon("res/play.png").getImage();
        setSize(500, 400);
        setTitle("Game");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setIconImage(playerIcon);
        setLocationRelativeTo(null);
        setVisible(true);
        addKeyListener(new InputHandler());
        setBackground(Color.BLACK);
        setResizable(false);
    }

    public static void main(String[] args) {
        new Game();
        Thread p = new Thread(player);
        p.start();
    }

    @SuppressWarnings("static-access")
    public void paint(Graphics g) {
        try {
            dbImage = ImageIO.read(new File("res/background.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            player1 = ImageIO.read(new File("res/play.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            block = ImageIO.read(new File("res/grass.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        dbg = dbImage.getGraphics();
        draw(dbg);
        g.drawImage(dbImage, 0, 0, this);
        g.drawImage(player1, player.x, player.y, this);
        g.drawImage(block, block1.x, block1.y, this);
    }

    public void draw(Graphics g) {
        repaint();
    }
}

I only added this class because this is where i added the images. Comment if you want to see the other classes. The problem is the image player1 and block are blinking.

Upvotes: 0

Views: 2478

Answers (1)

Harald K
Harald K

Reputation: 27084

  1. Never ever do file I/O on the EDT (Event Dispatcher Thread). The paint(Graphics g) method is invoked by AWT/Swing on the EDT, so you should not load images there (as Zebby Dee correctly points out). Initialize them in the constructor, or load via a SwingWorker or similar.

  2. Don't invoke repaint from paint, as you indirectly do using your draw method. This will cause an endless repaint loop. If you need your game to repaint regularly, use a Timer or similar, to post repaint requests from a different thread, at regular intervals. For some reason you also pass the Graphicsobject of an image to the draw method, and never use it. I'm not sure what the intention is there.

The combination of these two issues causes the blinking effect.

Upvotes: 2

Related Questions