简体   繁体   English

图片未显示在JFrame中

[英]Image not showing in a JFrame

I have just started learning java GUI and I have a lot of problems with the images. 我刚刚开始学习Java GUI,并且图像有很多问题。 I looked through multiple topics on this site and others too, but for some reason I cannot get this to work (though I am probably making a lot of mistakes and I just don't realise it). 我浏览了该站点上的多个主题以及其他主题,但是由于某些原因,我无法使它正常工作(尽管我可能犯了很多错误,但我只是没有意识到)。 I just want to start with showing an image on the screen. 我只想从在屏幕上显示图像开始。 To add some information - I am using IntelliJ; 要添加一些信息-我正在使用IntelliJ; the image is stored in a resource folder that I have marked as a "library root" (also, the image is pretty small - 16x16, but I have also tried with a bigger image and it doesn't help me). 该图像存储在一个我标记为“库根”的资源文件夹中(该图像非常小-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。

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

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