We help IT Professionals succeed at work.

Swing, Adding components to a jpanel on the fly

inudaci
inudaci asked
on
Medium Priority
427 Views
Last Modified: 2010-03-30
Hello

I have a loop in a class extending JPanel , i need components to be added to the panel right away, not after the loop finishes

....
while(true) {
    ...
    ...heavy code...
    ....
     this.add( new JLabel("im want to show up right away. inside this nice loop.") )
     this.revalidate();
}

every addition in a new thread? help needed thank you
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
You need to add components on the event dispatch thread. Call EventQueue.invokeAndWait from a non-gui thread

Author

Commented:
This seems to be the case, thanks, but...
..how do i from my listener in the gui thread, jump to another thread, so im allowed to call the EventQueue.invokeAndWait ?
CERTIFIED EXPERT
Top Expert 2016

Commented:
The best way would be to not do this intensive processing in the gui thread in the first place. Then you're free to call it
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
You should be using SwingWorker, its designed to handle exactly this situation.
Its part of 1.6 or can be downloaded for earlier verwsions

https://swingworker.dev.java.net/
CERTIFIED EXPERT
Top Expert 2016
Commented:
>>its designed to handle exactly this situation.

It isn't actually, it's designed for single invocations.

What you need to do is simply to create a new Thread for your processing and call EventQueue.invokeLater from it.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> It isn't actually, it's designed for single invocations.

rotfl, it can be used for as many invocations as you like
If you're going to mislead people, at least provide some facts to back up ridiculous claims.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.