0

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);
     }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
VVV
  • 39
  • 1
  • 5

1 Answers1

2

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");
        }
    }
});
vels4j
  • 11,208
  • 5
  • 38
  • 63