mardi 13 juin 2017

JTree replace folders icons by checkboxes

I am doing a window with a tree like this :

enter image description here

I would like to replace the folders and files icons by checkboxes. This question already has an answer, I found it in this link : Java Swing: Need a good quality developed JTree with checkboxes But I don't know if I really need to follow this answer or if I can do something "easier" to only adapt my code to have checkboxes. Could you tell me ?

Of course, then in my program I need to know all the checked boxes to do some some operations.

Here is my code, is it simple to adapt it or I have to follow the precedent tutorial ?

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class Window extends JFrame {
  private JTree tree;   
  public Window(){
    this.setSize(300, 300);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("Tree");
    //We build the tree
    buildTree();

    this.setVisible(true);
  }

  private void buildTree(){
    //We create the root
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

    //We add nodes and children to these nodes
    for(int i = 1; i < 12; i++){
      DefaultMutableTreeNode rep = new DefaultMutableTreeNode("Node number"+i);

      //We add some nodes for odd numbers
      if((i%2) == 0){
        for(int j = 1; j < 5; j++){
          DefaultMutableTreeNode rep2 = new DefaultMutableTreeNode("NodeChild" + j);
          //We add children to the nodes
          for(int k = 1; k < 5; k++)
            rep2.add(new DefaultMutableTreeNode("NodeChild" + k));
          rep.add(rep2);
        }
      }
      //We add nodes and children to the root
      root.add(rep);
    }
    //We create the tree
    tree = new JTree(root);

    this.getContentPane().add(new JScrollPane(tree));
  }

  public static void main(String[] args){
    Window win = new Window();
  }   
}




Aucun commentaire:

Enregistrer un commentaire