VVV
VVV

Reputation: 37

How to get item in a JList and remove it?

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

Answers (1)

vels4j
vels4j

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

Related Questions