Search code examples
javaswingjtreejtextarea

How to display JTree file in JTextArea


In my program i have a JTree which is being populated by a number of folders and files. When you select a file in the JTree I want that file to display in the JTextArea.

I no you can use getLastSelectedPathComponent() to get the last selected item from the JTree which can be used to get the chosen file from the tree but this is then a node of the tree... is there a way to get the text from this node like using a FileReader and a BufferReader?


Solution

  • Not directly. What you will need to do:

    1. Store the file name (with path if you want to make your life easier) in the node. Extend DefaultMutableTreeNode for this.
    2. When a node is selected, read the file name from it.
    3. Use the usual Java IO API to read the file as text