java refreshing an array into jList

醉酒当歌 提交于 2019-12-01 03:27:39

问题


OK so I have a JList and the content is provided with an array. I know how to add elements to an array but I want to know how to refresh a JList... or is it even possible? I tried Google. :\

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class bs extends JApplet implements MouseListener {

public static String newline;
public static JList list;

    public void init() {



             String[] data = {"one", "two", "three", "four"};
              list = new JList(data);



        this.getContentPane().add(list);

        list.addMouseListener(this);

        String newline = "\n";

        list.setVisible(true);

    }

    public void refresh(){
        Address found;
        this.listModel.clear();

        int numItems = this.getAddressBookSize();
        String[] a = new String[numItems];
        for (int i=0;i<numItems;i++){
            found = (Address)Addresses.get(i);
            a[i] = found.getName();
        }
        /* attempt to sort the array */
        Arrays.sort(a, String.CASE_INSENSITIVE_ORDER);
        for (int i=0;i<numItems;i++) {
            this.listModel.addElement(a[i]);
        }
    }



    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) {
        Object index = list.getSelectedValue();
       System.out.println("You clicked on: " + index);
    }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }




    public void paint(Graphics g) {

    }
}

Any ideas?

Thank you.


回答1:


One good approach is to create a ListModel to manage the data for you and handle updates.

Something like:

DefaultListModel listModel=new DefaultListModel();
for (int i=0; i<data.length; i++) {
  listModel.addElement(data[i]);
}
list=new JList(listModel);

Then you can simply make changes via the list model e.g.

listModel.addElement("New item");
listModel.removeElementAt(1); // remove the element at position 1



回答2:


You just need to supply your own ListModel:

 class MyModel extends AbstractListModel {
     private String[] items;

    public MyModel(String[] items) {
        this.items = items;
    }

    @Override
    public Object getElementAt(int index) {
        return items[index];
    }

    @Override
    public int getSize() {
        return items.length;
    }

    public void update() {
        this.fireContentsChanged(this, 0, items.length - 1);
    }
}

After sorting items, just call update.



来源:https://stackoverflow.com/questions/3268383/java-refreshing-an-array-into-jlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!