本文介紹了Windows 和 Mac 在密鑰檢測(cè)方面的 Java 差異的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問題描述
我有一個(gè)帶有鍵偵聽器的 JList,以便用戶可以輕松地從列表中刪除項(xiàng)目.在 Windows 上,它工作正常.您按下刪除鍵,該項(xiàng)目被刪除.在 mac 上,程序不響應(yīng)刪除鍵.我正在使用 KeyEvent.VK_DELETE
并且我認(rèn)為這是檢測(cè)特殊鍵的平臺(tái)中立方式.我應(yīng)該以其他方式檢測(cè) 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();
}
});
}
}
這篇關(guān)于Windows 和 Mac 在密鑰檢測(cè)方面的 Java 差異的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!