以克娄巴特拉的回答为基础,帮助处于类似情况的其他人;我有一堆我不想关注的自定义挥杆组件(有时仅在它们不可编辑时)。我最终得到了这个:
/**
* A custom focus traversal policy to make focus traversal inside a container to ignore some swing components.<br /><br />
*
* <b>Ignored components:</b><br />
* - <code>CustomComponent1</code> components<br />
* - <code>CustomComponent2</code> components that are not editable<br /><br />
*
* <b>Usage:</b><br /><br />
* <code>Container.setFocusTraversalPolicy(new CustomFocusTraversalPolicy());</code>
*/
public class CustomFocusTraversalPolicy extends LayoutFocusTraversalPolicy {
private static final long serialVersionUID = 1L;
protected boolean accept(Component c) {
if(c instanceof CustomComponent1) {
return false;
}
if(c instanceof CustomComponent2) {
CustomComponent2 t = (CustomComponent2) c;
if(!t.isEditable()) {
return false;
}
}
return super.accept(c);
}
}
请注意,需要为每个设置策略Container
(我为每个Window
创建的都设置了):
Window window = new JFrame(); // Or JDialog; both subclasses of Container and Window
window.setFocusTraversalPolicy(new CustomFocusTraversalPolicy());