[英]Do I need another method to use the ColorFactory class?
I just found this really great ColorFactory
class that I am using in my first Swing project. 我刚刚发现我在第一个Swing项目中使用的这个非常出色的
ColorFactory
类。 It is really cool: I can now pass a named color from my main class, like "crimson" or "mediumaquamarine" for example, to the createContentPane
Container
method. 真的很酷:我现在可以将主类中的一种命名颜色(例如“绯红色”或“中等海蓝宝石”)传递给
createContentPane
Container
方法。
Code: 码:
frame.setContentPane(ContentPaneCreator.createContentPane("darkorange"));`
Question: 题:
Do I need the public final void setBackground(Color color, JPanel contentPane)
method at all? 我是否完全需要
public final void setBackground(Color color, JPanel contentPane)
方法? Can everything be done inside createContentPane()
method instead? 可以在
createContentPane()
方法内完成所有操作吗? Thank you for your help. 谢谢您的帮助。
import java.awt.Color;
import java.awt.Container;
import javax.swing.JPanel;
public final class ContentPaneCreator extends JPanel {
private static final long serialVersionUID = 1L;
public static Container createContentPane(String color) {
JPanel contentPane = new JPanel();
// awesome txt to Color conversions using the ColorFactory().getColor();
// written by The Lobo Project
new ContentPaneCreator().setBackground(
new ColorFactory().getColor(color), contentPane);
contentPane.setOpaque(true);
return contentPane;
}
public final void setBackground(Color color, JPanel contentPane) {
contentPane.setBackground(color);
}
)
Answer to your question - I can't see why (or why you needed to start with, but hay). 回答您的问题-我不明白为什么(或为什么您需要从头开始,但干草)。
Extended answer: 扩展答案:
It should be: (if we're looking at the same piece of code) 应该是:(如果我们正在看同一段代码)
ColorFactory.getInstance().getColor(colorName);
Other wise you creating the color map on each instantiation, which is just a waste. 否则,您将在每个实例上创建颜色图,这只是浪费。
I'm also not sure why you need to extend JPanel, but it's not my code :P 我也不确定为什么需要扩展JPanel,但这不是我的代码:P
Several things may bear closer scrutiny: 可能需要仔细检查以下几件事:
As you plan to extend JPanel
, supply a String colorName
via the constructor and store the name in a field for later reference; 当您计划扩展
JPanel
,请通过构造函数提供String colorName
并将名称存储在字段中以供以后参考; the panel's backgroundColor
is a bound property. 面板的
backgroundColor
是绑定的属性。
The static factory , ColorFactory.getInstance()
, should be re-factored to use the initialization-on-demand holder idiom . 应该将静态工厂
ColorFactory.getInstance()
重构为使用按需初始化的持有人习惯用法 。
The code, excerpted from the Lobo Project , may have since been updated. 从Lobo项目中摘录的代码可能已更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.