View Javadoc

1   package com.swtdesigner;
2   
3   import java.awt.Component;
4   import java.awt.Container;
5   import java.awt.FocusTraversalPolicy;
6   
7   /**
8    * Cyclic focus traversal policy based on array of components.
9    * 
10   * This class may be freely distributed as part of any application or plugin.
11   * <p>
12   * 
13   * @author scheglov_ke
14   */
15  public class FocusTraversalOnArray extends FocusTraversalPolicy {
16  	private final Component m_Components[];
17  	////////////////////////////////////////////////////////////////////////////
18  	//
19  	// Constructor
20  	//
21  	////////////////////////////////////////////////////////////////////////////
22  	public FocusTraversalOnArray(Component components[]) {
23  		m_Components = components;
24  	}
25  	////////////////////////////////////////////////////////////////////////////
26  	//
27  	// Utilities
28  	//
29  	////////////////////////////////////////////////////////////////////////////
30  	private int indexCycle(int index, int delta) {
31  		int size = m_Components.length;
32  		int next = (index + delta + size) % size;
33  		return next;
34  	}
35  	private Component cycle(Component currentComponent, int delta) {
36  		int index = -1;
37  		loop : for (int i = 0; i < m_Components.length; i++) {
38  			Component component = m_Components[i];
39  			for (Component c = currentComponent; c != null; c = c.getParent()) {
40  				if (component == c) {
41  					index = i;
42  					break loop;
43  				}
44  			}
45  		}
46  		// try to find enabled component in "delta" direction
47  		int initialIndex = index;
48  		while (true) {
49  			int newIndex = indexCycle(index, delta);
50  			if (newIndex == initialIndex) {
51  				break;
52  			}
53  			index = newIndex;
54  			//
55  			Component component = m_Components[newIndex];
56  			if (component.isEnabled()) {
57  				return component;
58  			}
59  		}
60  		// not found
61  		return currentComponent;
62  	}
63  	////////////////////////////////////////////////////////////////////////////
64  	//
65  	// FocusTraversalPolicy
66  	//
67  	////////////////////////////////////////////////////////////////////////////
68  	public Component getComponentAfter(Container container, Component component) {
69  		return cycle(component, 1);
70  	}
71  	public Component getComponentBefore(Container container, Component component) {
72  		return cycle(component, -1);
73  	}
74  	public Component getFirstComponent(Container container) {
75  		return m_Components[0];
76  	}
77  	public Component getLastComponent(Container container) {
78  		return m_Components[m_Components.length - 1];
79  	}
80  	public Component getDefaultComponent(Container container) {
81  		return getFirstComponent(container);
82  	}
83  }