java - Netbeans ImageIcon 不显示

标签 java image netbeans imageicon gui-builder

我正在使用 NetBeans GUIBuilder 来制作 JPanel 表单。我添加了一个 JLabel 并使用 NetBeans 的界面为其提供一个来自外部图像 (.png) 的图标。路径已验证并且图像显示在 GUIBuilder 屏幕上。当我单击“预览设计”按钮时它甚至会出现。当我运行项目时它不会显示。 GUI 的其余部分按其应有的方式显示。你们中有人知道为什么会发生这种情况和/或如何解决它吗?

你们中的很多人都在要求获得 SSCCE。由于代码是由 NetBeans Form Builder 生成的,因此我包含了制作 JLabel 所采取的步骤。重点区域用红色圈出。

  1. 将 JLabel 拖放到表单生成器中。 Drag and drop a JLabel into the Form Builder.

  2. 打开 JLabel 的属性菜单。在 text 字段中输入空字符串 ("")。单击图标旁边的省略号。 Open up the JLabel's properties menu. Click the ellipsis next to icon.

  3. 选择外部图像并单击省略号。 Select External Image and click the ellipsis.

  4. 选择所需的图像。就我而言,它是 .png。 Select the image of choice.

  5. 请注意,图像出现在图标预览中。 Notice that the image appears in the icon preview.

  6. 关闭图标菜单和属性菜单,您会注意到该图像在表单生成器上显示为 JLabel 的图标。 Close the icon menu and the properties menu, and notice that the image appears on the Form Builder.

感谢您接受非正统的 SSCCE,并提前感谢您的帮助。

最佳答案

经过一番惨痛的教训,我发现依赖 Netbeans GUI 构建器来为您完成所有工作是一个错误。

只需创建一个如下所示的图标获取类,将图标放入其包中,并使用“自定义代码”而不是“图像选择器”。当然,这些图标在 NB 内是不可见的。但如果它们在应用程序运行时出现,谁会在乎呢。

package com.example.resource.icons;

import javax.swing.ImageIcon;

public class IconFetch {

    private static IconFetch instance;

    private IconFetch(){
    }

    public static IconFetch getInstance() {
        if (instance == null)
            instance = new IconFetch();
        return instance;
    }

    public ImageIcon getIcon(String iconName) {
        java.net.URL imgUrl = getClass().getResource(iconName);
        if (imgUrl != null) {
            return new ImageIcon(imgUrl);
        } else {
            throw new IllegalArgumentException("This icon file does not exist");
        }
    }

    public static final String MINESWEEPER_ONE = "one.png";
}

用法:

IconFetch.getInstance().getIcon(IconFetch.MINESWEEPER_ONE);

如果尝试此操作后图标仍然没有显示,则您在表单中布置组件的方式可能有问题(标签在那里,但您看不到它)。

希望这会有所帮助,尽管可能性不大。

关于java - Netbeans ImageIcon 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876742/

相关文章:

java - GWT - 从 FormPanel 上传文件后返回对象吗?

java - 在 Java 中执行 "tar -ztf"命令时出现问题

jquery - 通过缩略图悬停进行图像交换?

java - 构建maven项目时不应该包含web.xml吗?网 bean

java - java.lang.Math.PI 等于 GCC 的 M_PI 吗?

html - CSS3背景随机切割我的图像

python 嵌入式图像雷鸟

netbeans - 如何在Netbeans中编码模板变量以大写|小写|大写?

maven - Tomcat 在 netbeans 中两次部署相同的应用程序

java - 在泛型方法中使用 instanceof