Error with Bufferstrategy (Java)

Asked

Viewed 16 times

1

Well, I’m new to Java and I was studying rendering and buffers until I came across the following mistake:

Exception in thread "Thread-1" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.<init>(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.<init>(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at orientaçãoObjetos.Game.render(Game.java:49)
at orientaçãoObjetos.Game.run(Game.java:62)
at java.lang.Thread.run(Unknown Source)

My code is like this:

package orientaçãoObjetos;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;
public static JFrame frame;
private final int WIDTH = 160;
private final int HEIGHT = 120;
private final int SCALE = 4;
private boolean isRunning;

public Game() {
    frame = new JFrame();
    frame.setSize(WIDTH*SCALE, HEIGHT*SCALE);
    
}
public static void main(String args[]) {
    Game game =new Game();
    game.start();
    game.initFrame();
}
public void initFrame() {
    frame.setTitle("Jogo #1");
    frame.add(this);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.getContentPane().add(this);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
    Thread thread = new Thread(this);
    thread.start();
    isRunning = true;
}
public void tick() {
    
}
public void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if(bs==null) {
        this.createBufferStrategy(3);
        return;
    }
    
    Graphics g = bs.getDrawGraphics();
    g.setColor(new Color(18,19,20));
    g.fillRect(0, 0, 160,120);
    bs.show();
}

public void run() {
    while(isRunning) {
        tick();
        render();
        System.out.println("Jogo rodando");
        try {Thread.sleep(1000/60);} 
        catch (InterruptedException e) {e.printStackTrace();
        }
    }
    
}


}

Help me please.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.