Reputation: 11
I don't understand how to delete the line of JList which is pressed by delete-key. I know that it sounds like "write for me the code please" but.... it is) Because I don't know is it possible to determine the actual line and then make it answer to my actions.
I started to write something like that
list.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if(KeyEvent.getKeyText(e.getKeyCode()).equals("Delete")) {
// removing
}
}
});
but how to proceed I have no idea
Upvotes: 0
Views: 44
Reputation: 860
Assuming you are using a DefaultListModel
and assuming you want to delete all the selected items, the code you need is
list.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if(KeyEvent.getKeyText(e.getKeyCode()).equals("Delete")) {
// removing:
DefaultListModel lm = (DefaultListModel) list.getModel();
for(int i : list.getSelectedIndices()) {
lm.remove(i);
}
}
}
});
otherwise:
DefaultListModel
you have to extend the JList class or (better) create your own implementation of ListModel
and create your own remove method...Upvotes: 0