java - 图像未出现在 JFrame 中
问题描述
import javax.swing.*;
public class GUI {
public static void main(String s[]) {
ImageIcon image = new ImageIcon("logo.png");
JFrame frame = new JFrame();
JLabel label = new JLabel();
label.setIcon(image);
label.setText("Boom");
frame.setTitle("SJ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
frame.add(label);
}
}
我是初学者,刚刚学习JFrame
,你们能告诉我为什么图像不显示吗?我已将图像(logo.png)放在该类所在的文件夹中。我正在使用 VSCode 作为 IDE。提前致谢!!
解决方案
掸掉旧的 NetBeans 并试一试......
你会想要这样做:
ImageIO.read(getClass().getResource("logo.png"))
本质上,图像作为资源捆绑在您的 jar 文件中,为了正确提取它,您需要 Class#getResource(string name)
这是我的完整示例,其中包含我的图像放置截图:
测试应用程序.java:
import java.awt.Image;
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;
import javax.swing.SwingUtilities;
public class TestApp {
public TestApp() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestApp();
}
});
}
private void initComponents() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResource("logo.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon(img));
frame.add(label);
frame.pack();
frame.setVisible(true);
}
}
产生:
如果您的徽标可能在嵌套的 java 包中,如下所示:
您只需执行以下操作:
ImageIO.read(getClass().getResource("images/logo.png"))
更新:
正如@camickr 提到的,JFrame
在使其可见之前将所有组件添加到。
此外,所有 Swing 组件都应在 EDT 上创建,SwingUtilities.invokeLater
如我的示例中所示。
推荐阅读
- c# - C# 中的“System.Object”错误是否有修复?
- java - 检查 ImageView 是否应用了 ColorFilter?
- javascript - XML 加密和解密
- reactjs - 使用 Material UI 的 makeStyle 为组件的 [aria-checked="true"] 设置样式
- java - OpenGL\JOML:在缩放矩阵时防止不需要的平移
- python - Python,无法将字符串转换为浮点数:'7a'
- javascript - 在 jquery Datatable 中显示数据
- database - 如何更新 mongo 数据库集合中的数组
- flutter - Flutter TTS(文本到语音) - 是否有可能以及如何获取 iOS 语音的语言代码?
- android - 远程调试 AOSP 框架服务