I am trying to be able to select multiple items at a time and add them to my table but when I attempt at doing so, I am getting an array out of bounds exception. I think this is due to my listToArr method because it allows me to select one item at a time just fine without any errors. I made the listToArr method because insertRow() in a table model requires an int for the first parameter and an Object[] or Vector for the second parameter.
I also would love to know how to make the highlighted selected items become unhighlighted after my select button is pressed.
private void populateTable(JList<String> items){
DefaultTableModel t = (DefaultTableModel) selectedItemsTable.getModel();
t.insertRow(t.getRowCount()-1, listToArr(items));
selectedItemsTable.setModel(t);
}
private Object[] listToArr(JList<String> l){
Object[] o = new Object[l.getComponentCount()];
int i=0;
for(Object value : l.getSelectedValuesList()){
o[i] = (Object) value;
i++;
}
return o;
}
private void SelectNeedActionPerformed(java.awt.event.ActionEvent evt) {
populateTable(needsList);
}
and an Object[] or Vector for the second parameter.
The second parameter is an Array containing data for each column in the row. When you only select a single item this means you only have a single column in the table.
If you select 3 items then it means you will have 3 columns in the table.
I suspect you created your table with only a single column. This means you need to iterate through the List of selected items and add an Array containing each item separately , which will give you 3 rows with only a single column.
because insertRow() in a table model requires an int for the first parameter
You can just use the addRow(...)
method of the DefaultTableModel
. It will add the row to the end of the table model.
//selectedItemsTable.setModel(t); // get rid of this
There is no need to reset the model. The point of using a model is that it will notify the view (JTable) when the data is changed.
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.