为所有 JComponent 设置默认设置的便捷方法是什么
我想要一种方法来为我在 GUI 中使用的所有组件设置默认设置,例如背景颜色、大小等,有什么方便的方法来做到这一点?所以当我做新的 JButton 或 JLabel 等时,它已经应用了设置吗?
I want a way to set default settings like, background colour, size etc. for all components I use in my GUI, what's a convenient way to do this? so when I do new JButton or JLabel etc. it will already have the settings applied?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以创建自己的外观或更改默认值使用 UIManager 的颜色,例如:
Also you can create your own look and feel or change default values of the colors using UIManager, like:
编写一个工厂方法,返回已应用默认值的组件,然后从工厂检索它们,而不是直接创建它们。
或者编写一个接受 JComponent 实例并设置所需默认值的方法,这些默认值可以在整个代码中重用。
或者结合使用两者。
另一种选择是创建并使用您自己的“外观”:
...但我猜这比您正在寻找的内容要复杂得多。
Write a factory method that returns your components with the defaults already applied, then retrieve them from the factory instead of directly creating them.
Or write a method that accepts an instance of a JComponent and sets the desired defaults, that can be reused throughout your code.
Or use a combination of both.
Another option is to create and use your own "Look and Feel":
... but I would guess that this is much more involved than what you're looking for.
它称为外观和感觉,您可以编写自己的并设置将其作为默认值或调整现有默认值。如果仅更改背景颜色等少数设置,我只需 修改一些默认值
设置默认大小似乎是一个奇怪的要求。例如,对于
JLabel
,首选大小(与默认大小相比与 Swing API 更好匹配)将取决于JLabel
的内容。您如何为所有组件定义“默认大小”?It is called a Look And Feel, and you can write your own and set it as the default or adjust the defaults of an existing one. For changing only a few settings like background color I would simply modify some defaults
Setting a default size seems a weird requirement. For example for a
JLabel
the preferred size (which matches better with the Swing API then default size) would depend on the contents of theJLabel
. How would you define a 'default size' for all components ?