java - 图像未显示在 JFrame 中

标签 java image swing jframe jlabel

我刚刚开始学习 java GUI,图像方面有很多问题。我也浏览了这个网站和其他网站上的多个主题,但由于某种原因我无法让它发挥作用(尽管我可能犯了很多错误,但我只是没有意识到)。我只想从在屏幕上显示图像开始。添加一些信息 - 我正在使用 IntelliJ;该图像存储在我标记为“库根”的资源文件夹中(此外,该图像非常小 - 16x16,但我也尝试过使用更大的图像,但它对我没有帮助)。

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

public class Frame {

    public static final int WIDTH = 1024;
    public static final int HEIGHT = 768;

    public Frame()
    {
        JFrame frame = new JFrame();
        frame.setTitle("Shady Path");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.pack();
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().setBackground(Color.BLACK);
        frame.setResizable(false);

        //Font font = new Font(Font.MONOSPACED, Font.PLAIN, 10);
        JLabel human = new JLabel(new ImageIcon(getClass().getResource("/human.jpg")));
        Dimension humanDimension = new Dimension(150, 150);
        human.setMinimumSize(humanDimension);
        human.setPreferredSize(humanDimension);
        human.setMaximumSize(humanDimension);
        human.setLocation(100, 100);

        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.add(human);
        frame.add(panel);

        frame.setVisible(true);
    }
}

最佳答案

不要将布局设置为 null。

关于java - 图像未显示在 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657045/

相关文章:

java - 如何从 LinkedList 中删除中间节点?

c# - 如何将二进制数据转换为图片显示在div标签或img标签中?

c++ - 如何使用 openimageIO 将 RGB 值存储在数组中? (使用 C++、OpenGL)

java - 想要取消选择表格单元格

java - "Exception in thread "main"java.lang.NoClassDefFoundError : javafx/embed/swing/JFXPanel"mean and how do I fix it? 是什么意思

java - 如何删除 Java Swing 中的行?

java - 由于 kafka log4jappender,启动 yarn 作业时出现异常

java - Logic.class.getResource ("effects\\newball.wav");返回空值

Java 8 lambda 错误 : filter stream by reduced filter collection THEN map THEN collect

image - Prestashop img 文件夹太大(几乎 40GB)