2017-02-22 1 views
0

나는 자바 스윙 JList를 가지고 있으며, 이중 키를 사용하여 목록의 특정 행으로 이동할 수 있기를 원한다. 아래 목록을 참조하십시오. 리스트가 2002 라인으로 점프에 내가 키 2 개 초점을 누르면하지만 키를 눌러 할 수있게하려면 (22) (두 2 : S) :자바 스윙의 단축키 JList

1001 
1002 
1003 
1101 
1102 
1103 
2002 
2003 
2004 
2201 
2202 

초점은 2201

에 내 목록을 점프 이것이 JList에서도 가능한지 누구나 알고 있습니까?

+1

MCVE를 읽고 작성하십시오! http://stackoverflow.com/help/how-to-ask & http://stackoverflow.com/help/mcve. – StackFlowed

답변

4

이것은 LAF에서 제어합니다.

동일한 논리 키를 입력하면 목록의 다음 항목으로 순환됩니다.

"22 ..."숫자로 바로 갈 수 없으므로 "2 ..."로 시작하는 각 항목을 통과하게됩니다.

그러나 "2301"및 "2311"과 같은 번호가 있으면 해당 번호로 직접 이동할 수 있습니다.

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); 
     } 
    } 
} 

참고 "접두사"변수가 설정 주석 : 여기

는 BasicListUI에 클래스에있는 논리이다.

동작을 변경하려면 사용자 지정 UI를 만들고 메서드를 재정의해야합니다. 메서드가 private 변수 나 메서드를 사용하는지 여부를 모릅니다.

또 다른 선택은 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