It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes Thread in paintComponent doesn't paint Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Thread in paintComponent doesn Watch "Thread in paintComponent doesn New topic

Thread in paintComponent doesn't paint

Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi ranchers,

I made a test application to just paint a dot.
The paintComponent was overridden in an anonymous class of JPanel.

When I changed the line commented out (bold) in the following

... with a runnable and thread (italics).

The thread obviously runs ("dot" output in system.out), but the dot didn' show up again.

What am I doing wrong in the threading?
I looked up Sun tutorial about Swing but didn't found something about threading there.
Anyone knows where to look this up?

Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245
Swing is not thread safe. The Graphics object cannot be passed to different thread.
See Threads and Swing.
[ December 18, 2006: Message edited by: Vlado Zajac ]
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

There's already a thread in charge of painting all components that calls paint() (which then calls paintComponent()) - grabbing the graphics reference and painting to it in another thread is not going to work because there's no reference to any component or anything once the other thread gets around to calling g.paintOval(), the graphics reference might be painting another component, have a different clip region, be disposed of, etc. by this point anyway.

Swing is a single threaded model - look up some stuff about the event thread in Swing, SwingUtilities.invokeLater(), SwingUtilities.invokeAndWait(), etc.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Thanks ranchers,

I found the stuff.

Start reading ...

I agree. Here's the link:
subject: Thread in paintComponent doesn't paint
It's not a secret anymore!