简体   繁体   中英

Image display in JFrame

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);
}
}

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.

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);
        }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM