我正在为应用程序中的多个Panel设置新的Tab键顺序 . 我想创建一个新类,它允许我以与不推荐使用的setNextFocusableComponent方法相同的方式处理排序 . 我正在创建一个扩展DefaultTreversalPolicyClass的类,并重载getComponentBefore和getComponentAfter方法 . 在面板本身我希望实现就像创建一个新的自定义类(我称之为CustomizedTabOrderPolicy),然后添加我想要指定Tab键顺序的组件一样简单 . 我通过CustomizedTabOrderPolicy类上的便捷方法执行此操作,该类允许我将要为其指定Tab键顺序“链接”的组件添加到Hashtable,然后创建hastable的副本,其中键和值被切换 . 然后,我使用这些哈希表在两个组件之间 Build 前向和后向Tab键顺序“链接” .
以下是我的自定义类:
import java.awt.Component;
import java.awt.Container;
import java.awt.DefaultFocusTraversalPolicy;
import java.util.Hashtable;
public class CustomizedTabOrderPolicy extends DefaultFocusTraversalPolicy {
private Hashtable exceptionsMap = new Hashtable();
private Hashtable excpetionsMapReflection = new Hashtable();
private Component defaultComponent;
private Component firstComponent;
private Component lastComponent;
public CustomizedTabOrderPolicy() {
}
@Override
public Component getComponentAfter(Container container, Component component) {
java.awt.Toolkit.getDefaultToolkit().beep();
if (exceptionsMap.containsKey(component)) {
return exceptionsMap.get(component);
} else {
return super.getComponentAfter(container, component);
}
}
@Override
public Component getComponentBefore(Container container, Component component) {
if (exceptionsMap.containsValue(component)) {
return excpetionsMapReflection.get(component);
} else {
return super.getComponentBefore(container, component);
}
}
@Override
public Component getDefaultComponent(Container container) {
if (this.defaultComponent != null) {
return this.defaultComponent;
}
return super.getDefaultComponent(container);
}
@Override
public Component getFirstComponent(Container container) {
if (this.firstComponent != null) {
return this.firstComponent;
}
return super.getFirstComponent(container);
}
@Override
public Component getLastComponent(Container container) {
if (this.lastComponent != null) {
return this.lastComponent;
}
return super.getLastComponent(container);
}
public void addNewException(Component origin, Component destination) {
exceptionsMap.put(origin, destination);
excpetionsMapReflection.put(destination, origin);
}
public void setDefaultComponent(Component defaultComponent) {
this.defaultComponent = defaultComponent;
}
public void setLastComponent(Component lastComponent) {
this.lastComponent = lastComponent;
}
public void setFirstComponent(Component firstComponent) {
this.firstComponent = firstComponent;
}
}
为了实现这一点,我在我的JPanel上使用以下内容:
CustomizedTabOrderPolicy customPolicy = new CustomizedTabOrderPolicy();
customPolicy.addNewException(, );
customPolicy.addNewException(, );
customPolicy.addNewException(, );
this.setFocusTraversalPolicy(customPolicy);
我没有得到任何编译器或运行时错误,但似乎JPanel根本没有使用我的CustomTabOrderPolicy . 当我在getComponentBefore和getComponentAfter方法中插入断点时,它们永远不会被触发 . 我很擅长使用Focus Traversal政策,所以我想知道我在这里缺少什么......