How To Move Selected JList Item Up N Down In Java NetBeans
In this Java Tutorial we will see How To Make Two Buttons To Move Selected List Item Up Or Down On Click In Java Using NetBeans .
Project Source Code:
// populate jlist using string array and for loop
DefaultListModel model = new DefaultListModel();
jList1.setModel(model);
String[] JlistItems = {"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A11"};
for(int i = 0; i < JlistItems.length; i++)
{
model.add(i, JlistItems[i]);
}
// button to move selected jlist item up
private void jButton_UPActionPerformed(java.awt.event.ActionEvent evt) {
String selectedItem = jList1.getSelectedValue();//get item value
int itemIndex = jList1.getSelectedIndex();// get item index
DefaultListModel model = (DefaultListModel)jList1.getModel();// get list model
if(itemIndex > 0){
model.remove(itemIndex);// remove selected item from the list
model.add(itemIndex - 1, selectedItem);// add the item to a new position in the list
jList1.setSelectedIndex(itemIndex - 1);// set selection to the new item
}
}
// button to move selected jlist item down
private void jButton_DownActionPerformed(java.awt.event.ActionEvent evt) {
String selectedItem = jList1.getSelectedValue();
int itemIndex = jList1.getSelectedIndex();
DefaultListModel model = (DefaultListModel)jList1.getModel();
if( itemIndex < model.getSize() -1 ){
model.remove(itemIndex);
model.add(itemIndex + 1, selectedItem);
jList1.setSelectedIndex(itemIndex + 1);
}
}
// OUTPUT :