简体   繁体   中英

Purpose of Model / MVC at Java Swing

I have a little problem. I dont understand the purpose of ListModel and/or ListSelectionModel. I think it is important vor the MVC Pattern / UI Delegate Principle in Java Swing.

For example: I have a simple JList and want to get a selected values. So i just can add a ListSelectionListener with a valueChanged Methode.

But what can i do now with the (default) Model or with the (default) SelectionModel? Or is it possible that the model acts behind the scenes? I think you only get the selected data through the model and change the values of the data with this model. So you need a model but you dont really implement a custom model?

Here is my code:

String[] shoppingCart = {"Pen", "Paper", "Smartphone", "Cheese"};

    JList list = new JList(shoppingCart);

    c.add(list, BorderLayout.CENTER);

    ListSelectionModel lsm = list.getSelectionModel();

    ListModel lm = list.getModel();

    System.out.println("lm: " + lm);

    System.out.println("lsm: " + lsm);

    list.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        //System.out.println(list.getSelectionModel().getValueIsAdjusting());
        System.out.println("value changed " + list.getSelectedValue());

    }
});

So getSelectionModel gives me my selected values. But maybe it is a method which will call from a model but behind the scene?

The Default(ListModel) is for add your Model data. When the data gets added to model it automatically gets the Jlist refreshed. The Selection Model is to keep track of the selection which are made on the list.

Now the ListSelectionListener. This you can implement when you want some notification of the selection event. if you dont need notification you dont have to used.

Suppose i have a Jlist which have a model. And this model corresponds to a form data. So if you want to design a UI where on click of the list you want to load the model data to the form, you can add ListSelectionListener.

list.getSelectedValue();

would give you the selected value (if list has some selection) irrespective of the Listener.

It is supposed that MVC makes the code easy to read and migrate, even it helps with scallability. So If you do a program using MVC in a form you will be able to migrate the code easily when you'll want to make a future web version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM