I'm learning to use bufferstrategy with canvas, I coded this class which is then added to a JFrame in another class. I'm trying to draw a rectangle, but the canvas is empty. The console says
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 myPanel.draw(Pannello.java:72)
at myPanel.run(Pannello.java:59)
at java.lang.Thread.run(Unknown Source)
And here's the code. I've debugged it and it goes into every method that I've made. So basically now I don't know why it's not showing my rectangle.
public class myPanel extends Canvas implements Runnable {
//FIELDS
private static final long serialVersionUID = 1L;
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private boolean running;
private Thread t1;
public synchronized void start (){
running = true;
t1 = new Thread (this);
t1.start(); // calls run()
}
//INIT
public myPanel(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
}
//Main runnable
public void run(){
while (running){
update();
draw();
}
}
public void update(){
}
public void draw(){
BufferStrategy bs = getBufferStrategy();
if (bs== null){
createBufferStrategy(3);
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillOval(0, 0, 20, 20);
g.dispose();
bs.show();
}
}
Here is my initial answer, this should fix your problem. I will explain your errors in my next edit:
Ok, first of all, it is convention in Java to capitalize your class names. I did not do it here, but I hope you'll remember.
Second of all, there were a few things missing from your code. You didn't make a JFrame, and there wasn't a main method which I'm sure you know that every Java program needs to know where to start. You also need a constructor to initialize the JFrame and to set the size of the frame.
Third, you need to
return;
after creating the buffer strategy.I hope this helped.
EDIT:
Instead of adding a
new myPanel()
to your frame, addgame
instead.frame.add(game);