繁体   English   中英

图像未出现在 JFrame 中

[英]Image doesn't appear in the JFrame

import javax.swing.*;
public class GUI {
    public static void main(String s[]) {
        ImageIcon image = new ImageIcon("logo.png");

        JFrame frame = new JFrame();
        JLabel label = new JLabel();
        label.setIcon(image);

        label.setText("Boom");
        frame.setTitle("SJ");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.add(label);
    }  
}

我是初学者,刚刚学习JFrame ,你们能告诉我为什么图像没有显示吗? 我已将图像(logo.png)放在 class 所在的文件夹中。 我使用 VSCode 作为 IDE。 提前致谢!!

除尘旧的 NetBeans 并给它一个 go...

你会想要这样做:

ImageIO.read(getClass().getResource("logo.png"))

本质上,图像作为资源捆绑在您的 jar 文件中,为了正确提取它,您需要Class#getResource(string name)

这是我的完整示例,其中包含我的图像放置截图:

在此处输入图像描述

TestApp.java:

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TestApp {

    public TestApp() {
        initComponents();
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestApp();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        BufferedImage img = null;
        try {
            img =  ImageIO.read(getClass().getResource("logo.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        JLabel label = new JLabel(new ImageIcon(img));
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
    }
   
}

产生:

在此处输入图像描述

如果您的徽标可能在嵌套的 java package 内,如下所示:

在此处输入图像描述

您只需执行以下操作:

ImageIO.read(getClass().getResource("images/logo.png"))

更新:

正如@camickr 提到的,在JFrame可见之前将所有组件添加到它。

此外,所有 Swing 组件都应通过SwingUtilities.invokeLater在 EDT 上创建,如我的示例中所示。

非常感谢所有试图帮助我的人!!

我用了:

java.net.URL imageURL = app.class.getResource("download.png");
    ImageIcon img = new ImageIcon(imageURL);

有效!! 我把它提到这里

暂无
暂无

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

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