我正在为一个应用程序中的多个面板设置新的选项卡顺序。我想创建一个新类,它允许我以与不推荐使用的 setNextFocusableComponent 方法相同的方式处理排序。我正在创建一个扩展 DefaultTreversalPolicyClass 并重载 getComponentBefore 和 getComponentAfter 方法的类。在面板本身上,我希望实现与创建一个新的自定义类(我将其称为 CustomizedTabOrderPolicy)一样简单,然后添加我要为其指定 Tab 键顺序的组件。我通过 CustomizedTabOrderPolicy 类上的一种便捷方法来执行此操作,该方法允许我将要为其指定 Tab 键顺序“链接”的组件添加到 Hashtable,然后创建键和值在其中切换的 hastable 的副本。
以下是我的自定义类:
import java.awt.Component;
import java.awt.Container;
import java.awt.DefaultFocusTraversalPolicy;
import java.util.Hashtable;
public class CustomizedTabOrderPolicy extends DefaultFocusTraversalPolicy {
private Hashtable<Component, Component> exceptionsMap = new Hashtable<Component, Component>();
private Hashtable<Component, Component> excpetionsMapReflection = new Hashtable<Component, Component>();
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(<component1>, <component2>);
customPolicy.addNewException(<component3>, <component4>);
customPolicy.addNewException(<component5>, <component6>);
this.setFocusTraversalPolicy(customPolicy);
我没有收到任何编译器或运行时错误,但 JPanel 似乎根本没有使用我的 CustomTabOrderPolicy。当我在 getComponentBefore 和 getComponentAfter 方法中插入断点时,它们永远不会被触发。我对使用焦点遍历策略非常陌生,所以我想知道我在这里缺少什么......