简体   繁体   中英

How to remove an item from a jlist

I have a Jlist which is populated with books, however, what I would like to do is that once one of the books is selected I press a button called return book that should make the book removed from the list.

I have a members class that has a return book method as follows

public void returnBook(Book aBook)
{
    currentLoans.remove(aBook);
    aBook.setBorrower(null);
}

On my main application I have the following code under the return book button

private void theButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
  //!!!Return book
  DefaultListModel model = (DefaultListModel) BooksOnLoan.getModel(); 
  Book selectedBook;
  selectedBook = (Book)BooksOnLoan.getModel();
  model.remove(selectedBook); 
}  

As you can see I am quite not sure how to remove the item from the list once the button is clicked.

The method "remove" from DefaultListModel works with index, so you first need to get the index of the element that you want to remove and provide that to the remove method. You can use methods on your list for that: getSelectedIndex method for single selection mode (you will get -1 if there is no selection), or getSelectedIndices for multiselect.

If in any case your list stays the same after this, you need to refresh GUI after the model has been changed. Although I am almost certain that you need not do that, but keep this principle in mind for future.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM