N
N
Nifontov2014-01-27 09:23:22
Java
Nifontov, 2014-01-27 09:23:22

Why does Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer occur?

Good afternoon, dear users, not so long ago I began to study the java language.
Tried to add a multibuffering strategy, but the compiler doesn't want to run...

===== Below is the Code======
import javax.swing.JFrame;

public class TetrisMain extends Canvas implements Runnable, KeyListener {

public static final int WIDTH=400, HEIGHT=540;

public static void main(String[] args){
JFrame frame = new JFrame("Tetris");
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
TetrisMain tm = new TetrisMain();
frame.setVisible(true);
tm.start();
}

public void start(){
Thread t = new Thread(this);
t.setPriority(Thread.MAX_PRIORITY);
t.start();

}
public void run() {
boolean running = true;
while(running){
update();
BufferStrategy buf = getBufferStrategy();
if(buf == null){
createBufferStrategy(3);
continue;
}
Graphics2D g = (Graphics2D) buf.getDrawGraphics();
render(g);
buf.show();
}
}

public void update() {
}

public void render(Graphics2D g){
g.setColor(Color.BLACK);
g.fillRect(0, 0,WIDTH, HEIGHT);

}
public void keyPressed(KeyEvent e){

}
public void keyTyped(KeyEvent e){
}

public void keyReleased(KeyEvent e){
}
}
====================== ====================
And Here are the actual errors that the compiler produces
======================= ====================

Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers (Unknown Source)
at java.awt.Component$FlipBufferStrategy.(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.(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 Tetr.TetrisMain.run(TetrisMain.java:41)
at java.lang.Thread.run(Unknown Source)

Please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2014-01-27
@lorus

Read the source, please
It is obvious that you attempted to perform an operation before these conditions were met. This is due, among other things, to the fact that you are trying to perform this operation on a different thread, which is not allowed in AWT unless otherwise noted. Read about event dispatch thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question