Java ImageIcon/Icon and JLabel is not working

2019-05-10 10:41发布

问题:

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.