1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
public class SelecTree extends JFrame {
public static void main(String[] args) {
new SelecTree(hierarchy);
}
static int[] hierarchy = {1, 2,3,0,4,7,8,-1,0,5,6,-1};
public SelecTree(int[] hierarchy) {
super("");
Container content = getContentPane();
DefaultMutableTreeNode root = processHierarchy();
JTree tree = new JTree(root);
tree.expandRow(0);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(250, 275);
setVisible(true);
}
int index=0;
private DefaultMutableTreeNode processHierarchy() {
DefaultMutableTreeNode node =
new DefaultMutableTreeNode(hierarchy[index]);
DefaultMutableTreeNode child=null;
index++;
while(index <hierarchy.length-1 && hierarchy[index]!=-1) {
int a = hierarchy[index];
if (a == 0){ // node with children
index++;
child = processHierarchy();
}else{
child = new DefaultMutableTreeNode(a); // Leaf
}
node.add(child);
index++;
}
return(node);
}
} |
Partager