java 如何在 Swing 中全局设置应用程序的图标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/103179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set an Application's Icon Globally in Swing?
提问by Allain Lalonde
I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget.
我知道我可以为每个表单或根表单指定一个,然后它会级联到所有的子表单,但我想有一种方法来覆盖所有表单的默认 Java 咖啡杯,即使是那些我可能会忘记。
Any suggestions?
有什么建议?
采纳答案by Paul Brinkley
You can make the root form (by which I assume you mean JFrame) be your own subclass of JFrame, and put standard functionality in its constructor, such as:
您可以使根形式(我假设您的意思是JFrame)成为您自己的子类JFrame,并将标准功能放入其构造函数中,例如:
this.setIconImage(STANDARD_ICON);
You can bundle other standard stuff in here too, such as memorizing the frame's window metrics as a user preference, managing splash panes, etc.
您也可以在此处捆绑其他标准内容,例如将框架的窗口指标作为用户首选项记忆,管理启动窗格等。
Any new frames spawned by this one would also be instances of this JFramesubclass. The only thing you have to remember is to instantiate your subclass, instead of JFrame. I don't think there's any substitute for remembering to do this, but at least now it's a matter of remembering a subclass instead of a setIconImagecall (among possibly other features).
由该框架产生的任何新框架也将是该JFrame子类的实例。您唯一需要记住的是实例化您的子类,而不是JFrame. 我认为没有任何替代方法可以代替记住这样做,但至少现在是记住子类而不是setIconImage调用(可能还有其他功能)的问题。
回答by John Gardner
There is another way, but its more of a "hack" then a real fix....
还有另一种方法,但它更像是一种“黑客”,然后才是真正的修复......
If you are distributing the JRE with your Application, you could replace the coffee cup icon resource in the java exe/dll/rt.jar wherever that is with your own icon. It might not be very legit, but it is a possibility...
如果您将 JRE 与您的应用程序一起分发,您可以将 java exe/dll/rt.jar 中的咖啡杯图标资源替换为您自己的图标。这可能不是很合法,但这是一种可能性......
回答by John Gardner
Also, if you have one "main" window, and set its icon properly, as long as you use that main window as the "parent" for any Dialog classes, they will inherit the icon. Any new Frames need to have the icon set on them, though.
此外,如果您有一个“主”窗口,并正确设置其图标,只要您将该主窗口用作任何 Dialog 类的“父”窗口,它们就会继承该图标。但是,任何新框架都需要在其上设置图标。
as Paul/Andreas said, subclassing JFrame is going to be your best bet.
正如保罗/安德烈亚斯所说,子类化 JFrame 将是你最好的选择。
回答by Andreas Bakurov
Extend the JDialog class (for example name it MyDialog) and set the icon in constructor. Then all dialogs should extend your implementation (MyDialog).
扩展 JDialog 类(例如将其命名为 MyDialog)并在构造函数中设置图标。然后所有对话框都应该扩展您的实现(MyDialog)。

