Search code examples
javaswingjframejlabelimageicon

Jframe becomes empty on adding image


I need to display an image from my pc file system. The image is stored at -
C:\Users\Akshay\Desktop\allfiles

The relevant code is (scroll to right) :

    JFrame frame = new JFrame();
    frame.setExtendedState( frame.getExtendedState()|JFrame.MAXIMIZED_BOTH );
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setLayout(new FlowLayout());

    JLabel title = new JLabel("Image : ");
    ImageIcon image = new ImageIcon("C:\\Users\\Akshay\\Desktop\\allfiles\\sampleposter.jpg"); //line #1 
    JLabel l = new JLabel("");
    l.setIcon(image); // line #2
    frame.add(title);
    frame.add(l);

Following is the output. I am getting an empty frame instead of two jlabels.

enter image description here

On commenting line #2 in the code i.e. -

l.setIcon(image);

I get the same output instead of two simple JLabels

On commenting both line #1 and line #2 , I am getting the two labels (one empty) as shown below.

enter image description here

How do I display the image properly with the other label? What could be the problem here?


Solution

    • you added JLabel title = new JLabel("Image : "); to the already visible Swing GUI, after setVisible(true); was called,

    • move code lines creating JLabel with ImageIcon before frame.setVisible(true);

    • move code line frame.setLayout(new FlowLayout()); before frame.setVisible(true);