ImageIcon 不会显示图像
ImageIcon will not display image
我无法显示图像。我已经尝试了 ImageIO 和 ImageIcon。
这是我的代码:
public TestGUImain()
{
JFrame frame = new JFrame("Basic Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JLabel lblText = new JLabel("Hello World", JLabel.CENTER);
lblText.setBounds(10, 10, 100, 200);
panel.add(lblText);
ImageIcon image = new ImageIcon(getClass().getResource("150_leading_side_prep.jpg"));
JLabel lblImage = new JLabel(image, JLabel.CENTER);
lblImage.setBounds(0, 0, 800, 600);
panel.add(lblImage);
}
P.S。如果 JLabel
更改为包含文本,它 将 显示。图像存储在与 src 文件夹同一级别的名为 resource 的源文件夹中。
图片需要存放在src文件夹中,不能和它在同一层级。您还需要在构造函数的末尾执行 frame.setVisible(true),或者使用 revalidate();
和 repaint();
来刷新您的 window.
我无法显示图像。我已经尝试了 ImageIO 和 ImageIcon。
这是我的代码:
public TestGUImain()
{
JFrame frame = new JFrame("Basic Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JLabel lblText = new JLabel("Hello World", JLabel.CENTER);
lblText.setBounds(10, 10, 100, 200);
panel.add(lblText);
ImageIcon image = new ImageIcon(getClass().getResource("150_leading_side_prep.jpg"));
JLabel lblImage = new JLabel(image, JLabel.CENTER);
lblImage.setBounds(0, 0, 800, 600);
panel.add(lblImage);
}
P.S。如果 JLabel
更改为包含文本,它 将 显示。图像存储在与 src 文件夹同一级别的名为 resource 的源文件夹中。
图片需要存放在src文件夹中,不能和它在同一层级。您还需要在构造函数的末尾执行 frame.setVisible(true),或者使用 revalidate();
和 repaint();
来刷新您的 window.