Image display in JFrame

14,532

Solution 1

I try it on my computer and image is showing up on icon. If you want show the image on background try this :

import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.*;

        public class Caine extends JFrame{
        //the pictures
        ImageIcon guy = new ImageIcon("tester.gif");
        JLabel pn = new JLabel(guy);
        JPanel panel = new JPanel();

        Caine(){
            super("Photuris Lucicrescens");

            //Important
            setSize(700,600);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            add(panel);
            setVisible(true);
            JLabel im = new JLabel(new ImageIcon("iconImage.gif"));
            setIconImage(customIcon);
            panel.add(im);
            add(pn);
        }
        }

Solution 2

The problem is that you add two components to the JFrame. When you add a Component to a JFrame, it actually adds it to its content pane. By default, the content pane uses the BorderLayout as its LayoutManager. If you don't set a constraint, the component is considered to be in the center. Therefore, here you have two components that are in the center and receives the same bounds from the LayoutManager, resulting in only one component to be shown, the other being hidden. This is why you see the JPanel and not the JLabel.

If you want to see the JLabel, then don't add that panel to the frame.

Other remarks:

  • setVisible() should be invoked after you have created your component hierarchy.
Share:
14,532
Ben Hagel
Author by

Ben Hagel

I'm an enthusiast programmer seeking answers to questions and problems.

Updated on June 04, 2022

Comments

  • Ben Hagel
    Ben Hagel almost 2 years

    I'm just wondering why this 100x100 px .gif image isn't showing up on the screen. The image is in the same directory, so the program should have no problem finding it. Does anybody know how to solve this problem?

    import java.awt.*;
    import java.awt.image.ImageObserver;
    import java.io.File;
    import javax.imageio.*;
    import javax.swing.*;
    
    public class Window extends JFrame{
    //the pictures
    ImageIcon guy = new ImageIcon("tester.gif");
    JLabel pn = new JLabel(guy);
    JPanel panel = new JPanel();
    
    Window(){
        super("Photuris Lucicrescens");
    
        //Important
        setSize(700,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(panel);
        setVisible(true);
        //Decoration
        Image customIcon = Toolkit.getDefaultToolkit().getImage("iconImage.gif");
        setIconImage(customIcon);
        //Adding the image
        add(pn);
    }
    }