views:

34

answers:

1

I'm working a java+swing+miglayout project we settled on a class design for graphical classes that inherits from JPanel & JFrame, here is the skelletons :

class GammaFrame extends JFrame {
private JPanel __pane__ = null;

public static GammaFrame open(...) {

    _instance = GammaFrame()

    __pane__ = _instance.getContentPane();
    __pane__.setLayout(new MigLayout(...));

    _instance.__init__()

    # do logic job if any

    return _instance;
    }

    public static void main(String argv[]) {
        GammaFrame.open();
    }
}

class GammaPanel extends JPanel {

public static GammaPanel create(...) {

    _instance = GammaPanel()

    _instance.setLayout(new MigLayout(...));

    _instance.__init__()

    # do logic job if any

    return _instance;
    }

    public static void main(String argv[]) {
        JPanel panel = GammaPanel.create()
        JFrame frame = new JFrame()
        frame.getContentPane().add(panel)

        # 
        # more settings here
        # 

        frame.setVisible(true)
    }
}

what may be the flaws of this design ?

+3  A: 

The major drawback I see is the fact that your GammaPanel is not automatically used inside the GammaFrame class.

You shouldn't use a main method to generate the GUI. You should let the constructor of GammaFrame handle instantiating its components and showing them; otherwsie you will have to instantiate everything in the main method, but this is unsuitable if you have multiple frames and many components.

Usually you tend to encapsulate a whole frame, with its content, in just one class that may have inner classer for custom components (like your GammaPanel).

If you plan to have shared components, like a custom graph, you can declare it separately and then instantiate and use it in different frames.

It is critical that you build your GUI components on the event dispatch thread.

You may want to consider the benefits of model-view-controller design, as suggested in this example.

Jack