dpm
dpm

Reputation: 245

Use JList in JComboBox

I have a JList which is of DefaultListModel. I am not trying to create a JComboBox which should display as its the elements, the elements in the JList.

What is the best way to achieve this ? Thank you.

My code:

DefaultListModel<String> listModelTopic = new DefaultListModel<>();
//create the list
listTopic = new JList<>(listModelTopic);
//create comboBox
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(topicList.getModel());

Error: The constructor DefaultComboBoxModel(ListModel) is undefined

Upvotes: 0

Views: 1389

Answers (1)

Ravi Ranjan
Ravi Ranjan

Reputation: 740

Use copyInto on DefaultListModel to copy all the values to an array.

 String[] lstArray = new String[listModelTopic.getSize];
 listModelTopic.copyInto(lstArray );

Then create DefaultComboBoxModel using this array.

DefaultComboBoxModel comboModel = new DefaultComboBoxModel(lstArray );
 JComboBox comboBox = new JComboBox();
 comboBox.setModel(comboModel );

Hope this helps!

Upvotes: 2

Related Questions