BufferStrategy problem

So hey guys i have some weird problem with BufferStrategy well it might be just weird for me but yeah so the problem is in this code


		BufferStrategy bs = getBufferStrategy();

		if (bs == null) {

			createBufferStrategy(2);

			return;

		}

so yeah and this is the error message that i get

[quote]Exception in thread “Thread-1” java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Component.java:3982)
at java.awt.Component$FlipBufferStrategy.(Component.java:3956)
at java.awt.Component$FlipSubRegionBufferStrategy.(Component.java:4479)
at java.awt.Component.createBufferStrategy(Component.java:3833)
at java.awt.Canvas.createBufferStrategy(Canvas.java:194)
at java.awt.Component.createBufferStrategy(Component.java:3756)
at java.awt.Canvas.createBufferStrategy(Canvas.java:169)
at com.me.app.main.Game.render(Game.java:85)
at com.me.app.main.Game.run(Game.java:73)
at java.lang.Thread.run(Thread.java:744)
[/quote]
and this is the full code

package com.me.app.main;

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;
	static int W = 400;
	static int H = 400;
    static String Title = "My cool game :p ";
	Thread thread;
	boolean Running = true;
	static JFrame frame;

	public static void main(String args[]) {

		

		Game g = new Game();

		frame = new JFrame(Title);
		
		frame.pack();
		
		frame.setSize(H, W);
		
		frame.setVisible(true);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.setLocationRelativeTo(null);
		
		frame.setResizable(false);
		
		g.start();
	}

	public void start() {

		Running = true;

	thread = new Thread(this);

		thread.start();
		
		

	}

	public void stop() {

		Running = false;

		try {
			thread.join();
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

	}

	public void run() {

		while (Running) {

			render();

		}

	}

	public void render() {

		BufferStrategy bs = getBufferStrategy();

		if (bs == null) {

			createBufferStrategy(3);

			return;

		}
		
		Graphics g = bs.getDrawGraphics();
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, getWidth() , getHeight());
		g.dispose();
		bs.show();
		

	}
}


so yeah if you guys can help me that would be very nice from you :slight_smile:

Hi, add the canvas to the frame with something like this :


...
Game g = new Game();

frame = new JFrame(Title);
      
frame.add(g);   <-- here

frame.pack();
...

Umm Thanks i really feel soo stupid i am sorry i am still new to java thanks again :slight_smile:

No problem, you’re welcome :wink: