-1

I have built my own K-ary tree, which contains nodes storing data about a file system entries. I would like to be able to display this in a JScrollPane or something similar. I've now found the JTree class, but am struggling to find how to efficiently translate the information from my tree to the JTree, while still maintaining my tree functionality, for example I'd like to be able to select a node from the JTree and get the information from my own tree.

public class DirectoryTree implements Serializable {

    private TreeNode Root;
    private int numNodes;

    private TreeNode Focus;
    private LocalDateTime date;

    private long totalSizeOnDisk;

I had originally decided to create a class NodeWithButton, and create a tree hierarchy on a scroll pane using buttons, but I would have to recursively create them and their listeners and it all became a little too much to deal with.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Richardweber32
  • 168
  • 2
  • 16
  • Swing is based on data models. When you have your own data that you want a Swing component to display, you write your own model which wraps your data. In this case, you should write your own implementation of [TreeModel](http://docs.oracle.com/javase/8/docs/api/javax/swing/tree/TreeModel.html). – VGR Mar 30 '17 at 14:34
  • See also the [File Browser GUI](http://codereview.stackexchange.com/q/4446/7784). – Andrew Thompson Mar 30 '17 at 14:52
  • @VGR You mean I should write another class which implements TreeModel and contains an object of my DirectoryTree, and then ask the JScrollPane to display that? – Richardweber32 Mar 30 '17 at 14:55
  • Yes to the first part, but JScrollPane has nothing to do with it. – VGR Mar 30 '17 at 14:56
  • 1
    @AndrewThompson Thanks! This will help greatly. – Richardweber32 Mar 30 '17 at 14:58
  • See also the `FileTreeModel` cited [here](http://stackoverflow.com/a/34224804/230513). – trashgod Mar 30 '17 at 19:20

1 Answers1

0

In case anyone stumbles across this, it was a fairly simple solution.

JScrollPane takes a TreeModel as an argument for the constructor, so with the tip from VGR in the comments, I just made a new class DirectoryTreeModel, which implemented TreeModel, and contained an instance of my DirectoryTree and then overwrote the methods with my own tree functions. e.g.:

@Override
public Object getChild(Object parent, int index) {

    TreeNode p = (TreeNode) parent; //got to cast the object class into my TreeNode class
    return p.getChildren().get(index);

}
Richardweber32
  • 168
  • 2
  • 16