Do I need another method to use the ColorFactory class?

六月ゝ 毕业季﹏ 提交于 2019-12-18 09:09:06

问题


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 a String colorName via the constructor and store the name in a field for later reference; the panel's backgroundColor is 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!