0

I'm working on a basic program that creates a JFrame and adds a JPanel to it that contains an image. It works, however for some reason there is a slight delay (just a couple of seconds) where the screen is blank before the image is added. Why is this? and how can I fix it? Here is the code:

Frame Class:

public class Frame extends JFrame {

public Frame() {

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    JFrame loader = new JFrame();
    loader.setSize(screenSize.width / 3, screenSize.height / 3);
    loader.add(new LaunchPanel(screenSize.width, screenSize.height));
    loader.setLocationRelativeTo(null);
    loader.setResizable(false);
    loader.setUndecorated(true);
    loader.repaint();
    loader.setVisible(true);

    } 
}

Launch Panel Class:

public class LaunchPanel extends JPanel{

public LaunchPanel(int w, int h) {
    BufferedImage image = null;
    try {
        image = ImageIO.read(new File("myImagePath.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.setSize(w, h);
    Image scaledImage = image.getScaledInstance(this.getWidth() / 3, this.getHeight() / 3,Image.SCALE_SMOOTH);
    JLabel label = new JLabel(new ImageIcon(scaledImage));
    this.add(label);
    label.setLocation(0, 0);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • There are any number of possible issues. Swing takes a few seconds to get the Event Dispatching Thread up and running, hook up the native peer and cycle through all the initial events which occur when starting up. Add in that reading and scaling an image are time intensive process and you are adding more delays. So, what's the answer? You could try using [the splash screen API](https://docs.oracle.com/javase/tutorial/uiswing/misc/splashscreen.html) instead. It acts a little differently from normal components, but is (generally) faster to load – MadProgrammer Dec 30 '18 at 01:21
  • `getScaledInstance` is asynchronous (the rest of the code proceeds while the image is being scaled). Ways around that are to either 1) Create a new buffered image and scale the original image to it. 2) Add a `MediaTracker` to the (get) scaled (instance) image. General tips: 1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) .. – Andrew Thompson Dec 30 '18 at 04:53
  • .. hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). – Andrew Thompson Dec 30 '18 at 04:53

0 Answers0