PDA

Click to See Complete Forum and Search --> : Can this java code be reduced?


debbie_82
Mar 12th, 2004, 12:04 AM
final class TraverseGrid{
private final static int UP = 1;
private final static int DOWN = 2;
private final static int LEFT = 3;
private final static int RIGHT = 4;

private static Vector getAllFocusableComponents(Container cycleRoot){
Vector components = new Vector();
int iCtr;

for (iCtr = 0; iCtr < cycleRoot.getComponentCount(); iCtr++) {
if ((cycleRoot.getComponent(iCtr).isFocusable()) == true){
components.addElement((Object)cycleRoot.getComponent(iCtr));
}
}
return components;
}

private static Component mapComponent(Vector components, Component origin, int position){
Component comp;
Vector subset = new Vector();
Vector row = new Vector();
Point reference = origin.getLocation();
int minimum = origin.getLocation().y;
Component temp;
int iCtr;
for (iCtr = 0; iCtr < components.size(); iCtr++ ) {
temp = (Component)components.elementAt(iCtr);
if ((position == UP && origin.getLocation().y > temp.getLocation().y) ||
(position == DOWN && origin.getLocation().y < temp.getLocation().y)) {
if (minimum == origin.getLocation().y)
minimum = temp.getLocation().y;
else if ((position == UP && minimum < temp.getLocation().y)||
(position == DOWN && minimum > temp.getLocation().y))
minimum = temp.getLocation().y;
subset.addElement(temp);
}
}

comp = origin;
for (iCtr = 0; iCtr < subset.size(); iCtr++) {
temp = (Component)subset.elementAt(iCtr);
comp = temp;
if (temp.getLocation().y == minimum && temp.getLocation().x >= origin.getLocation().x)
break;
}
return comp;
}

private static Component getComponent(Vector components, Component theComponent, int iDirection){
Component comp = theComponent;
int iCtr;

for (iCtr = 0; iCtr < components.size(); iCtr++) {
if (theComponent.equals((Component)components.elementAt(iCtr)) == true){
if (iDirection == RIGHT)
iCtr++;
else
iCtr--;
break;
}
}
if (iCtr > -1 && iCtr < components.size())
comp = (Component)components.elementAt(iCtr);
return comp;
}
synchronized public static Component getAboveComponent(Container cycleRoot, Component origin){
Vector comp = getAllFocusableComponents(cycleRoot);
return mapComponent(comp, origin, UP);
}
synchronized static Component getBelowComponent(Container cycleRoot, Component origin){
Vector comp = getAllFocusableComponents(cycleRoot);
return mapComponent(comp, origin, DOWN);
}
synchronized static Component getNextComponent(Container container, Component origin){
return getComponent(getAllFocusableComponents(container), origin, LEFT);
}
synchronized static Component getPreviousComponent(Container container, Component origin){
return getComponent(getAllFocusableComponents(container), origin, RIGHT);
}
}

CornedBee
Mar 14th, 2004, 03:05 AM
I doubt that the code itself can be made much faster.