为什么我的代码没有显示我插入的图像?没有编译错误或语法错误,但为什么会这样呢?
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);
}
}
主类
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);
}
}
最佳答案
如果“pie.png”位于 FirstUI.class
的相同路径中,请尝试使用:
Icon pie = new ImageIcon(ImageIO.read( FirstUI.class.getResourceAsStream( "pie.png" ) ) );
关于Java ImageIcon/Icon 和 JLabel 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8168371/