FocusTraversalPolicy



Has anyone written a decent one?

I had an app that worked fine in 1.3, in 1.4 the focussing is a disaster.
I have JDesktop panes, JIternalPanes and JTabbed panes containing JTables,
JComboBoxes, JTextFields etc.

Using ContainerOrderFocusPolicy I can't get initial focus to work, it's take
2 or 3 tabs sometimes to move from one component to the next etc. I guess
it's stepping out to parent panes and then back or something even though
I've set everything to focusable(false) except the items I want to land on.
I wrote a pretty basic policy but it's not handling compound components
properly (a JComboBox I've made AutoCompletable) and I haven't covered any
of the up/down cycle stuff or checked for no enabled components. Does anyone
have anything more complete? (I'm no swing expert)

Cheers, Richard.

from memory ...

import java.awt.*;
import java.util.*;

public class MyTraversalPolicy extends FocusTraversalPolicy {
private Map map;
private java.util.List components;
private int currentKey;

public MyTraversalPolicy(){
map = new IdentityHashMap();
currentKey = 0;
components = new ArrayList();
}

public void add(Component c){
map.put(c, new Integer(currentKey++));
components.add(c);
}

public Component getDefaultComponent(Container focusCycleRoot) {
return getFirstComponent(focusCycleRoot); }

public Component getFirstComponent(Container focusCycleRoot) {
Component c = components.get(0);
return c.isEnabled() ? c : getComponentAfter(focusCycleRoot, c);
}

public Component getLastComponent(Container focusCycleRoot) {
Component c = components.get(components.size() - 1);
return c.isEnabled() ? c : getComponentBefore(focusCycleRoot, c);
}

public Component getComponentAfter(Container focusCycleRoot, Component
aComponent) {
int key = ((Integer)map.get(aComponent)).intValue();
if(key == components.size() - 1){
return getFirstComponent(focusCycleRoot);
}
Component c = components.get(key + 1);
return c.isEnabled() ? c : getComponentAfter(focusCycleRoot, c);
}

public Component getComponentBefore(Container focusCycleRoot, Component
aComponent) {
int key = ((Integer)map.get(aComponent)).intValue();
if(key == 0){
return getLastComponent(focusCycleRoot);
}
Component c = components.get(key - 1);
return c.isEnabled() ? c : getComponentBefore(focusCycleRoot, c);
}
}



.



Relevant Pages

  • Fous Traversal Policy
    ... public class MyTraversalPolicy extends FocusTraversalPolicy { ... public Component getDefaultComponent(Container focusCycleRoot) { ...
    (comp.lang.java.programmer)
  • [Swing] How to implement tab order?
    ... Instead within the TabOrderFrame class I'd like to specify the order of the panels and within a panel class (e.g. TabOrderPanel1) I'd like to specify the order of its text fields. ... public Component getDefaultComponent(Container focusCycleRoot) { ... JTextField comp1; ...
    (comp.lang.java.gui)