简体   繁体   中英

Java: Displaying image in JFrame

I'm having difficulties linking my "fish.png" image so that it can appear in a JFrame. Here's a bit of code that I've modified from online:

package evolution;

import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Image extends JFrame {

    public Image() {

        this.getContentPane().setLayout(new FlowLayout());
        JLabel label1 = new JLabel("Example Text");
        ImageIcon icon = new ImageIcon("fish.png");
        JLabel label2 = new JLabel(icon);

        add(label1);
        add(label2);
    }

    private static void createAndShowGUI() {

        JFrame frame = new Image();
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        createAndShowGUI(); 
    }
}

The "Example Text" label appears, so I know the JFrame works. I've put the same "fish.png" in the src folder (where this class is) and one level up in the main folder (where the src folder is), but the JFrame only shows the text label and not the image. How can I link this properly?

Use:

ImageIcon icon = new ImageIcon(getClass().getResource("fish.png"));

Put the fish.png file right next to your source file (really the class file). This works even if it is inside a jar file if you include it.

Find the directory in which Eclipse stores your project files and put the image in that directory. I tried it and worked.

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