我有一个java swing JList,并希望能够使用DOUBLE键移动到列表中的某一行。 看看我的下面列表。如果我按2个键焦点在列表中跳转到行2002年,但我希望能够按键22(二2:S)和焦点跳跃到2201java swing中的快捷方式JList
我的列表:
1001
1002
1003
1101
1102
1103
2002
2003
2004
2201
2202
任何人都知道这对JList来说甚至是可能的吗?
我有一个java swing JList,并希望能够使用DOUBLE键移动到列表中的某一行。 看看我的下面列表。如果我按2个键焦点在列表中跳转到行2002年,但我希望能够按键22(二2:S)和焦点跳跃到2201java swing中的快捷方式JList
我的列表:
1001
1002
1003
1101
1102
1103
2002
2003
2004
2201
2202
任何人都知道这对JList来说甚至是可能的吗?
这是由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(...)
用你自定义的前缀。
谢谢。 我有我的JList的这个声明: private JList officeList = new JList(); 然后,在init()方法中,我删除默认的KeyListener,就像您所建议的那样: officeList.removeKeyListener(officeList.getKeyListeners()[0]); 但后来我卡住了。我如何实现我自己的KeyListener? – chichi
@chichi,我给你当前的代码。您需要修改它并将其添加到您自己的侦听器中。如果您不知道如何编写KeyListener,请阅读[如何编写KeyListener](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html)上的Swing教程部分,作为一个基本的例子让你开始。 – camickr
谢谢,我很感激! – chichi
请阅读并创建和MCVE! http://stackoverflow.com/help/how-to-ask&http://stackoverflow.com/help/mcve。 – StackFlowed