Search code examples
javauser-interfacedesign-patternspanelwrapper

How to build a good Java GUI application design pattern?


I'm wondering about Java GUI panels programming in a good way. My main concern is about methods, panels, labels, listeners, initializing - where?

Where i'm suppose to place these things, how i have to place them between panel and wrapper ( controller too maybe).

Let's say that I have to programm MenuPanel with MenuPanelWrapper containing some buttons and so on. How to do this in a best way?


Solution

  • I think the best way to create some Java UI is to use the MVC (model-view-controleur) pattern.

    Let's suppose that: we have a JButton, JLabel and a JTextField in our Java UI, like this :

    MVC step 1

    On the left we have the UI and on the right we have the design of the MVC. In this UI, the user can put some text in the JTextField, and display it in the JLabel by pressing the JButton.

    • The View contains the JLabel, because the View represents the data of the Model. (And in some case the View can also refresh the UI by hidding or adding some actions : like hidding/adding some JButton or removing some listener).
    • The Model contains the data to display, and retrieve the data send by the Controler. The Model is not directly visible in the UI. It's like a black box that we can just manipulate it by the Controler and see his data by the View.
    • The Controler contains the JButton and the JTextField. The Controler will change the value of the Model, and the Model will alert the View to refresh himself (in this case the JLabel).

    Step 1

    Now if the user change the value of the JTextField, this will affect the JtextField of the Controler.

    MVC step 2

    Step 2

    If the user press the JButton, the Controler will change the value of the Model.valueLabel by calling the setter of the Model.

    MVC step 3

    Step 3

    At this step, the Model will notify his View that the value of the Model.valueLabel has changed. And the View will refresh himself (by changing the value of the JLabel). Finally, the JLabel display the value of the data Model.

    MVC step 4

    Step 4 - In some case

    After the View has finished his refresh, he can refresh the Controler by adding or disabling some actions.

    MVC step 5


    EDIT

    P.S: Sometimes the view and the controler are together and it's more like a Model and ViewControler, when we cannot separate the View and the Controler.