【问题标题】:The way to put image on JLabel and JButton [duplicate]将图像放在 JLabel 和 JButton 上的方法 [重复]
【发布时间】:2021-12-15 15:33:12
【问题描述】:

我写这篇文章是因为我之前的问题被错误的答案链接关闭。

我在代码下方的 JLabel 上看不到图像

import javax.swing.*;

public class JButtonEx extends JFrame{

JButtonEx() {
    setSize(300,300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel(new ImageIcon("network/star.png"));
    add(label);
    setVisible(true);
}

public static void main(String[] args) {
    new JButtonEx();
}

【问题讨论】:

    标签: java swing components


    【解决方案1】:

    当你加载图片时,使用 getClass().getResource();

    ImageIcon icon = new ImageIcon(getClass().getResource("star.png"));
    

    【讨论】:

    • 上一个问题中标记的副本上的接受答案具有代码行ImageIO.read(getClass().getResource("/wood.jpeg"));。它不仅解决了您的代码的主要问题(使用getResource()),它还具有使用ImageIO 加载图像的功能,而这个答案没有。当代码尝试通过ImageIO 加载图像并失败时,会产生有用的堆栈跟踪。因此,这个答案比副本为后来的观众提供了 less 价值。这是噪音。
    • 但是当我使用 ImageIo 时,它不起作用
    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2017-02-21
    • 2011-08-20
    相关资源
    最近更新 更多