0
private void addSomeComponentsToFrame(){
JFrame frame = new JFrame();
.....
frame.setVisible(true);

frame.getContentPane().validate();
frame.getContentPane().repaint();

runOtherTask();
}

I want to see frame object and its components before runOtherTask method starts but when i try to run addSomeComponentsToFrame method, frame appears(as black rectangle) but freezes and after runOtherTask method completes it shows frame's components on screen.

Turgut Dsfadfa
  • 775
  • 6
  • 20
  • 42
  • You may use `SwingUtilities.invokeLater` to prevent using more than one thread, that would ensure that `runOtherTask()` is executed after painting is complete. However if `runOtherTask()` is a long running task it is best to be executed in a dedicated thread and keep the EDT responsive. – Extreme Coders Feb 15 '13 at 14:53
  • 2
    @ExtremeCoders, I don't see how using `SwingUtilities` would help here..all it's going to do is place the `runOtherTask` event at the end of the event queue, which is where it'll be regardless in this scenario. – mre Feb 15 '13 at 14:55
  • @mre I think he means creating only the Frame on EDT and calling the method outside of EDT thus it will block the intial thread and not GUI EDT – David Kroukamp Feb 15 '13 at 15:00
  • i found JComponent.paintImmediately method but i dont understand it. – Turgut Dsfadfa Feb 15 '13 at 15:01
  • 1
    JComponent.paintImmediately wont work for JFrame – David Kroukamp Feb 15 '13 at 15:04
  • I had a similar problem. Removing double buffering solved my problem. Every swing component has a setDoubleBuffered() option. Disabling it fixed my problem. – Andrew Case Dec 01 '13 at 23:24

1 Answers1

3

when i try to run addSomeComponentsToFrame method, frame appears(as black rectangle) but freezes and after runOtherTask method completes it shows frame's components on screen.

Sounds like you are blocking the Event Dispatch Thread with a long running task.

You might want to offload that task from your EDT to a separate thread:

If you manipulate Swing components in runOtherTask better to use :

Otherwise you can use (Note the below does not run in the GUIs Event Dispatch Thread thus manipulating Swing components in them is not allowed):

Just as a side note no need for:

frame.getContentPane().validate();
frame.getContentPane().repaint();

simply:

frame.validate();
frame.repaint();

Also if your java version allows use revalidate() instead of validate(). But these are only necessary if adding/removing a component from a visible container.

Community
  • 1
  • 1
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138