Java Swing: List Models and Collections
Asked Answered
O

3

5

I am currently writing a program which is having a lot of code duplication between the GUI aspect and the data storage aspect, and I was wondering if my proposed solution follows acceptable design principles.

Basically, I have some Data objects, which have a List holding some more information. Then the GUI displays the object, and a JList which displays all the information in the Data object's List. In the GUI, users can add or remove information to the object's list, and this is visually reflected in the JList.

However, this results in me having to maintain the GUI JList and the object List separately:

private void addInformation(String s) {
    this.listmodel.addElement(s);
    this.dataObject.getList().add(s);
}

(Obviously that is a very simple example but you get the idea). It also means that I'm using up twice as much memory holding both lists. Would it be acceptable for me to create a class which implemented both the ListModel and the List interfaces and then only need to update the single combined list/listmodel? I'm still studying at uni and I want to make this project the best I possibly can in terms of maintainability by others and adherence to best practices.

Overrule answered 15/7, 2011 at 1:7 Comment(1)
I'm not sure, I understand you or not. Maybe this helps youSarcous
F
3

Your GUI should not hold information about the state of the data model. It would be better to separate it up into a Model-View-Controller (MVC) design. Where the controller is responsible for object creation and updating the model and view accordingly. Your actual view should just be responsible for screen display by passing arguments to it to display. This way the view and model don't need to know anything about each other and there will only be one data model.

If your having to keep both lists consistent then something is wrong with your design and will probably introduce more bugs into the code.

See here for MVC details.

Freeway answered 15/7, 2011 at 1:15 Comment(0)
Y
2

Java Swing use a separable model architecture to minimize coupling between the model (e.g. ListModel, Table Model) and the corresponding view (JList, JTable). You don't have to use more memory.

Yezd answered 15/7, 2011 at 1:20 Comment(0)
S
2

I'd suggest you use an implementation of the ListModel interface (such as DefaultListModel) to hold your data. Then bind it to your JList. If the default renderer doesn't suit, write your own customized ListCellRenderer and apply it to the JList object.

Spock answered 15/7, 2011 at 1:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.