Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the ListModel of a JList in Netbeans?

I have designed a Swing GUI with the help of Netbeans IDE and this GUI contains a JList.

Bydefault, it uses AbstractListModel to pass it as an argument in the JList contructor to create that JList.

I want to specify somewhere in the Netbeans to pass DefaultListModel as the model to be passed in that JList so that later I can retrieve it to make changes in the listModel.

How can I do that.

like image 493
Yatendra Avatar asked Jan 22 '10 14:01

Yatendra


People also ask

How do you add elements 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 you remove an element from a JList in Java?

To actually remove the item, we use the syntax . remove(int); where the integer is the index of the item you wish to remove. That is how we add and remove things from a JList, and this concludes our tutorial on the JList.

What method was used to identify the selected item in a JList?

Call getSelectedIndex to get the index of the selected item in the JList . Call getSelectedValue method to get the value of the selected item in the JList .

Which method of JList returns an array of all selected items?

getSelectedValuesList() returns a list of all the selected items.


2 Answers

You have two ways of doing this:

1) In your code manually call list.setModel() anywhere after initComponents() is called. 2) Do it through NetBeans - Right click the list, go to "Customize Code". The first code section is the list's constructor call. Change the dropdown from "Default Code" to "Custom Creation" and simply insert your ListModel in the constructor call. You can do this by setting it to new

javax.swing.JList(new DefaultListModel())

or by instantiating your listmodel before the call to initComponents() in the code and then doing

javax.swing.JList(defaultModel);
like image 110
Jason Nichols Avatar answered Sep 18 '22 20:09

Jason Nichols


I usually do this way in Netbeans
1. Select the JList
2. In model property, select Custom code and insert the listModel name (declared in 3rd step)
3. declare DefaultListModel listModel = new DefaultListModel(); in code view
4. change listModel declaration to accept a List or similar

like image 34
Tun Avatar answered Sep 17 '22 20:09

Tun