wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes Is paint/paintComponent method called by another thread? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Is paint/paintComponent method called by another thread?" Watch "Is paint/paintComponent method called by another thread?" New topic
Author

Is paint/paintComponent method called by another thread?

James Tan
Greenhorn

Joined: Apr 23, 2002
Posts: 13
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){};
}
}


James Tan<br />SUN Certificated Programmer
Brad Baker
Greenhorn

Joined: Aug 12, 2002
Posts: 15
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

Joined: Aug 12, 2002
Posts: 15
My bad,
invokeAndWait() would have been better for this example.
Brad
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is paint/paintComponent method called by another thread?