简体   繁体   English

Java:在JFrame中显示图像

[英]Java: Displaying image in JFrame

I'm having difficulties linking my "fish.png" image so that it can appear in a JFrame. 我在链接“ fish.png”图像时遇到困难,因此该图像可以显示在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. 出现“示例文本”标签,因此我知道JFrame可以工作。 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. 我已经在src文件夹(此类位于)中放置了相同的“ fish.png”,并在主文件夹(src文件夹所在的位置)中放置了一个级别,但是JFrame仅显示文本标签,而不显示图像。 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). fish.png文件放在源文件(实际上是类文件)旁边。 This works even if it is inside a jar file if you include it. 即使包含在jar文件中,它也可以工作。

Find the directory in which Eclipse stores your project files and put the image in that directory. 找到Eclipse在其中存储项目文件的目录,然后将映像放在该目录中。 I tried it and worked. 我尝试过并工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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