[英]Image doesn't appear in the 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);
}
}
I am beginner and just learning JFrame
, can you guys tell me why isn't the image showing up?我是初学者,刚刚学习
JFrame
,你们能告诉我为什么图像没有显示吗? I have placed the Image (logo.png) in the folder where is that class.我已将图像(logo.png)放在 class 所在的文件夹中。 I am using VSCode as IDE.
我使用 VSCode 作为 IDE。 Thanks in advance!!
提前致谢!!
Dusted off the old NetBeans and gave it a go...除尘旧的 NetBeans 并给它一个 go...
You would want to do this:你会想要这样做:
ImageIO.read(getClass().getResource("logo.png"))
Essentially the image is bundled in your jar file as a resource and in order to correctly extract it you need the Class#getResource(string name)本质上,图像作为资源捆绑在您的 jar 文件中,为了正确提取它,您需要Class#getResource(string name)
Here is my full example with screenshot of my image placement:这是我的完整示例,其中包含我的图像放置截图:
TestApp.java: TestApp.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);
}
}
Which produces:产生:
If your logo is perhaps inside nested java package like this:如果您的徽标可能在嵌套的 java package 内,如下所示:
You would simply do:您只需执行以下操作:
ImageIO.read(getClass().getResource("images/logo.png"))
Update:更新:
As @camickr mentioned add all components to the JFrame
before making it visible.正如@camickr 提到的,在
JFrame
可见之前将所有组件添加到它。
Also all Swing components should be created on the EDT via SwingUtilities.invokeLater
as also shown in my example.此外,所有 Swing 组件都应通过
SwingUtilities.invokeLater
在 EDT 上创建,如我的示例中所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.