JTree ScrollBar

Hi,
I have a JTree component placed into a JScrollpane which is itself placed in a JSplitPane.
When I expand all my tree, I would like to have a scroll bar appearing in order to see all the nodes of my tree but it doesn't appear.
Does anybody have an idea ??

Found my answer,
For those who don't know, you effectively need to put your JTree in a JScrollPane but you also need NOT to define the setPreferredSize() and setMaximumSize() of your JTree

Similar Messages

  • JTree scrollbar problem - can't scroll back to top when some nodes hidden

    I have a problem which I cannot resolve: I have a JTree which has had 88 rows added to it, and which then has 15 or so rows set to be not visible; when I then scroll to the bottom of the pane I am unable to scroll all the way back to the top using either the scroll button at the top of the bar or the mouse scroll wheel although I can drag the knob to get to the top; using the button or wheel, the scrolling stops somewhat short of the top; via testing I've found that the AdjustmentEvent is not fired when it reaches that point. Anyone seen this before and/or know a way around it?
    Thanks in advance,
    Mike

    MikeAuerbach267 wrote:
    It turns out that my problem was due to the fact that I am using my own TreeCellRenderer which makes invisible some nodes via user option but doesn't reload the tree; hence the confusion as to the scrollbar size. I now correctly reload after user option has changed rather than render nodes invisible and all is fine. Which reinforces Andrew's view in reply #1 that a 'vague waving about of hands' does not allow the forum members to help.

  • Popup JTree

    I created a subclass of JWindow which acts as a popup when the appropriate mousebutton is clicked. A JTree is shown in an etched border and when the user selects an item in the tree it updates the JTextField the popup is connected to. It is similar in concept to a JComboBox but rather then a list, it uses a tree. It is connected to two JTextFields in a subclass of JDialog. This works great when dialog box is run in the applet window under VAJ. However, when the dialog box is created (.show()) from within a JApplet in the browser it appears fine when the right mouse button is pressed in the appropriate JTextField but as soon as a mouse button is pressed within the popped up JTree, the popped up window (JWindow subclass) is forced behind the other window. If the roller on the microsoft mouse is used the jtree can be scrolled but if I try to manipulate the scrollbar the window disappears behind the parent window. How can I lock the window in place until I dispose of it??
    Thanks,
    Walt

    The problem is actually a problem in VAJ. The code generated by the VCE does not allow for creating the popup with a parent window. It is still unclear why when it was created on top of the 'parent' window and the scrollbar should have digested the mouse event, that the mouse event percolated through the popup to the underlying window, causing it to gain focus and be placed on top in the Z order. Anyone that can answer that one get the duke bucks too. What I did was modify the alternative constructors for the popup to initialize the window (set the listeners) which appears to be another bug in VAJ and then manually create the popup as invisible. Normally VAJ uses lazy construction to only construct the object upon first reference. Since that code is automatically regenerated by the VCE I couldn't modify it.
    Another question is why does the JWindow appear with the foolish "Java Applet Window" text in a status area. And why does a JWindow even have a status area? The drop down list of a JComboBox doesn't have one. And that was really all I wanted was a JComboBox with a tree instead of a list. So if anyone can address that, there are duke dollars available for it as well.
    So the questions are:
    1) why does the mouse action percolate through the popup window, which should have captured and digested it, even if only through the scrollbar logic?
    2) what does the JWindow based popup get stuck with the "Java Applet Window" text in an unwanted status area.
    3) how could this simply be like a JComboBox with a drop down JTree, as opposed to drop down list?
    Thanks,
    Walt

  • JSplitPane, JScrollPane and JTree resizing

    Hi,
    In a JSplitPane, I have, in the left part, a JScrollPane, containing a JTree and, in the right part, I have an other panel.
    When I click on different nodes in the JTree, the width of the left part changes, so the JSplitPane separator moves. How to avoid that ? I would prefer a scrolling move inside the JScrollPane !
    I am using JDK 1.3
    Thanks
    Olivier Scalbert

    Try to define the JScrollPane as
    public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
    Use vsbPolicy and hsbPolicy like the VERTICAL_SCROLLBAR_AS_NEEDED
    HORIZONTAL_SCROLLBAR_AS_NEEDED respectively.
    Then define the setPreferredSize to your JScrollPane. This preferredSize must be smaller than the size of the Component view if you want to see the ScrollBar.
    By the way, when you define your JSplitPane have to define the setOneTouchExpandable(true);?

  • JTree in JScrollPane doesn't scroll

    I have a JTree in a JScrollPane that doesn't scroll.
    Background: it used to!
    History: I moved the creation of the JTree to inside an Object that returns it with a ".getTree()" method. Since then, it hasn't been scrolling. I even set the JScrollPane to always have scrollbars and they just sit there inactive.
    Does anyone know what this would happen and/or how to fix it?
    thanks.

    That actaully worked, but it was way to big. I'm not sure what I did, but I changed the values to Studio ONE's defaults and now it works ok.

  • JTree in JScrollpane, find out

    I have following constellation:
    A JTree in a JScrollpane with a vertical scrollbar.
    Most nodes are hidden "behind the scrollpane" and only view are seen.
    I search for a property which signals if a node is currently seen on screen and which are "scrolled" (that means those nodes which aren't visible) (the jcomponent method isVisible() doesn't work)
    I think about such a method which uses the information of the scrollbarposition and the dimension of the jviewport but i can't get the information which node is seen if some nodes are expanded and some are collapsed.
    Does anybody know such a property or method?
    Or is there a SWING-THING which solves the problem?
    Thank you for your answers

    isVisible() is a "Component-Method" which means i have to take the rendered component finding out the visible nodes.
    my application is following:
    i write a method which expand all nodes until the leafs are visible but because of performance (i have more than 1000 nodes directly under the root) i want to expand only the nodes which are showing and expand the other later.

  • JTree custom renderer - JScrollPane

    Hi,
    I am building a JTree and need a custom renderer that will allow me to display the contents of certain leaf nodes in a JEditorPane that is contained in a scrollpane as the leaf may contain a varying amount of text.
    I have managed to get a renderer displaying the text as expected however the scrollbars do not work as I hoped - I cannot scroll down the editorpane.
    Has anyone got an example of a renderer that uses a scrollpane, any help/suggestions would be gratefully received.
    Thanks

    Return the size of your editor pane in customized cell renderer's getPreferredSize() method and set JTree rowHeight to zero. When row height is 0, it use renderer's getPreferredSize() to get size of the cell, I think. I have made custom cellrenderer which extends Jpanel and in getCellRendererComponent I add there another panel which contains buttons etc. I have used super.getPreferredSize() in my renderer's getPreferredSize() method.

  • How to make only right handside scrollbar?

    in a frame, i just want to have the right handside scrollbar, and omit the bottom one?
    can anyone help? thanks!

    You can do it with a JScrollPane and set the horizontal scroll bar policy to never. You can put your component in place of the JTree here that I used as a sample.
    import java.awt.*;
    import javax.swing.*;
    public class TestFrame extends JFrame {
        public TestFrame() {
            JScrollPane scrollPane = new JScrollPane(new JTree());
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            getContentPane().add(scrollPane);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String [] args) {
            new TestFrame();
    }

  • Autoscroll behavior during DnD in JTree, 1.4 vs 1.6

    The following code compiles under both Java 1.4 and Java 1.6. I'm wondering if anyone knows why the following actions cause different behaviors between the two versions:
    1. When the frame opens, you should see a fully-expanded tree (which, because of the small size, causes a vertical scrollbar to appear).
    2. Make a drag-and-drop gesture on the first child node ("blue"), and attempt to cause the tree to scroll down so you can drop it on the last parent node ("food").
    Under 1.6, the tree scrolls nicely as you hold the DnD gesture.
    Under 1.4, the tree does not scroll. I had some hope JTree.setAutoscrolls(true) would help, but it did not.
    Any suggestions how to get 1.4 to behave the way 1.6 does?
    Thanks for your time.
    import javax.swing.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import java.util.Enumeration;
    public class AutoScroll14 extends JFrame {
        public static void main(String[] args) {
            new AutoScroll14();
        public AutoScroll14() throws HeadlessException {
            super("AutoScroll 1.4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            public boolean importData(JComponent comp, Transferable t) {
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return false;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return false;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return true;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    return new StringTransferable(toTransfer);
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { localStringFlavor };
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;

    I added the class "TreeDropTarget".
    "TreeDropTarget" extends the class "DropTarget", which implements the interface "DropTargetListener".
    DropTargetListener has a few methods, that are called automatically by Swing during drag operation
    (dragOver, dragExit, drop). So we can implement "autoscroll", as well as "automatic node expansion".
    With "automatic node expansion", a collapsed node will be expanded,
    so that its children become visible and we can do a drop on them:
    package demo;
    * AutoScroll.java
    * source level 1.4
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.io.*;
    import java.util.*;
    public class AutoScroll extends JFrame {
        public static void main(String[] args) {
            new AutoScroll();
        public AutoScroll() throws HeadlessException {
            super("AutoScroll " + System.getProperty("java.version"));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            tree.setDropTarget(new TreeDropTarget());//<----------------------
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private AutoScroll.MyTransferHandler.StringTransferable transferable;
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            protected void exportDone(JComponent comp, Transferable t, int action) {
                if (t == null) {
                    t = transferable;
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    transferable = new StringTransferable(toTransfer);
    return transferable;
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[]{localStringFlavor};
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;
    class TreeDropTarget extends DropTarget {
    public TreeDropTarget() {
    super();
    public void dragOver(DropTargetDragEvent dtde) {
    JTree tree = (JTree) dtde.getDropTargetContext().getComponent();
    Point loc = dtde.getLocation();
    updateDragMark(tree, loc);
    autoscroll(tree, loc);
    super.dragOver(dtde);
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTree tree, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = tree.getVisibleRect();
    Rectangle inner = new Rectangle(
    outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(
    cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    tree.scrollRectToVisible(scrollRect);
    public void updateDragMark(JTree tree, Point location) {
    int row = tree.getRowForPath(tree.getClosestPathForLocation(location.x, location.y));
    TreePath path = tree.getPathForRow(row);
    if (path != null) {
    markNode(tree, location);
    private void markNode(JTree tree, Point location) {
    TreePath path = tree.getClosestPathForLocation(location.x, location.y);
    if (path != null) {
    if (lastRowBounds != null) {
    Graphics g = tree.getGraphics();
    g.setColor(Color.white);
    g.drawLine(lastRowBounds.x, lastRowBounds.y,
    lastRowBounds.x + lastRowBounds.width, lastRowBounds.y);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    private Rectangle lastRowBounds;
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);

  • Scroll bar hides bottom of JTree

    I have a dialog with a JTree in a JScrollPane and it's possible to have the dialog at just the right size that the scroll pane becomes confused. Both scroll bars are displayed and when I try to scroll down to the bottom of the tree, the scroll pane keeps resetting itself so that the horizontal scroll bar covers the bottom of the tree. If I want to see the bottom of the trr, I must resize the dialog. I looked in the bug database but didn't find anything similar to this problem.
    Ken

    It's not that the vertical scrollbar is the wrong size. It's that the VSB's thumb won't stay all the way at the bottom. Instead, it springs back to a position approx. halfway. The problem occurs when there's enough text in a tree entry to force the display of the HSB and the VSB's thumb is all the way at the bottom. I can't include a screen shot here as the boss doesn't want to have to mess with proprietary info and non-disclosure agreements, so I hope the description I gave is sufficient.

  • Adding Jtree to Panel

    Hi all,
    I have a JTree in a scrollpane rendered with checkbox on each node. I
    When I try adding to JFrame its displaying with scrollbar as expected. like this
    frame.setContentPane(scrollPane); //working fineBut When I try adding to panel and try to display that its not working
    JPanel panel = new JPanel();
    panel.add(scrollPane);
    frame.setContentPane(panel); // displaying tree without scrollbarsthanks,
    sur

    scrollPane.setPreferredSize(new Dimension(x,y));where x,y can be the width/height of the frame

  • Scrollbar in panel

    Hi,
    I want to display tree structure ina panel .
    this panel , i have created using net beans .
    i want the scrollbar to be added to the panel.
    could you please help me in getting that done.
    my code is as follows.
    Sources1 is a panel.
    tree is a JTree.
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.getViewport();
    scrollPane.setPreferredSize(new Dimension(250, 80));
    scrollPane.add(tree);
    tree.add( scrollPane, BorderLayout.EAST );
    Sources1.add(tree, "West");
    this is not displaying scrollbar.
    any help is appreciated.
    regards
    hari

    tree.add( scrollPane, BorderLayout.EAST ); You don't need this line.
    Sources1.add(tree, "West");Add the scroll pane (not the tree) to the panel.

  • JTree won't scroll

    I'm trying to add a JTree to a scrollpane so that it will scroll vertically when there are too many nodes to fit. I can't get it to ever scroll though. The scrollbar never shows up, even when the nodes start overflowing past the bottom of the visible panel. Here's the portion of my code:
    tree = new TableTree();
    JScrollPane treeScrollPane = new JScrollPane(tree);
    JPanel treePanel = new JPanel();
    treePanel.setLayout(new BoxLayout(treePanel, BoxLayout.Y_AXIS));
    treePanel.add(treeScrollPane);
    treePanel.add(saveButtons);
    getDemoPanel().add(treePanel, BorderLayout.WEST);
    I can't find anything strange in my code. I've tried directly adding the scrollpane to the main demo panel too, instead of adding it to the treePanel first, and it doesn't work. Also, earlier in my code, I'm adding a JTable to a scrollpane in the exact same way, and it works just fine. I can't figure out what's wrong...
    Any ideas? Thanks!

    Hi Starlite,
    I have a fix for you. I was scratching my head with this one for days, then voila..
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePanel extends JPanel {
        TreeModel _model;
        public TreePanel(TreeModel model) {
            super();
            try {
                _model = model;
                jbInit();
            catch(Exception ex) {
                ex.printStackTrace();
        void jbInit() throws Exception {
            this.setLayout(new GridLayout(1,1,1,1));
            this.setBorder(BorderFactory.createBevelBorder(1));
            JTree tree = new JTree(_model);
            tree.getPreferredScrollableViewportSize();
            JPanel panel = new JPanel(new GridLayout(1,1));
            panel.add(tree);
            JScrollPane scroll = new JScrollPane(panel);
            this.add(scroll);
    }I simply add the tree to a panel with a layout like a box or grid, then add the panel to the scroll pane. It works well.
    Hope this helps..
    Steve

  • Setting scrollbar in jtextarea

    hi
    Consider a JSplitPanel. in that split panel i have added jtree as the left component, and jScrollpane as the right component. if the user click a node in the jtree, i use the setDividerLocation method to divide the splite pand and add a jscrollpane at right side. in that jscrollpane i added a jtext area with the horizontal scrollbar option which will show always. thing is working well. scrollbar showing when the jscrollpane get visible. the problem is if the text of the text area is go beyond than the jtextarea viewport there is no change in scrollbar. it is showing lik dummy scrollbar without any changes.
    What i have to do to activate the scrollbar if the text in the jtextarea execde it view area?

    I devided JScrollPane Vertically. i added a jtree as left side component of JScrollPane. i did't add anythin in the right side. <br>
    if the user click a node in the JTree which is added in the left side of the jScrollpane, then i add a new jscrollpane as the right side component.<br>
    In that jscrollpane i added a JText area.<br>
    The JTextArea which i created earlier set the vertical scroll bar policy as always. so the vertical scrollbar will be shown always. <br>
    The above things working correctly.<br>
    What is wrong is,<br>
    if the user type any text more than text area, the scrollbar should be activated lik in our forums(text area). But it dos't happen to me. the empty jscrollbar is displayed eventhough the user enter more data that can't be displayed in the jtext area.<br>
    MyAction is,<br>
    if the user click the jtree, i call the setDivider location to devide the JSplitpane. so the left side componet(JTree) uses 200 as width all other width in the screen will be allocated to the JSplitPane(contains the JTextarea).<br>
    My question is,<br>
    why the JScrollbar is not activated are perform correctly eventhough the data which is entered in the JTextArea execedes the row(example 40) which i specified in the constructer when i create the jTextArea?

  • JTree in JComboBox

    Hi,
    i have create a own combobox popup editor. The editor is a JPanel and contains a JTree and a JButton.
    Now when the user clicks on the combobox the user see the JTree and the Button. When now selecting a tree node or pressing the button, always the popup editor close. I cant't find out from where the event to close the editor came. What i wantis, when the user select a node this node should be expanded or when he press the button some action should be done, but without closing the combobox editor.
    Can anybody help me???
    Thanks in advance
    Wolf

    More info
    i found out that the problem is that i add the tree in a jscrollpane.
    But without a scrollpane the popup size is to large and has no horizontal scrollbar.

Maybe you are looking for