Java ImageIcon / Icon和JLabel无法正常工作

为什么我的代码没有显示我插入的图像? 没有编译错误或语法错误,但为什么会这样?

import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.SwingConstants; public class FirstUI extends JFrame{ private JLabel firstlabel; private JLabel secondLabel; private JLabel pie; public FirstUI(){ super("Tittle"); setLayout(new FlowLayout()); firstlabel = new JLabel("Hello World"); firstlabel.setToolTipText("Hello World"); String path = "pie.png"; Icon pie = new ImageIcon(path); secondLabel = new JLabel("Text with icon",pie,SwingConstants.LEFT); add(secondLabel); add(firstlabel); } } 

主要class级

 import javax.swing.JFrame; public class FirstUiTest { public static void main(String[] args){ FirstUI MyUI = new FirstUI(); MyUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyUI.setSize(320,280); MyUI.setVisible(true); } } 

如果“pie.png”与FirstUI.class路径相同, FirstUI.class尝试使用:

 Icon pie = new ImageIcon(ImageIO.read( FirstUI.class.getResourceAsStream( "pie.png" ) ) ); 

我尝试了这个确切的代码,并且它有效。 看起来像找不到pie.png。 如果您正在使用eclipse,请将其放在项目根目录中(与/ bin和/ src相同的文件夹)。 否则,将它放在运行java命令的同一目录中。