2014-04-23 48 views
0

我有一個問題。我分配給JDialog的inputMap的鍵綁定Ctrl + Tab不起作用。爲什麼JDialog中沒有鍵綁定工作?

請複製粘貼此代碼並鍵入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

Ctrl-Tab是Windows的一個操作系統特性和一些Linux發行版......你在什麼操作系統上?它是否適用於JFrame? –

回答

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串也是其他組合。

相關問題