我有一个带有键监听器的JList,使用户可以轻松地从列表中删除一个项目.在
Windows上,它工作正常.您点击删除键,该项目被删除.在mac上,程序不响应删除键.我正在使用KeyEvent.VK_DELETE,我认为这是一种检测特殊键的平台中立方式.有没有不同的方法我应该在Mac上检测按键?
studentJList.setModel(studentListModel); // a custom model I wrote studentJList.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_DELETE) { studentListModel.remove(studentJList.getSelectedIndex()); studentJList.revalidate(); } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } });
例如
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ListDemo extends JPanel { private static final long serialVersionUID = 1L; private JFrame frame = new JFrame("ListDemo"); private JList list; private DefaultListModel listModel; public ListDemo() { super(new BorderLayout()); listModel = new DefaultListModel(); listModel.addElement("Jane Doe"); listModel.addElement("John Smith"); listModel.addElement("Kathy Green"); list = new JList(listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.setVisibleRowCount(5); JScrollPane listScrollPane = new JScrollPane(list); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); frame.add(listScrollPane,BorderLayout.CENTER); frame.pack(); frame.setVisible(true); setKeyBindings(); } private void setKeyBindings() { list.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .put(KeyStroke.getKeyStroke("DELETE"),"clickDelete"); list.getActionMap().put("clickDelete",new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { int index = list.getSelectedIndex(); if (index > -1) { listModel.remove(index); } } }); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { ListDemo listDemo = new ListDemo(); } }); } }