问题
I just found this really great ColorFactory class that I am using in my first Swing project. 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.
Code:
frame.setContentPane(ContentPaneCreator.createContentPane("darkorange"));`
Question:
Do I need the public final void setBackground(Color color, JPanel contentPane) method at all? Can everything be done inside createContentPane() method instead? 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);
}
)
回答1:
Several things may bear closer scrutiny:
As you plan to extend
JPanel, supply aString colorNamevia the constructor and store the name in a field for later reference; the panel'sbackgroundColoris a bound property.The static factory,
ColorFactory.getInstance(), should be re-factored to use the initialization-on-demand holder idiom.The code, excerpted from the Lobo Project, may have since been updated.
The names appear to be standard.
回答2:
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
来源:https://stackoverflow.com/questions/11679985/do-i-need-another-method-to-use-the-colorfactory-class