Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 向JLabel添加图像图标_Java_Image_Swing_Jbutton_Imageicon - Fatal编程技术网

Java 向JLabel添加图像图标

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

我的程序将运行,并会出现一个按钮,但引用库中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 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”的效果