2017-02-22 97 views
0

我有一個java swing JList,並希望能夠使用DOUBLE鍵移動到列表中的某一行。 看看我的下面列表。如果我按2個鍵焦點在列表中跳轉到行2002年,但我希望能夠按鍵22(二2:S)和焦點跳躍到2201java swing中的快捷方式JList

我的列表:

1001 
1002 
1003 
1101 
1102 
1103 
2002 
2003 
2004 
2201 
2202 

任何人都知道這對JList來說甚至是可能的嗎?

+1

請閱讀並創建和MCVE! http://stackoverflow.com/help/how-to-ask&http://stackoverflow.com/help/mcve。 – StackFlowed

回答

4

這是由LAF控制的。

默認邏輯規定,當您輸入相同的鍵時,列表將循環到列表中的下一個項目。

因此,您不能直接進入「22 ...」號碼,因爲它會通過以「2 ...」開頭的每個項目。

但是,如果你有一個像「2301」和「2311」這樣的號碼,你可以直接進入這些號碼。

這裏是在BasicListUI類中找到的邏輯:

public void keyTyped(KeyEvent e) { 
    JList src = (JList)e.getSource(); 
    ListModel model = src.getModel(); 

    if (model.getSize() == 0 || e.isAltDown() || 
      BasicGraphicsUtils.isMenuShortcutKeyDown(e) || 
      isNavigationKey(e)) { 
     // Nothing to select 
     return; 
    } 
    boolean startingFromSelection = true; 

    char c = e.getKeyChar(); 

    long time = e.getWhen(); 
    int startIndex = adjustIndex(src.getLeadSelectionIndex(), list); 
    if (time - lastTime < timeFactor) { 
     typedString += c; 
     if((prefix.length() == 1) && (c == prefix.charAt(0))) { 
      // Subsequent same key presses move the keyboard focus to the next 
      // object that starts with the same letter. 
      startIndex++; 
     } else { 
      prefix = typedString; 
     } 
    } else { 
     startIndex++; 
     typedString = "" + c; 
     prefix = typedString; 
    } 
    lastTime = time; 

    if (startIndex < 0 || startIndex >= model.getSize()) { 
     startingFromSelection = false; 
     startIndex = 0; 
    } 
    int index = src.getNextMatch(prefix, startIndex, 
           Position.Bias.Forward); 
    if (index >= 0) { 
     src.setSelectedIndex(index); 
     src.ensureIndexIsVisible(index); 
    } else if (startingFromSelection) { // wrap 
     index = src.getNextMatch(prefix, 0, 
           Position.Bias.Forward); 
     if (index >= 0) { 
      src.setSelectedIndex(index); 
      src.ensureIndexIsVisible(index); 
     } 
    } 
} 

注意這裏的「前綴」變量設置註釋。

所以,如果你想改變行爲,你需要創建一個自定義的用戶界面並覆蓋該方法。不知道該方法是否使用私有變量或方法。

或者另一種選擇是從JList中刪除默認的KeyListener。然後你可以實現你自己的KeyListener,並直接調用getNextMatch(...)用你自定義的前綴。

+0

謝謝。 我有我的JList的這個聲明: private JList officeList = new JList(); 然後,在init()方法中,我刪除默認的KeyListener,就像您所建議的那樣: officeList.removeKeyListener(officeList.getKeyListeners()[0]); 但後來我卡住了。我如何實現我自己的KeyListener? – chichi

+0

@chichi,我給你當前的代碼。您需要修改它並將其添加到您自己的偵聽器中。如果您不知道如何編寫KeyListener,請閱讀[如何編寫KeyListener](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html)上的Swing教程部分,作爲一個基本的例子讓你開始。 – camickr

+0

謝謝,我很感激! – chichi