Drawing on JPanel
807605Sep 30 2007 — edited Oct 1 2007Hello,
I have a problem with painting on a JPanel. My program represents a client application which connects to a server and recieves data. This data is being recieved in an infinite loop and there is a thread that writes all the data to a JTextArea, however I need to draw this data (some circles and lines) at the same time (almost the same time) as the data is being written to JTextArea. My attempt to do this includes SwingWorker thread and it works ok as long as the data recieved doesn't change - if it changes I need to repaint the drawing in the JPanel, but when I do that new drawing is painted over old one, so there is a mix of old drawings and nwe ones on JPanel.
How can I fix this so that only new drawing is being painted?
Here's the code:
private static void LoadGraph(){
final SwingWorker worker = new SwingWorker() {
public Object construct() {
return null;
}
public void finished() {
Draw(drawPanel.getGraphics());
}
};
worker.start();
}
//Drawing circles and lines
private static void Draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Point [] points = new Point [ms.listaMot.size()];
String [] strID = new String [ms.listaMot.size()];
for(int i=0;i<ms.listMot.size();i++)
{
points[i] = new Point();
points=ms.PointsToDraw(i);
strID[i]=ms.RetID(i);
}
g2.setColor(Color.black);
for(int i=0;i<points.length;i++)
g2.fillOval(points[i].x,points[i].y,20,20);
g2.setColor(Color.white);
for(int j=0;j<strID.length;j++)
g2.drawString(strID[j],points[j].x+7,points[j].y+14);
g2.setColor(Color.black);
//draw lines betwen circles
for(int i=1;i<points.length;i++)
{
Point [] pointsNeighbour = ms.RetPointsNeighbour(i);
if(pointsNeighbour[0].x != -1 && pointsNeighbour[0].y!= -1){
for(int j=0;j<pointsNeighbour.length;j++){
g2.drawLine(points[i].x+8, points[i].y+14, pointsNeighbour[j].x+8, pointsNeighbour[j].y+14);
}
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
drawPanel.repaint();
}
});
}
//this is a part form method that connects to server and gets data
while(true){
//recieving data into sturcture
//processing data and calculating coordinates
//writing to JTextArea
//drawing on JPanel
LoadGraph();
}
//this is a definition for JPanel
private JPanel getDrawPanel(){
if (drawPanel == null){
drawPanel = new JPanel();
drawPanel.setLayout(new GridBagLayout());
drawPanel.setBackground(new Color(251, 251, 220));
drawPanel.setToolTipText("draw panel");
drawPanel.setBounds(new Rectangle(409, 53, 416, 428));
}
return drawPanel;
}
//this is a class where everithing happens :)
public class MotApp extends JFrame {...}
If anyone can help me, I would be very grateful :)