Jtree Handles but no children problem

My tree uses data from a database to populate. What I want is there to be the little handle image to open and close, whether or not there are children. The reason why is, I don't want the database queried until the uses tries to expand the node. I've tried using the DefaultCellRenderer to set leaf nodes to the default closed position and open position, but i just get little folder not the expandable handles. It needs to behave as though is has children, even though it has none. Right now I have it all working with a placeholder to trick each node and when I retrieve the data it vanishes (user never sees it) but it seems like there should be a better way. Help(?) jaszzmongrel

I hate this, but don't know of a better way.import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import javax.swing.tree.*;
import java.util.*;
public class Test2 extends JFrame {
  private static final Random rand = new Random();
  public Test2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    DefaultMutableTreeNode mtn = new DefaultMutableTreeNode("Root");
    for (int i=0; i<5; i++) mtn.add(new MyTreeNode("Node-"+i));
    JTree jt = new JTree(mtn);
    jt.addTreeWillExpandListener(new javax.swing.event.TreeWillExpandListener() {
      public void treeWillExpand(TreeExpansionEvent tse) {
        TreeNode tn = (TreeNode)tse.getPath().getLastPathComponent();
        if (tn instanceof MyTreeNode && !((MyTreeNode)tn).isChildChecked()) {
          int r = rand.nextInt(3);
          ((MyTreeNode)tn).removeAllChildren();
          for (int i=0; i<r; i++) ((MyTreeNode)tn).add(new MyTreeNode("Child-"+i));
      public void treeWillCollapse(TreeExpansionEvent tse) {}
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    jt.setShowsRootHandles(true);
    setSize(300,300);
  public static void main(String[] args) { new Test2().setVisible(true); }
class MyTreeNode extends DefaultMutableTreeNode {
  boolean childCheck = false;
  public MyTreeNode(Object obj) {
    super(obj);
    add(new DefaultMutableTreeNode());
  public boolean isChildChecked() { return childCheck; }
  public void add(MutableTreeNode mtn) {
    if (childCheck) {
      removeAllChildren();
      childCheck=true;
    super.add(mtn);
}

Similar Messages

Maybe you are looking for