图像未显示在 JFrame 中
Image not showing in a JFrame
我刚开始学习java GUI,我对图像有很多问题。我浏览了这个网站和其他网站上的多个主题,但出于某种原因我无法让它工作(尽管我可能犯了很多错误而且我只是没有意识到)。我只想从在屏幕上显示图像开始。要添加一些信息——我正在使用 IntelliJ;图像存储在我标记为 "library root" 的资源文件夹中(另外,图像非常小 - 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);
}
}
不要将布局设置为空。
我刚开始学习java GUI,我对图像有很多问题。我浏览了这个网站和其他网站上的多个主题,但出于某种原因我无法让它工作(尽管我可能犯了很多错误而且我只是没有意识到)。我只想从在屏幕上显示图像开始。要添加一些信息——我正在使用 IntelliJ;图像存储在我标记为 "library root" 的资源文件夹中(另外,图像非常小 - 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);
}
}
不要将布局设置为空。