• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is paint/paintComponent method called by another thread?

 
James Tan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I met a problem that I have to access the member variables in paint method. However, the value getten in paint method perhaps was changed for paint method being called by a system thread I think. If I changed some member variables in paint method directly, they would be dirty data without serialized. I am not so confidented about my idea.
Do I need to lock 'this' when I want to access the member variables in paint method? It seems not be reasonable.
here is my testing program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintTest extends JFrame
{
private int i;
public static void main(String [] args)
{
new PaintTest().addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public PaintTest()
{
super("Paint Test");
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
setSize(size);
setLocation(0,0);
show();
while(i<1000)
{
i++;
repaint();
}
}

public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString(String.valueOf(i),10+40*(i/60),10+8*(i%60));
try
{
Thread.sleep(1);
}catch(InterruptedException e){};
}
}
 
Brad Baker
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello James,
This would have gotten more reponces in the AWT/Swing area but I will do what I can.
Your:

repaint just lets the GUI thread knows that there is something that need to be updated. It does not force it to do it. So you could have incremented 20, 50 even the whole 1000 before it gets around to updating the GUI
The only way to correctly update values that is not from the GUI itself is:

This way all changes happen during the GUI thread and there are no synchronization problems.
I hope this helps some.
Brad
 
Brad Baker
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My bad,
invokeAndWait() would have been better for this example.
Brad
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic