Java JList model

前端 未结 2 1529
无人共我
无人共我 2021-01-03 06:39

How can I make a list model from a JList in order to be able to insert an item into it. I want to use this method: addElement(java.lang.Object item)

相关标签:
2条回答
  • 2021-01-03 07:15

    Just an alternative method, if someone requires to use a custom ListModel. Inside the class that implements the list model interface, it would be necessary to create a structure to actually hold the elements like a LinkedList, like this:

    public class MyListModel implements ListModel{
        
        private LinkedList data;
        private LinkedList<ListDataListener> listeners;
    
        public MyListModel() {
            data = new LinkedList();
            listeners = new LinkedList();
        }
        
        public void addElement(Object element){
            data.add(element);
        }
        
        @Override
        public int getSize() {
            return data.size();
        }
    
        @Override
        public Object getElementAt(int index) {
            return data.get(index);
        }
    
        @Override
        public void addListDataListener(ListDataListener l) {
            listeners.add(l);
        }
    
        @Override
        public void removeListDataListener(ListDataListener l) {
            listeners.remove(l);
        }
        
    }
    

    You can also create access methods to do anything related to the LinkedList, like removeElement(Object element), or just make the data LinkedList public, or use different data structures if necessary. Of course, for a simple implementation it will always be easier to use the models provided with Java.

    0 讨论(0)
  • 2021-01-03 07:18

    Java provides implementations of ListModel already, like DefaultListModel, that you can instantiate and use

    For example:

    final DefaultListModel model = new DefaultListModel();
    model.addElement("one");
    model.addElement("two");
    model.addElement("three");
    
    final JList list = new JList(model);
    
    0 讨论(0)
提交回复
热议问题