0

I'm trying to render an Image with a BufferStrategy and Graphics2D. The Code works well, but the Image is flickering. Before I tested it with Graphics2D, I tried only with Graphics and the Frame was flickering crazy. Here's the Code:

public Main() {

    x = 0;

    Dimension size = new Dimension(sx, sy);
    setPreferredSize(size);

    frame = new JFrame();

    ImageIcon player2 = new ImageIcon("res/gfx/char.png");
    player = player2.getImage();

    addKeyListener(new AL());

    time = new Timer(5, this);
    time.start();

}

public synchronized void start() {
    running = true;
    thread = new Thread(this, "Display");
    thread.start();
}

public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    while (running) {
        render();
        update();
    }
}

public void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    Graphics2D g2d = (Graphics2D) g;

    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, 800, 600);

    g2d.drawImage(player, x, 350, null);

    g.dispose();
    bs.show();
}

(Sorry for my bad english)

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Dragonbone
  • 13
  • 4

1 Answers1

1

I think you are drawing the image directly on jframe. Try to use a middle level container component like JPanel and draw the image over it and add the panel to the frame. Direct drawing causes flickering effect.

Niru
  • 732
  • 5
  • 9
  • If I make it how you say that, can i keep the Tripple Buffering? – Dragonbone Aug 06 '14 at 15:31
  • It is unclear actually how and where you are rendering the image. Also try to avoid thread if you are doing some animation, try using javax.swing.Timer. – Niru Aug 06 '14 at 15:34
  • As you can see in the code, I am working with javax.swing.Timer, but thx for the Answeres! – Dragonbone Aug 06 '14 at 15:38
  • Do you need the triple buffer? JPanel by default has a double buffer. You may be able to make a really messy BufferStrategy with JPanel if it is absolutely needed. . . – Cartier Aug 06 '14 at 15:51