抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

设置在Swing界面中使用Tab键或回车键在多个输入框中进行导航

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//使窗口居中
this.setLocationRelativeTo(null);

btnWeightUnit.setEnabled(false);
btnDimUnit.setEnabled(false);

//设置焦点遍历键
AWTKeyStroke keyEnter = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0);
AWTKeyStroke keyTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0);

Set<AWTKeyStroke> set = new HashSet<>(1);
set.add(keyEnter);
set.add(keyTab);
this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);

//设置焦点遍历策略
List<Component> comList = new ArrayList<>();
comList.add(txtLabel);
comList.add(txtWeight);
comList.add(txtDimL);
comList.add(txtDimW);
comList.add(txtDimH);

FocusTraversalPolicy policy = new FocusTraversalPolicy() {
@Override
public Component getFirstComponent(Container focusCycleRoot) {
return (Component) comList.get(0);
}

@Override
public Component getLastComponent(Container focusCycleRoot) {
return (Component) comList.get(comList.size() - 1);
}

@Override
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
int index = comList.indexOf(aComponent);

return (Component) comList.get((index + 1) % comList.size());
}

@Override
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
int index = comList.indexOf(aComponent);
return (Component) comList.get((index - 1 + comList.size()) % comList.size());
}

@Override
public Component getDefaultComponent(Container focusCycleRoot) {
return (Component) comList.get(0);
}
};
this.setFocusTraversalPolicy(policy);

评论