简体   繁体   中英

How to add element to existing JList

Part of my code

 ArrayList<Item> i = g.getItems(); 
 Vector itemsVector = new Vector(i); 
 JList items = new JList(iemsVector); 

Later in the code I create new object which I want to add to JList. How can I do that?

Populate the JList with a DefaultListModel, not a vector, and have the model visible in the class. Then simply call addElement on the list model to add items to it.

Well you can not use directly that Array but use this this will might help you for the same.

 DefaultListModel demoList = new DefaultListModel();
 demoList.addElement("addElements");
 JList listd = new JList(demoList);

That way you can add elemets into the LIST.

You may add it ( new object ) to the itemsVector (Vector). After adding an item into Vector object invoke the items.setListData(itemsVector); method.

尝试使用add方法,如下所示: items.add(newItem)

I'm using code similar to the following:

public void addRow(MyObject object)
{
    Object[] objects = new Object[]{object.getSomeInt(), object.getSomeString()};
    DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
    tableModel.addRow(objects);
}

Try this:

DefaultListModel model = new DefaultListModel();
JList list = new JList(model);

// Initialize the list with items
String[] items = { "A", "B", "C", "D" };
for (int i = 0; i < items.length; i++) {
  model.add(i, items[i]);

}

source : java2s

private javax.swing.JList<String> list1;
list1.setFont(new java.awt.Font("Tahoma", 0, 24));

DefaultListModel listModel1 = new DefaultListModel();

String st="Working hard";
listModel1.addElement(r);

list1.setModel(listModel1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM