简体   繁体   English

向JLabel添加ImageIcon

[英]Adding an ImageIcon to a JLabel

My program will run, and a button will appear, but the image which is in the res folder that is in a referenced library will not appear ( egg.png ). 我的程序将运行,并且将出现一个按钮,但不会出现所引用库中res文件夹中的图像( egg.png )。 There are no errors, but I'm confused as to why it won't run properly. 没有错误,但是我对为什么它无法正常运行感到困惑。

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);
  }
}

try this:- for eg:- if image is in icons folder in resource:- 试试这个:-例如:-如果图像在资源的图标文件夹中:-

private final ImageIcon imageIcon = new ImageIcon(getClass().getClassLoader().getResource("icons/image.png")); 私有的最终ImageIcon imageIcon = new ImageIcon(getClass()。getClassLoader()。getResource(“ icons / image.png”)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM