0

I want to show a buffered image in a JFrame. I though the image should appear as soon as I do frame.setVisible(true). However, this is not true if I have, for instance, a Thread.sleep() or another process after this command.

Is it possible to "force" to show the JFrame content?

I'm calling this JFrame when I click from a button in another (main) JFrame. Below an example using a JPanel instead of an image.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
     JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    f.pack();
    f.setVisible(true);

    try {
        Thread.sleep(5000);
    } catch (InterruptedException ex) {
        Logger.getLogger(NovoJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
alrossi
  • 11
  • 2
  • 1
    DON'T!, **NEVER!** use `Thread.sleep()` in a Swing GUI, this will block the GUI from updating or repainting until this `Thread.sleep()` finishes, I think you wanted to use a [Swing Timer](https://docs.oracle.com/javase/8/docs/api/javax/swing/Timer.html) instead. *"I'm calling this JFrame when I click from a button in another (main) JFrame"*, See, [the use of multiple JFrames, Good / Bad practice?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-or-bad-practice) – Frakcool Aug 30 '16 at 21:35
  • Btw why are you placing that `Thread.sleep()` call? What are you pretending to do while it works? – Frakcool Aug 30 '16 at 21:41
  • As @Frakcool said, `Thread.sleep() ` is not going to work, this is due to the fact that the GUI is rendering in the current thread, and you're pausing the thread before it can render. If you really want to go the threading route, look into multi-threading. But as was mentioned a Swing Timer is good in this situation. – parabolah Aug 30 '16 at 21:43
  • Actually, I'm not using a `Thread.sleep()` in my real application. Instead, I'm calling another process that takes a while to finishes. I tried to "simulate" this process using `Thread.sleep()` in this example. Thank you @Frakcool and @Winter Roberts. – alrossi Aug 31 '16 at 14:38
  • I suppose it's a DB Connection, then you should make this call inside another Thread, not on the EDT or you'll get problems like this – Frakcool Aug 31 '16 at 15:23
  • This process reads/writes in a serial port. Thank you @Frakcool. – alrossi Sep 05 '16 at 12:57

0 Answers0