为什么键绑定在JDialog中不起作用?

时间:2014-04-23 11:48:23

标签: java swing key-bindings

我有问题。我分配给JDialog的inputMap的键绑定Ctrl + Tab不起作用。

请复制粘贴此代码并键入Ctrl + TAB以解决此问题。它应该打印到控制台,但它没有。

public class PopupFilesAccessor extends JDialog {

    private static PopupFilesAccessor filesAccessor = new PopupFilesAccessor();

    private DefaultListModel<String> filesModel;
    private JList<String> files;

    public PopupFilesAccessor() {
        super(null, "Demo", ModalityType.APPLICATION_MODAL);
        super.setUndecorated(true);
        super.setAlwaysOnTop(true);
        super.setLocationRelativeTo(null);

        filesModel = new DefaultListModel<>();

        files = new JList<>(filesModel);
        files.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        files.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        files.setVisibleRowCount(0);
        // files.setCellRenderer(new FilesListCellRenderer());

        InputMap inputMap = super.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        ActionMap actionMap = super.getRootPane().getActionMap();

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK), "selectDown");
        actionMap.put("selectDown", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectNextItem();
            }

            private void selectNextItem() {
                System.out.println("Good! selectNextItem method is running");
            }
        });

        JScrollPane scrollBar = new JScrollPane(files);
        super.getContentPane().add(scrollBar);
    }

    private void prepareToShow() {
        List<String> openedFiles = Arrays.asList("item1", "item2", "item3", "item4", "item5", "item6", "item7");
        filesModel.clear();
        for (int i = 0; i < openedFiles.size(); i++) {
            String userFile = openedFiles.get(i);
            filesModel.addElement(userFile);
        }
        files.setSelectedIndex(1);
        super.pack();
    }

    public static void popup() {
        filesAccessor.prepareToShow();
        filesAccessor.setVisible(true);
        filesAccessor.requestFocusInWindow();
    }

    public static void main(String[] args) {
        PopupFilesAccessor.popup();
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

这不是一个好方法,但如果它适合你,你仍然可以使用ActionEvent#paramString()来尝试。

long eventMask = AWTEvent.KEY_EVENT_MASK;

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
    public void eventDispatched(AWTEvent e) {
        String paramString = e.paramString();
        // System.out.println(paramString);
        if (paramString.contains("KEY_RELEASED,keyCode=9,keyText=Tab,keyChar=Tab,modifiers=Ctrl,extModifiers=Ctrl")) {
            System.out.println("Ctrl+Tab keys are released");
        }
    }
}, eventMask);

注意:您也可以检查param字符串的其他组合。