Expand tree row and make node visible in Java
Description
The following code shows how to expand tree row and make node visible.
Example
import java.awt.BorderLayout;
import java.util.Vector;
/* w w w . ja va 2s . c o m*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
class TreeNodeVector<E> extends Vector<E> {
String name;
TreeNodeVector(String name) {
this.name = name;
}
TreeNodeVector(String name, E elements[]) {
this.name = name;
for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}
}
public String toString() {
return "[" + name + "]";
}
}
public class Main {
public static void main(final String args[]) {
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v1 = new TreeNodeVector<String>("Two", new String[] { "Mercury", "Venus",
"java2s.com" });
Vector<Object> v2 = new TreeNodeVector<Object>("Three");
v2.add(System.getProperties());
v2.add(v1);
Object rootNodes[] = {v1, v2 };
Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
frame.add(new JScrollPane(tree), BorderLayout.CENTER);
tree.expandRow(1);
tree.scrollRowToVisible(2);
tree.revalidate();
frame.setSize(300, 300);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »