Detect when the User presses the Delete Key

(Using Java 15.0.1) I’m writing a program for school that should execute some code when the user presses the “DEL” key over a JList. I tried out some code and this is how far I got:

rechnungen.addKeyListener(new KeyListener() {
            public void keyTyped(KeyEvent keyEvent) {
                char key = keyEvent.getKeyChar();

When I now press keys over that JList I get the output in the command-line. And as I want to detect the “DEL” key I tried that and it gives me this:

Pasting that in Intelliq gives me: DEL in some wired spaces this:
this That is a string so if I want to do a switch case thing to do execute code on specific keys, it tells me that I can compare a String with a Character.

How should I do that?


Here is a sample app that displays a JList and when you press the Delete key on the keyboard, the selected item in the JList is removed. It uses key bindings.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.DefaultListModel;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;

public class DeletLst implements Runnable {
    private JFrame  frame;
    private JList<String>  list;

    public void run() {

    private JScrollPane createList() {
        String[] items = new String[]{"Yashin",
                                      "di Stefano",
        DefaultListModel<String> model = new DefaultListModel<>();
        list = new JList<>(model);
        InputMap inputMap = list.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "deleteListSelection");
        ActionMap actionMap = list.getActionMap();
        actionMap.put("deleteListSelection", new ListDeleteAction());
        JScrollPane scrollPane = new JScrollPane(list);
        return scrollPane;

    private void showGui() {
        frame = new JFrame();
        frame.add(createList(), BorderLayout.CENTER);

    private class ListDeleteAction extends AbstractAction {
        public void actionPerformed(ActionEvent event) {
            int ndx = list.getSelectedIndex();
            if (ndx >= 0) {
                DefaultListModel<String> model = (DefaultListModel<String>) list.getModel();

    public static void main(String[] args) {
        EventQueue.invokeLater(new DeletLst());

Source: stackoverflow