(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() { @Override public void keyTyped(KeyEvent keyEvent) { char key = keyEvent.getKeyChar(); System.out.println(key); }
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:
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?
Advertisement
Answer
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; @Override public void run() { showGui(); } private JScrollPane createList() { String[] items = new String[]{"Yashin", "Thuram", "Maldini", "Baresi", "Moore", "Beckenbauer", "di Stefano", "Messi", "Pele", "Maradona", "Cruyff"}; DefaultListModel<String> model = new DefaultListModel<>(); model.addAll(Arrays.asList(items)); list = new JList<>(model); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(createList(), BorderLayout.CENTER); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } private class ListDeleteAction extends AbstractAction { @Override public void actionPerformed(ActionEvent event) { int ndx = list.getSelectedIndex(); if (ndx >= 0) { DefaultListModel<String> model = (DefaultListModel<String>) list.getModel(); model.remove(ndx); } } } public static void main(String[] args) { EventQueue.invokeLater(new DeletLst()); } }