JList list = new JList(); list.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { // do something when Enter key is pressed } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} });
public class MyKeyListener implements KeyListener { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_DELETE) { // do something when Delete key is pressed } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} } JList list = new JList(); list.addKeyListener(new MyKeyListener());In this example, we create a new class called MyKeyListener that implements the KeyListener interface. We then override the keyPressed method and use an if statement to detect if the Delete key has been pressed. We then create a new JList and add an instance of MyKeyListener to it using the addKeyListener method. The javax.swing package library contains the JList, KeyListener, and KeyEvent classes used in these examples.