Java 向JLabel添加图像图标
我的程序将运行,并会出现一个按钮,但引用库中res文件夹中的图像不会出现(Java 向JLabel添加图像图标,java,image,swing,jbutton,imageicon,Java,Image,Swing,Jbutton,Imageicon,我的程序将运行,并会出现一个按钮,但引用库中res文件夹中的图像不会出现(egg.png)。没有错误,但我不明白为什么它不能正常运行 package gui; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; public class IconButton { public static void main(String a
egg.png
)。没有错误,但我不明白为什么它不能正常运行
package gui;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class IconButton {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("C:\\Users\\Jack Young\\Desktop\\Egg game Sprites");
JButton button = new JButton();
button.setIcon(image);
frame.add(button);
frame.setSize(300, 200);
frame.setResizable(false);
frame.setVisible(true);
}
}
试试这个:-例如:-
如果图像位于资源中的图标文件夹中:-
private final ImageIcon ImageIcon=新的ImageIcon(getClass().getClassLoader().getResource(“icons/image.png”) 您提到了
“egg.png”
,但使用了“C:\\Users\\Jack Young\\Desktop\\egg game Sprites”
。。。所以我并不惊讶,只要文件名正确,这就行了。你也提到了“res”文件夹,但该路径没有提到任何“res”文件夹在我发布的代码中,我已经发布了来自我的计算机的路径,但它不起作用,所以我试着将其更改为我res文件夹中的egg.png。但只是新建图像图标(“egg.png”)代码>也不会剪切它,因为它将查看项目的根。请看,我能够通过使用“C:\\Users\\Jack Young\\Desktop\\Eclipse\\GUI\\res\\egg.png”使其工作。有没有办法将其简化为“egg.png”的效果