How do I make nodes in my JTree render as JTextPanes ?

As a newbie to Java, I developed an application which started out by by having a user select a value in a JList and associated information was formatted nicely into a JTextPane (really it is just making some bold/italic/regular font switches).
I now think it may be more visually appealing to represent the whole thing as a JTree, and the user would just click the +/- to access the associated information.
So I would like substitute the JTree for the JList, while keep my nicely formatted JTextPane and am a bit stuck. I'd like each item in the JList to be a node and the information is going to be a leaf.
Searching through the forums and other tutorials it I think I need to create a TreeCellRenderer that uses my JTextPane.
Aside from advice such as Prior Planning Prevents Poor Performance, can someone give me a gentle kick in the right direction ? Pseudo-code or links would be great !
Thanks in advance.

Hi codingMonkey,
I've looked at both of those (previously) but I've not got enough experience to figure out the coding bits for my application.
So lets say I wanted to hack the JTextPane example here http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html and put a simple JTree in its place with three nodes and use the provided JTextPane as a text for the leafs.
I think the important bits (except are addStylesToDocument) are this:
private JTextPane createTextPane() {
        String[] initString =
                { "This is an editable JTextPane, ",            //regular
                  "another ",                                   //italic
                  "styled ",                                    //bold
                  "text ",                                      //small
                  "component, ",                                //large
                  "which supports embedded components..." + newline,//regular
                  " " + newline,                                //button
                  "...and embedded icons..." + newline,         //regular
                  " ",                                          //icon
                  newline + "JTextPane is a subclass of JEditorPane that " +
                    "uses a StyledEditorKit and StyledDocument, and provides " +
                    "cover methods for interacting with those objects."
        String[] initStyles =
                { "regular", "italic", "bold", "small", "large",
                  "regular", "button", "regular", "icon",
                  "regular"
        JTextPane textPane = new JTextPane();
        StyledDocument doc = textPane.getStyledDocument();
        addStylesToDocument(doc);
        try {
            for (int i=0; i < initString.length; i++) {
                doc.insertString(doc.getLength(), initString,
doc.getStyle(initStyles[i]));
} catch (BadLocationException ble) {
System.err.println("Couldn't insert initial text into text pane.");
return textPane;
I don't really understand the TreeCellRenderer API link you sent and how to link the above JTextPane to the TreeCellRenderer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • How to select a node in a JTree by name

    I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
    Thanks!

    I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
    So in short, I have the String name of the node that I want to programatically select.
    Thanks!

  • How to highlight a node in a JTree???

    I am trying to highlight (actually set the Font to Bold) one node of a JTree when an TreeSelectionEvent occurs (valueChanged method). The node to be highlighted can be different than the one selected.
    Thanks for your help.
    JavaSan

    To control the appearance of tree nodes, you need to write a TreeCellRenderer. Check Sun's tutorial on how to use trees (there's a link to it in the API documentation for JTree). The signature of the method you need to implement is this:
    public Component getTreeCellRendererComponent(
        JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)so as you can see, you can vary the appearance of the node based on any of the parameters of that method.

  • How to use custom nodes in a JTree without reinventing the wheel?

    Hello,
    Each node contains two JTextAreas in a Box layout and a few JButtons.
    I wish to display these nodes in a JTree.
    Reading the tutorial, it seems I would have to reimplement the TreeModel, TreeCellRenderer/Editor, MutableTreeNode interfaces etc.
    Can I use the DefaultTreeModel, and other standard widgets (great stuff!) to minimize the amount of reimplementation I must do. aka avoid reinventing the wheel? I was thinking of extending my node from the DefaultMutableTreeNode class - however it does not display the nodes with the TextAreas, buttons etc.
    any help appreciated.
    thanks,
    Anil

    was able to fix it over here:
    http://forum.java.sun.com/thread.jspa?messageID=4089777

  • How to get a node  in a Jtree on which right mouse button is clicked

    I am dealing with a situation in which whenever tree component is clicked by right mouse button I am needed to get the tree node on which right mouse button was clicked.

    MouseEvent e = ...
    TreePath path = tree.getPathForLocation(e.getX(), e.getY());
    Object nodeClickedOn = path.getLastPathComponent();Or something along those lines.

  • How to remove a node from  a Jtree?

    I tried giving this to move a node from one parent node to other parent node.
    IconNodeClass userObject = (IconNodeClass)tr.getTransferData(TransferableDataItem.Image_Tree_Node_Flavor);
    IconNodeClass node = (IconNodeClass)path.getLastPathComponent();
    IconNodeClass newNode = new IconNodeClass(userObject);
    DefaultTreeModel model = (DefaultTreeModel)getModel();
    IconNodeClass oldParentNode = (IconNodeClass)userObject.getParent();
    Object oldParent = oldParentNode.getUserObject();
    Object newParent = node.getUserObject();
    if(oldParent.equals(newParent)) {
    model.insertNodeInto(newNode, node, 0);
    if(oldParentNode != null) {
    oldParentNode.remove(newNode);
    model.reload(oldParentNode);
    }

    what happened next ?????

  • How to dynamically add Nodes to JTree?

    How to add nodes to a Jtree by getting the information into a specific file
    For example, in JList:
    DefaultListModel workgroups;
    workgroups = new DefaultListModel();
    List<String> workgroupsList = new ArrayList<String>();
    workgroupsList = ParserUtils.getWorkgroupList(ParserUtils.getConfigPath() + "\\.workgroup.properties");
    if (!workgroupsList.isEmpty()){
         for (String workgroup : workgroupsList){
              workgroups.addElement(workgroup.toString().trim());
    workgroupList = new JList(workgroups); //adds the list workgroupsThe output of this will be a JList displaying the list of workgroups per line. The list could be found in a file name "workgroup.properties"
    Question is, is it possible to adapt this same method in JTree. The information per line will serve as one node in the tree. For example, I have 3 workgroups in the list, there will also be 3 nodes to be found in the tree.
    Any suggestions?
    THanks.

    There's a huge JTree example in the Swing tutorial. It's a bit of a beast to use.

  • How can I make a "property node" for a VI?

    Hello!
    If I add a boolean button on the FP then I am able to make a property node for that button in the Block Diagram. But how can I make a property node for a VI? I have several VI:s an that together is one program. What I need to do is to verify what kind of VI some of my VI:s is. I need to verify if it is .exe or .vi-file, and if it is .exe then I want to disable run, abort, run continuously bottons otherwise not. I have hard that this is possible to do programmaticaly but I can´t figure out how. I am aware that I could do that manually in the File->vi properties->customize->windows appearance but theese choises makes it last forever.
    I want to be able to stop and run and everything if it is a .vi file, but if it is .exe-file then all those buttons should be disabled.
    Anyone have an example on this?
    In an other message at this Forum I read "You can use the `Front Panel Window. Allow Runtime PopUp`" property to disable run-time shortcuts menues programmaticaly, but still I dont know how to create this property node.
    /Amir

    You really shouldn't open a new thread. If you don't understand something, ask and we will explain it.
    Like I said in the other thread, you can check if you are running in LV or an EXE by using the Application>>Kind property. To get it, place a property node (from the Application Control palette) on the diagram, click it and find the property.
    To set the properties for the VI, place another property node, right click it and select Select Class>>VI Server>>VI. You should have the properties you want under Front Panel Window.
    To learn more about LabVIEW, I suggest you try searching this site and google for LabVIEW tutorials. Here and here are a couple you can start with. You can also contact your local NI office and join one of their courses.
    In addition, I suggest you read the LabVIEW style guide and the LabVIEW user manual (Help>>Search the LabVIEW Bookshelf). I believe chapter 17 of the user manual explains about programmatic control of VIs.
    Try to take over the world!

  • How to get total number of nodes in a JTree?

    Hi,
    I am trying to get total number of nodes in a JTree, and cannot find a way to do it.
    The current getRowCount() method returns the number of rows that are currently being displayed.
    Is there a way to do this or I am missing something?
    thanks,

    How many nodes does this tree have?
    import java.awt.EventQueue;
    import javax.swing.*;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.*;
    public class BigTree {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    TreeModel model = new TreeModel() {
                        private String node = "Node!";
                        @Override
                        public void valueForPathChanged(TreePath path,
                                Object newValue) {
                            // not mutable
                        @Override
                        public void removeTreeModelListener(TreeModelListener l) {
                            // not mutable
                        @Override
                        public boolean isLeaf(Object node) {
                            return false;
                        @Override
                        public Object getRoot() {
                            return node;
                        @Override
                        public int getIndexOfChild(Object parent, Object child) {
                            return child == node ? 0 : -1;
                        @Override
                        public int getChildCount(Object parent) {
                            return 1;
                        @Override
                        public Object getChild(Object parent, int index) {
                            return node;
                        @Override
                        public void addTreeModelListener(TreeModelListener l) {
                            // not mutable
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(new JScrollPane(new JTree(model)));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }But for bounded tree model using DefaultMutableTreeNode look at bread/depth/preorder enumeration methods to walk the entire tree. Or look at the source code for those and adapt them to work with the TreeModel interface.

  • How to tap non node area in a JTree

    how can I trap area of a JTree which does not constitute the node rows???

    selPath.getPathForLocation(me.getX(),me.getY())
    this function returns null if there is no rows. you cant track by this.
    Raheel

  • How do I get a dotted line to connect nodes in a JTree?

    I am trying to recreate a Windows Explorer application, does anyone know how they get the dotted lines to connect the nodes in the JTree????

    JTree uses a specific line style to represent the edges between nodes. The default is no edges, but we can set JTree�s lineStyle client property so that each parent node appears connected to each of its child nodes by an angled line:
    myJTree.putClientProperty("JTree.lineStyle", "Angled");
    We can also set this property such that each tree cell is separated by a horizontal line:
    myJTree.putClientProperty("JTree.lineStyle", "Horizontal");
    To disable the line style:
    myJTree.putClientProperty("JTree.lineStyle", "None");
    As with any Swing component, we can also change the UI resource defaults used for all instances of the JTree class. For instance, to change the color of the lines used for rendering the edges between nodes as described above, we can modify the entry in the UI defaults table for this resource as follows:
    UIManager.put("Tree.hash", new ColorUIResource(Color.lightGray))
    Hope this serves your purpose.
    Regards,
    Sachin Shanbhag

  • How to allow multiple selection of nodes in a JTree

    How to allow multiple selection of nodes in a JTree ?
    Thanks
    S.Satish

    By default when you create new instance og JTree the selection model is multiple selection. And if you want to change it you use next:
    tee.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Hope will help!

  • How to remove all nodes (except root node)from a Jtree?

    How to remove all nodes (except the root node)from a Jtree?

    Either:
    - remove all children of root.
    - save the root node, throws away the tree model, build a new TreeModel with the saved root, set the new TreeModel in the JTree.
    - implement your own TreeModel, which would support an emptyExceptRoot() method.
    IMHO, using the DefautlTreeModel and DefaultMutableTreeNode does lead to all sorts of small problems when the app evolves, and implementing your own TreeNode and TreeModel is not that hard and much more efficient.

  • How do i expand all the nodes in a jtree

    Hi,
    I am working on a project where i need to expand all the nodes of a jtree i have tried a few different ways but it never seems to expand all the nodes..
    I would be very greatful if someone could point me in the right direction
    cheers
    Mary

    you could use the following method that expands nodes recursively
    expandNode( myTree, myRootNode, new TreePath( myRootNode ) );
    public static void expandNode( JTree tree, TreeNode node, TreePath path ) {
        tree.expandPath( path );
        int i = node.getChildCount( );
        for ( int j = 0; j< i; j++ ) {
            TreeNode child = node.getChildAt( j );
            expandNode( tree, child , path.pathByAddingChild( child ) );
    }

  • How to Remove a Node from JTree?

    I want to remove a node from a JTree but the node may or maynot be visible.
    My method takes a String which is the name of the node.
    The nodes im using are DefaultMutableTreeNode
    This is my code so far but it doesnt work.
    public void removePerson(String pName)
              TreePath node = tree.getNextMatch(pName,0,Position.Bias.Forward);
              tree.expandPath(node);
              tree.removeSelectionPath(node);
    }Any Suggestions or ways which i could achive this?
    Thank you,

    I don't think removeSelectionPath is what you want to use.
    These should help:
    [http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)|http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)]
    [http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml|http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml]

Maybe you are looking for

  • I can't import certain CDs into I tunes

    Hello, I am having trouble importing Cd's into I tunes. I will put the CD in and it will only import the first 5 seconds of the first song and then it will stop and the computer no longer recognizes the CD drive. If I reboot my computer the drive com

  • How can I make metadata saved to xmp file stay saved?

    When a raw file badge shows that the file has been changed, I use Metadata Save to File & for the large majority of my images, the badge goes away and Metadata Status Changed does not show the file.  For some of my files, however, the Save to File co

  • How do i get quicktime for my iphone4 to watch tv commericals sent to me

    I need to understand why i can not open and view my commercials sent as attachments to my phone?

  • How to handle "Display/Change" mode in XD0x with CUSTOMER_ADD_DATA_CS

    Hi, I've implemented customer fields to the debitor master data screen with BADI CUSTOMER_ADD_DATA_CS, using methods SET_DATA and GET_DATA and created a new screen within a Z-function group. So I have a new tab with the custom fields. If I do nothing

  • Shift+A not working

    The machine is a Macbook with 2GHz and 1GB ram. Shift+A is not working. The shift key will work when capitalizing any of the other letters except A. Anyone know what this problem is?