Java ImageIcon/Icon and JLabel is not working

冷暖自知 提交于 2019-12-22 10:09:58

问题


Why is it that my code is not showing the image that I inserted? there's no compilation error or Syntax error but why is it like that?

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

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

回答1:


if the "pie.png" is in the same Path of FirstUI.class try to use:

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



回答2:


I tried this exact code, and it worked. It looks like pie.png cannot be found. If you're using eclipse, put it in the project root (The same folder that has /bin and /src). Otherwise, put it in the same directory where you run the java command from.



来源:https://stackoverflow.com/questions/8168371/java-imageicon-icon-and-jlabel-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!