[英]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);
}
}
我是初學者,剛剛學習JFrame
,你們能告訴我為什么圖像沒有顯示嗎? 我已將圖像(logo.png)放在 class 所在的文件夾中。 我使用 VSCode 作為 IDE。 提前致謝!!
除塵舊的 NetBeans 並給它一個 go...
你會想要這樣做:
ImageIO.read(getClass().getResource("logo.png"))
本質上,圖像作為資源捆綁在您的 jar 文件中,為了正確提取它,您需要Class#getResource(string name)
這是我的完整示例,其中包含我的圖像放置截圖:
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);
}
}
產生:
如果您的徽標可能在嵌套的 java package 內,如下所示:
您只需執行以下操作:
ImageIO.read(getClass().getResource("images/logo.png"))
更新:
正如@camickr 提到的,在JFrame
可見之前將所有組件添加到它。
此外,所有 Swing 組件都應通過SwingUtilities.invokeLater
在 EDT 上創建,如我的示例中所示。
非常感謝所有試圖幫助我的人!!
我用了:
java.net.URL imageURL = app.class.getResource("download.png");
ImageIcon img = new ImageIcon(imageURL);
有效!! 我把它提到這里!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.