I'd like to make a JPanel that draws itself when it can, using multithread.
My class extends a JPanel and implements Runnable and I want to draw the JPanel not in the EDT because the listener that I have set are freezing it.
The method paintComponent() put a variable to true if the component needs to be painted.
The method drawManager() call the method draw() that paint the component. And set the variable to false when the draw() method has finished to paint.
Thanks in advance for replying!
Here is an overview of my class:
public MyClass extends JPanel implements Runnable {
private boolean isDrawing = false;
private Graphics2D gg;
public MyClasse() {
Thread t = new Thread(this);
t.start();
}
// here is the run() method
@Override
public void run() {
try {
this.drawManager();
}
catch(InterruptedException ex) {
Logger.getLogger(PanelPlateau.class.getName()).log(Level.SEVERE, null, ex);
}
}
// here the paintComponent that tells me : you should draw if you are not drawing
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
synchronized(this) {
if(!this.isDrawing) {
this.gg = (Graphics2D)g.create();
this.doDraw();
this.notify();
}
}
}
// here the code that draw the JPanel when it needs to be drawn
private void drawManager() throws InterruptedException {
while(true) {
synchronized(this) {
while(!this.isDrawing) {
wait();
}
}
this.draw(this.gg);
this.gg.dispose();
this.isDrawing = false;
}
}
// here the code to draw my JPanel
private void draw(Graphics2D g2d) {
...
}
}