How to add element to existing JList

此生再无相见时 提交于 2019-12-10 02:58:22

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


Try with the add method, like this: items.add(newItem).




回答5:


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);
}



回答6:


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




回答7:


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);


来源:https://stackoverflow.com/questions/8176965/how-to-add-element-to-existing-jlist

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