Java ImageIcon/Icon 和 JLabel 不工作

标签 java image swing icons

为什么我的代码没有显示我插入的图像?没有编译错误或语法错误,但为什么会这样呢?

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/

相关文章:

java - JTable 在更改时加载值,加载时显示进度条

java - 在 JFrame 中看不到 JPanel 它包含在

java - 家庭作业帮助 Pt2(数学复杂课)

java - 无法在Eclipse中执行Gradle构建

Android - 从图库加载图像并设置为背景

image - 在 JavaFX 2.0 中将 ScatterChart 的图像复制到系统剪贴板

java - Jprogressbar.setStringpainted(true);正在画两个字符串

java - Spring 启动应用程序 : how to set profile propery with spel?

java - Elasticsearch 返回没有父对象的嵌套对象

css - 使用 CSS 剪影 PNG 图像