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.
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
No to add element Dynamically you may use given code
DefaultListModel model = (DefaultListModel)jList1.getModel();
model.addElement("Element " + count++);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With