Ivan Gorbunov
Ivan Gorbunov

Reputation: 11

Action at pressing the key on certain line in jlist

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

Answers (1)

Bruno Zamengo
Bruno Zamengo

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:

  • if you don't want to remove all the selected items I didn't understand your question :(
  • if you're not using a DefaultListModel you have to extend the JList class or (better) create your own implementation of ListModel and create your own remove method...

Upvotes: 0

Related Questions