Java difference in key detection between Windows and Mac(Windows 和 Mac 在密钥检测方面的 Java 差异)
问题描述
我有一个带有键侦听器的 JList,以便用户可以轻松地从列表中删除项目.在 Windows 上,它工作正常.您按下删除键,该项目被删除.在 mac 上,程序不响应删除键.我正在使用 KeyEvent.VK_DELETE
并且我认为这是检测特殊键的平台中立方式.我应该以其他方式检测 Mac 上的按键吗?
I have a JList with a key listener to make it easy for the user to delete an item from the list. On windows, it works fine. You hit the delete key and the item is removed. On mac, the program does not respond to the delete key. I am using KeyEvent.VK_DELETE
and I thought this was a platform neutral way of detecting special keys. Is there a different way I should be detecting the key press on the 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();
}
});
}
}
这篇关于Windows 和 Mac 在密钥检测方面的 Java 差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Windows 和 Mac 在密钥检测方面的 Java 差异


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01