问题描述
我正在尝试让图像出现在我的 JFrame 中。但是,此图像仅在我最大化 GUI 窗口时出现。我的图片位于我的 src 文件夹中。我想知道我是否错误地实现了 JFrame。
更新代码
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloSEOperation
(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JLabel(new ImageIcon("logo.png")));
frame.pack();
frame.setVisible(true);
解决方法
简单的例子。
图像放置在 stof
包中。该示例使用 ImageIO
加载图像。原因有两个。
- 如果出现问题,则会引发异常,以便您进行诊断
-
ImageIO.read
在图像完全加载之前不会返回。这意味着,与ImageIcon
不同,一旦调用返回,您就知道图像可用于渲染。请记住,如果图像很大并且您在事件调度线程中执行此操作,则会导致 UI“停滞”
示例
import java.awt.EventQueue;
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;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
BufferedImage image = ImageIO.read(Test.class.getResource("/stof/Background.png"));
JFrame frame = new JFrame();
frame.add(new JLabel(new ImageIcon(image)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}