Java 图标常量 - 静态常量可以吗?

发布于 2024-07-10 13:31:44 字数 1019 浏览 5 评论 0原文

我在整个应用程序中使用了许多图标 - 让我们以“确定/取消”图标为例。 目前它们可能是一个勾号和一个十字(tick.png、cross.png),但我将来可能想替换它们。 另外,我想将资源路径保留在一处。

这样可以吗:

public class Icons {
    public static Icon OK = new ImageIcon(Icons.class.getResource("/icons/tick.png");
    public static Icon CANCEL = new ImageIcon(Icons.class.getResource("/icons/cross.png");
}

或者我应该以不同的方式来做这件事? 我不介意在运行时依赖图像文件的存在,因为它们位于 .jar

解决方案

中。我使用了 Bent 的想法进行初始化,并且将常量定为最终值:

public final class Icons {
    private static final Logger logger = Logger.getLogger(Icons.class);

    public static final Icon OK = icon("/icons/add.png");
    public static final Icon CANCEL = icon("/icons/cancel.png");

    private static Icon icon(String path) {
        URL resource = Icons.class.getResource(path);
        if(resource==null) {
            logger.error("Resource "+path+" does not exist");
            return new ImageIcon();
        }
        return new ImageIcon(resource);
    }
}

I have a number of icons used throughout an application - let's take ok/cancel icons as an example. At the moment they might be a tick and a cross (tick.png, cross.png) but I may want to replace them in future. Also, I would like to keep the resource path in one place.

Is this ok:

public class Icons {
    public static Icon OK = new ImageIcon(Icons.class.getResource("/icons/tick.png");
    public static Icon CANCEL = new ImageIcon(Icons.class.getResource("/icons/cross.png");
}

Or should I be doing this a different way? I don't mind relying on the existence of the image files at runtime since they're in the .jar

Solution

I've used Bent's idea for initialisation, and I've made the constants final:

public final class Icons {
    private static final Logger logger = Logger.getLogger(Icons.class);

    public static final Icon OK = icon("/icons/add.png");
    public static final Icon CANCEL = icon("/icons/cancel.png");

    private static Icon icon(String path) {
        URL resource = Icons.class.getResource(path);
        if(resource==null) {
            logger.error("Resource "+path+" does not exist");
            return new ImageIcon();
        }
        return new ImageIcon(resource);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡看悲欢离合 2024-07-17 13:31:44

我看到两个问题,两者都可能是可以接受的:

  1. 如果找不到您的图标或由于某些原因无法加载图标,则调试将变得困难。 在静态初始化程序中运行的代码可能很棘手,因为很容易“丢失”异常。
  2. 该类可能永远不会被卸载,因此图标使用的资源永远不会被释放。

如果您可以确保图标始终存在,甚至可以通过将初始化放在静态初始化程序块中并添加良好的异常处理和日志记录来解决,则数字 1 可能是可以接受的。

数字 2 可能是可以接受的,因为图标通常在应用程序的整个运行时使用,并且无论如何在应用程序退出之前它们都不会被释放。

总而言之,我想说这很好。

I see two problems with that, both might be acceptable:

  1. It will get hard to debug if your icons are not found or can't be loaded for some reasons. Code that runs in static initializers can be tricky, because it's easy to "loose" the exception.
  2. The class will probably never be unloaded and therefore the resource used by the Icons will never bee freed.

Number 1 is probably acceptable if you can make sure that the icons are always there and can even be worked around by putting the initialization in a static initializer block and adding good exception handling and logging.

Number 2 is probably acceptable since icons are usually used throughout the entire runtime of the application and they wouldn't be freed long before the application quits anyway.

So all in all I'd say that's fine.

落花浅忆 2024-07-17 13:31:44

您可能希望将常量标记为最终常量。

You may want to mark the constants as final.

违心° 2024-07-17 13:31:44

如果你想将图标保留为静态常量,我会将 ImageIcon 对象的实例化提取到静态方法中;

public static final Icon ok = icon("ok.png");


private static Icon icon(String path) {

    URL resource = Icons.class.getResource("/icons/" + path);
    if (resource == null) {
        // Log something...
        return null;
    }
    return new ImageIcon(resource);
}

这样,每当出现故障时,您就可以进行控制,并且不必在实例化中重复自己。

另外,我会将常数定为最终常数。

更通用的方法可能是使用反射来检查 Icons 类并为类中的每个公共静态 Icon 字段加载资源。 这样,你只需要声明一个新的 Icon 常量,相应的资源就会根据常量的名称自动加载。 如果您需要更多提示,请发表评论。

If you want to keep you icons as static constants, I would extract the instantiation of the ImageIcon objects into a static method;

public static final Icon ok = icon("ok.png");


private static Icon icon(String path) {

    URL resource = Icons.class.getResource("/icons/" + path);
    if (resource == null) {
        // Log something...
        return null;
    }
    return new ImageIcon(resource);
}

This way you have control whenever something fail, and you don't have to repeat yourself in the instantiation.

Also, I would make the constants final.

A more general approach could be to use reflection to inspect your Icons-class and load resources for each public static Icon field in the class. This way, you would only have to declare a new Icon constant, and the corresponding resource would be loaded automatically based on the name of the constant. Leave a comment if you want more tips for doing this.

蓝梦月影 2024-07-17 13:31:44

这似乎是一个相当简单的方法。 尽管我会使用与它们的用途相同的名称来命名图像(“ok.png”,“cancel.png”)。 并确保清楚删除或重命名图像可能会导致问题。

That seems to be a fairly easy way to do that. Although I would name the images with the same name as what they are for ("ok.png", "cancel.png"). And make sure that it is clear that removing or renaming the images may cause issues.

烟柳画桥 2024-07-17 13:31:44

这似乎是标准的做事方式,但我以前遇到过问题。

如果您将 Eclipse 与 Maven 一起使用并将这些图标存储在 maven 的资源目录中,那么当 Eclipse 执行其自动构建之一时,它不会将图标文件复制到您的 target/classes 目录中。 当找不到图标时,这将导致运行时异常。

您必须至少手动执行一次 Maven 打包才能将图标放在正确的位置。

This seems to be the standard way of doing things, but I have had issues with before.

If you are using Eclipse with Maven and store these icons in maven's resource directory, when Eclipse does one of its automatic builds, it won't copy the icon files to your target/classes directory. This will cause a runtime exception when it can't find the icons.

You have to manually do a maven package at least once to get the icons in the right spot.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文