Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Jlist dynamically

Tags:

java

swing

jlist

I am new to swing. I have dragged and drop the Jlist component in panel. It generated code that is

jList1 = new javax.swing.JList();
jList1.setModel(new javax.swing.AbstractListModel() {
    String[] strings = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};

    public int getSize() {
        return strings.length;
    }

    public Object getElementAt(int i) {
        return strings[i];
    }
});
jScrollPane1.setViewportView(jList1);

After executing the code it gives the element which are included by default. I want to insert the element dynamically through code, how can I do that. I tried using

DefaultListModel model = new DefaultListModel();
jList1 = new JList(model);
for (int i = 0; i < 15; i++) {
    model.addElement("Element " + i);
}
jList1.setModel(model);

But the list does not get updated. How can I update it dynamically.

like image 410
Nikhil Kadam Avatar asked Mar 18 '23 04:03

Nikhil Kadam


2 Answers

Start by getting rid of jList1 = new JList(model); after you create new DefaultListModel

DefaultListModel model = new DefaultListModel();
//jList1 = new JList(model);
for (int i = 0; i < 15; i++) {
    model.addElement("Element " + i);
}
jList1.setModel(model);

You're creating a new instance of JList which has nothing to do with the instance that is on the screen

like image 99
MadProgrammer Avatar answered Mar 19 '23 18:03

MadProgrammer


No to add element Dynamically you may use given code

  DefaultListModel model = (DefaultListModel)jList1.getModel();
  model.addElement("Element " + count++);
like image 40
Kunal Kishor Avatar answered Mar 19 '23 19:03

Kunal Kishor