本文介绍了Java ImageIcon / Icon和JLabel无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我的代码没有显示我插入的图像?没有编译错误或语法错误,但为什么会这样?
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);
}
}
主要类
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
尝试使用:
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" ) ) );
这篇关于Java ImageIcon / Icon和JLabel无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!