Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to a JList

I have an array of objects that contain the name of customers, like this: Customers[]

How I can add those elements to an existing JList automatically after I press a button? I have tried something like this:

for (int i=0;i<Customers.length;i++)
{
    jList1.add(Customers[i].getName());
}

But I always get a mistake. How I can solve that? I am working on NetBeans. The error that appears is "not suitable method found for add(String). By the way my method getName is returning the name of the customer in a String.

like image 806
Little Avatar asked Apr 25 '13 12:04

Little


People also ask

How do you add an element to a JList?

Now to add additional elements at any time during execution, use addElement() again: listModel. addElement(new item); and it will show up in the JList.

How do I add a list to my swing?

JList(E [ ] l) : creates an new list with the elements of the array. JList(ListModel d): creates a new list with the specified List Model. JList(Vector l) : creates a new list with the elements of the vector.

How do I make my JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example: JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.

How get values from JList?

We can display a value when an item is selected from a JList by implementing MouseListener interface or extending MouseAdapter class and call the getClickCount() method with single-click event (getClickCount() == 1) of MouseEvent class.


1 Answers

The add method you are using is the Container#add method, so certainly not what you need. You need to alter the ListModel, e.g.

DefaultListModel<String> model = new DefaultListModel<>();
JList<String> list = new JList<>( model );

for ( int i = 0; i < customers.length; i++ ){
  model.addElement( customers[i].getName() );
}

Edit:

I adjusted the code snippet to add the names directly to the model. This avoids the need for a custom renderer

like image 172
Robin Avatar answered Sep 21 '22 21:09

Robin