2

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 operations.

Here is my code, is it simple to adapt 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();
  }   
}
LaPalme
  • 339
  • 5
  • 16
  • 1
    It can be performed using editors and renderers. Look the [HowTo use JTree](https://docs.oracle.com/javase/tutorial/uiswing/components/tree.html) article. Editors are better described in article about [JTable](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html) but they also work with JTree. – Sergiy Medvynskyy Jun 13 '17 at 10:39
  • Thanks for your help. I have already seen a tutorial on how to personnalize icons for the JTree. But it's a little bit more difficult with checkboxes than with draws or icons because it is a specific object and my code has errors because of that. And I have to take into account the "checked" function. – LaPalme Jun 13 '17 at 11:53
  • 1
    You simply need objects which store the name of the node and whether the node is selected. – Sergiy Medvynskyy Jun 13 '17 at 12:21
  • Ok I understand. I'll explore this solution thanks ! – LaPalme Jun 13 '17 at 13:05

0 Answers0