Reputation: 37
I am unable to remove an item from JList
. The following code has been put on the JButton
.
DefaultListModel model = (DefaultListModel) list1.getModel();
int selectedIndex = list1.getSelectedIndex();
if (selectedIndex != -1)
{
model.remove(selectedIndex);
}
Upvotes: 0
Views: 487
Reputation: 11298
The following code should work
JButton removeButton = new JButton("Remove Selected Element");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int selectedIndex = list1.getSelectedIndex();
if (selectedIndex != -1) {
model.remove(selectedIndex);
} else {
System.out.println("Nothing selected");
}
}
});
Upvotes: 2