What is the best way to draw on JPanel in a background.
Hello all,
my task is to draw many objects, on the panel and then add names to each object. This may take a long time and should be done in background (thread).
What is the best way, to do it.
I have implemented this concept. If you try to resize the frame, the Thread should make some drawings. But nothing happends. If I put drawString method into paintComponent, I see result immediately.
I would appreciate any help.
If the windows was resized, the drawString method should start from the begining, because the position of the objects, and some other factors could be changed. So, this stops and starts of the thread.
If I use it in an unsafe manner, please let me know.
package test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
publicclass Painterextends JFrame{
privatestaticfinallong serialVersionUID = 1;
JPanel panel =new JPanel(){
privatestaticfinallong serialVersionUID = 1;
private ThreadPainter threadPainter;
@Override
protectedvoid paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.gray);
g2d.fillRect(0, 0, 800, 600);
g2d.setColor(Color.white);
for (int i = 0; i < 6; i++){
Rectangle2D rec2d =new Rectangle2D.Double(10+i*100,10+i*100,10,10);
g2d.fill(rec2d);
}
//save current Graphics2D in attribute
currG2D = g2d;
//start thread to paint some changes later
if (threadPainter ==null){
threadPainter =new ThreadPainter();
threadPainter.start();
}else{
threadPainter.stopThread();
threadPainter =new ThreadPainter();
threadPainter.start();
}
}
};
private Graphics2D currG2D =null;
publicclass ThreadPainterextends Thread{
privateboolean stop =false;
@Override
publicvoid run(){
while (!stop){
//do some paintings and stop the execution
//of the thread, untill next repaint of the panel component
currG2D.setColor(Color.red);
int cnt = 0;
for (int i = 0; i < 6; i++){
currG2D.drawString("Square "+i, 10+i*100+20, 10+i*100);
System.out.println("count "+i);
//load data, do calculations
try{
//emulate calculation
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
if (stop){
break;
}
cnt++;
}
if (cnt == 6){
stopThread();
}
}
};
publicvoid stopThread(){
this.stop =true;
};
};
public Painter(){
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(new Point(100,100));
this.setPreferredSize(new Dimension(800,600));
this.panel.setOpaque(true);
this.add(panel,BorderLayout.CENTER);
}
publicstaticvoid main(String[] args){
Painter painter =new Painter();
painter.pack();
painter.setVisible(true);
}
}

