java refreshing an array into jList
Asked Answered
V

2

5

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.

Valenta answered 16/7, 2010 at 19:52 Comment(0)
J
8

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
Jess answered 16/7, 2010 at 20:7 Comment(0)
W
6

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.

Worth answered 16/7, 2010 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.