Spacebar in JTree

What does the spacebar do when pushed on a Jtree?
Thanks
P.S. I know it does something.

Anyone?

Similar Messages

  • Problemns with JTree

    Hi! I'm having problems with the Tree cell renderer. I must render a tree that have leafs that is also JPanels compounded by a checkbox, an icon and a the text label. It's supposed to alter the state of the checkbox when clicked or when press the spacebar over the cell, but it isn't working...
    If I set the tree as editable (down in the code, in main method), the checkbox is selected only after the second click, but the cell is not being highlighted and cannot collapse the category nodes. Otherwise, when set the Tree as NOT editable, the highlight of cell and the rest works, but obviously I cannot edit the checkboxes...
    Can someone help me, please?
    package test;
    import com.interact.sas.ResourceLocator;
    import com.interact.sas.dms.*;
    import com.interact.sas.ui.UserIconLabel;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.tree.*;
    public class DocumentControllerTreeTest
        static class MyTreeCellEditor extends AbstractCellEditor implements TreeCellEditor, TreeCellRenderer
            private static Icon iconCategory = ResourceLocator.getIcon( "sas/dms/tb_categories.png" );
            private static Border noFocusBorder = new EmptyBorder( 1, 1, 1, 1 );
            private JPanel cell = new JPanel();
            private JCheckBox checkRequired = new JCheckBox();
            private UserIconLabel userIconLabel = new UserIconLabel();
            private DocumentControllerTree.Item currentItem = null;
            public MyTreeCellEditor()
                userIconLabel.setOpaque( false );
                checkRequired.setOpaque( false );
                cell.setLayout( new BorderLayout() );
                cell.add( checkRequired, BorderLayout.WEST );
                cell.add( userIconLabel, BorderLayout.CENTER );
                cell.addKeyListener( new KeyAdapter()
                    public void keyPressed( KeyEvent e )
                        if ( e.getKeyCode() == KeyEvent.VK_SPACE )
                            checkRequired.setSelected( ! checkRequired.isSelected() );
                            e.consume();
                cell.addMouseListener( new java.awt.event.MouseAdapter()
                    public void mouseClicked(java.awt.event.MouseEvent evt)
                        checkRequired.setSelected( ! checkRequired.isSelected() );
             * getCellEditorValue
             * @return Object
            public Object getCellEditorValue()
                currentItem.getController().setRequired( checkRequired.isSelected() );
                return new Boolean( currentItem.getController().isRequired() );
             * getTreeCellEditorComponent
             * @param JTree tree,
             * @param Object value,
             * @param boolean isSelected,
             * @param boolean expanded,
             * @param boolean leaf,
             * @param int row
             * @return Component
            public Component getTreeCellEditorComponent( JTree tree,
                    Object value,
                    boolean isSelected,
                    boolean expanded,
                    boolean leaf,
                    int row)
                return getTreeCellRendererComponent( tree, value, isSelected, expanded, leaf, row, true );
             * getTreeCellRendererComponent
             * @param JTree tree,
             * @param Object value,
             * @param boolean selected,
             * @param boolean expanded,
             * @param boolean leaf,
             * @param int row,
             * @param boolean hasFocus
             * @return Component
            public Component getTreeCellRendererComponent( JTree tree,
                    Object value,
                    boolean isSelected,
                    boolean isExpanded,
                    boolean isLeaf,
                    int row,
                    boolean hasFocus )
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object object = node.getUserObject();
                if ( object instanceof DocumentControllerTree.Item )
                    currentItem = (DocumentControllerTree.Item) object;
                    checkRequired.setSelected( currentItem.getController().isRequired() );
                    //checkRequired.setSelected( !checkRequired.isSelected() );
                    int action = currentItem.getController().getAction();
                    if ( action == DocumentController.ACTION_APROVE ||
                            action == DocumentController.ACTION_VERIFY )
                        checkRequired.setVisible( true );
                    else
                        checkRequired.setVisible( false );
                    userIconLabel.setFont( tree.getFont() );
                    userIconLabel.setUser( currentItem.getUser() );
                    userIconLabel.setText( currentItem.getUser().getName() );
                else
                    // nunca poderia chegar aqui ...
                    checkRequired.setVisible( false );
                    userIconLabel.setFont( tree.getFont() );
                    userIconLabel.setIcon( ! isLeaf ? iconCategory : null );
                    userIconLabel.setText( object.toString() );
                if ( isSelected )
                    cell.setBackground( UIManager.getColor( "Tree.selectionBackground") );
                    cell.setForeground( UIManager.getColor( "Tree.selectionForeground") );
                else
                    cell.setBackground( tree.getBackground() );
                    cell.setForeground( tree.getForeground() );
                Border border = noFocusBorder;
                if (hasFocus)
                    if (isSelected)
                        border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
                    if (border == null)
                        border = UIManager.getBorder("List.focusCellHighlightBorder");
                cell.setBorder(border);
                return cell;
        public static void main( String[] args )
            try
                DocumentControllerTree tree = new DocumentControllerTree();
                DocumentManager dm = DocumentManager.getInstance();
                DocumentCategory dc = dm.getCategory( 32 );
                Vector<DocumentController> vdc = dm.getControllers( dc );
                tree.setCellRenderer( new MyTreeCellEditor() );
                tree.setCellEditor( new MyTreeCellEditor() );
                tree.setCategory( dc );
                tree.setControllers( vdc );
                // This must be true
                //tree.setEditable( true );
                JScrollPane scroller = new JScrollPane( tree );
                scroller.setPreferredSize( new Dimension( 240, 320 ) );
                JOptionPane.showMessageDialog( null, scroller );
            catch ( Exception e )
                e.printStackTrace();
            System.exit( 0 );
    }

    OK, here's briefly what I'd do:
    1
    In your tree constructor, set a custom TreeCellRenderer. (I assume your tree extends JTree.)
    2
    Create a custom TreeCellRenderer by extending JPanel and implementing TreeCellRenderer. In the getTreeCellRendererComponent method, remember you don't have to use a component that you have around. You use the tree node's text: tree.convertValueToText(value, sel, expanded, leaf, row, hasFocus)); This returns a string. The string could be "true" or "false". You then create a JCheckBox based on this value. Add the JCheckBox to �this�, i.e. to the custom TreeCellRenderer that extends a JPanel. Return �this�. Remember that once �this� is returned, the value is forgotten and the JCheckBox is unclickable. (What you click actually is the TreeCellRenderer, that then decides you want to focus a node and thereafter passes focus and subsequent clicks to your panel and/or the TreeCellEditor).
    3
    Back to the tree constructor. Set your TreeCellEditor to a custom class of yours. Copy the code from DefaultCellEditor. There is a constructor in DefaultCellEditor that accepts a JCheckBox as sole argument. Try that one. In an inner class in DefaultCellEditor, EditorDelegate, you'll find the stopCellEditing method. Override it and make sure to convert boolean values back to "true" or "false" in the tree node, so that the renderer will have the right value to work with.
    From there on, I guess things should work by themselves. (Warning: completely unchecked!!!) If not, at least the code is sufficiently separated for us to know where it fails (renderer, editor, tree...)
    PS. Second thought: DefaultMutableTreeNode accepts an Object as object, not only a string. Maybe you could use a boolean value or a Boolean object directly in the tree node instead of strings...
    Just my 2 cents

  • Exist a Jtree node.id or something like this ?

    I would want to retrieve a node using a unique 'id', for example the absolute index (into the total nodes count)
    Is there something like this ?
    Can I add a particular property to a node ? ( for example this 'id' if it does not exist )
    Another question :
    If I want to implement a search code, this 'id' can be useful, or must I transverse the whole Jtree
    Thanks

    Hello.
    Do the following:
    1. Go to the Apple Menu at the top left of the screen
    2. Select Software Update...
    3. Install any updates that are found.
    If the Amazon issue continues after these updates, then do this:
    1. Open Safari
    2. Erase any web address you have currently showing (for example www.apple.com or www.google.com)
    3. Type in www.amazon.com
    4. That should take you directly to amazon.com
    It should look like this in your Safari::

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • I recently managed to get the whole casing of my 13" Macbook Pro (Mid-2009) replaced due to a missing foot and dodgy spacebar. The lid is dented and scratched so would like to know how much it would cost to replace? I know its not covered by AppleCare.

    So i took my Macbook Pro 13'' (Mid-2009) into Apple because the spacebar was jammed and I had one of the feet of the bottom casing missing which was unusual (black circles). The unibody and bottom plate had a fair few dents and nicks and under AppleCare I was able to get the whole unibody and bottom case fixed for free. Saved myself a good £181!
    This now leaves my lid which has one or two noticeable dents and the bottom right part is suffering from several scratches. I was wondering how much a new lid would cost if I took it into Apple? I know it won't be covered under AppleCare as its accidental damage but want to know whether its worth paying for to have a once again dent free Macbook Pro .
    As a side note, do Apple upgrade your hardware at all, such as the hard drive or memory? I know it would be cheaper to do it at an independant computer shop or by myself but would like to explore my options first.

    http://www.ifixit.com/
    See my reply to your second question elsewhere.

  • Can't read or write some files, internet is failing, youtube won't load, software I tried to install was in Slovenian, not dutch or english like in my systempreferences settings, pictures and files won't preview with spacebar, etc. Malware?

    Specs:
    iMac 10.8.5
    3,4 GHz Intel Core i7
    32 GB 1600 MHz DDR3
    Can't read or write some files, internet is failing, youtube won't load, security software I tried to install was in Slovenian, not dutch or english like in my systempreferences settings, pictures and files won't preview with spacebar and are randomly corrupted, when I entered something in the Youtube searchbar (when it was still working) it send me to a site with sexadds.
    I tried restart my iMac and when I was logged back in, my dock preferences were reset.
    Also tried to download some security software to check my Mac for malware, but when I did, I tried several, I got a notification that said something like 'dumpfiles (don't know if this is the right translation...) damaged'.
    I'm taking screenshots from all the weird notifications I get and even three quarters off the screenshots I took in the last three hours are already unreadable.
    It started this morning when I tried opening a Premiere Pro file on which I worked the night before.
    When I tried opening it, it said the file was damaged and could not be openend.
    I tried opening it with AE or importing the file in a new project but nothing helped.
    When I tried looking for autosaves, this is the really weird part, there were none.
    Even though there are autosaves from my other projects, this one was completely gone.
    It looked like the day before never happened on my computer.
    Also when I openend Premiere all the recent projects had been wiped.
    So at first I thought it was a Premiere Pro failure.
    But than, later on the day, I tried loading some RAW files from my compact flash card.
    This is where I would get an error (error -36) which said some data cannot be read or written.
    I tried importing the files with a view different technics, from dragging to importing via Lightroom and I succeeded with Image Browser.
    But when I tried moving the files to an other folder the same error occurred.
    While dealing with this issue I wanted to put on some soothing music on youtube.
    This is when the next weird thing occurred: youtube wasn't completely loading in Chrome. I refreshed a view times, checked the internet connection and still no difference.
    When I tried in Safari it did work but when I clicked enter on the searchbar in Youtube, a page with sexadds appeared (I didn't install AdBlock in Safari...).
    I read about this 'phishing' where you are redirected to a site were a possible malware installment can take place...
    I don't know if it's connected to any of the problems I've been having but I just never experienced this on a mac, I have been a Mac user for 10 years now.
    On top of it all, internet started working worse and worse and now it's not even working at all. I had to fill in the password over and over, normally it remembers.
    Just like my system preferences, all the preferences I had with Chrome where also reset.
    Also somewhere in between I got this notification: Mac OS X must restore library to run programs. Type your password to allow.
    To me this is all very weird and suspicious. I have clearly no idea what's going on. Could this be another sort of trojan horse or malware?
    Some background info which could be helpful for solving this mystery:
    two months ago the one year old Fusion Drive in my iMac just broke out of nowhere.
    I got it replaced by a qualified apple repair store.
    When I got my computer back, all the files where gone.
    I got on the internet without AdBlock installed yet.
    A game or whatever it was, can't clearly remember, got installed by accident.
    I deleted it immediately.
    Only two weeks later, I couldn't log in to my account. It didn't recognize my password and username. 
    So I brought my mac back to the store.
    Here the repair guy said it was a minor thing and he just needed to reconnect my account. He also mentioned he found a downloaded game name Sparta and it probably had something to do with the error.
    I asked him; could it be a virus? He replied no way.
    I don't know why I couldn't be a virus, just because it's a mac doesn't mean it cannot be done.
    So today I tried installing anti virus software (such as avast- was in a weird language looked like slovenian, clamxav - was in slovenian) but I couldn't install them.
    PLEASE help me! I don't know what to do anymore, I work fulltime and I need my computer, I have no time to bring it in for repair, are there other perhaps easier ways?
    Could this be the work of a virus or a malware? Or is it a disk permissions issue?

    It sounds like you may have multiple problems, but none of them are likely to be caused by malware.
    First, the internet-related issues may be related to adware or a network compromise. I tend to lean more towards the latter, based on your description of the problem. See:
    http://www.adwaremedic.com/kb/baddns.php
    http://www.adwaremedic.com/kb/hackedrouter.php
    If investigation shows that this is not a network-specific issue, then it's probably adware. See my Adware Removal Guide for help finding and removing it. Note that you mention AdBlock as if it should have prevented this, but it's important to understand that ad blockers do not protect you against adware in any way. Neither would any kind of anti-virus software, which often doesn't detect adware.
    As for the other issues, it sounds like you've got some serious corruption. I would be inclined to say it sounds like a failing drive, except it sounds like you just got it replaced. How did you get all your files back after the new drive was installed?
    (Fair disclosure: I may receive compensation from links to my sites, TheSafeMac.com and AdwareMedic.com, in the form of buttons allowing for donations. Donations are not required to use my site or software.)

  • In Pages 5.5.1 when I go to the Open menu I cannot get a preview of any of the files in the list using the spacebar, which I can do in every other application and finder. Is there a workaround?

    In all other applications and in the finder, if I select a document and press the spacebar I get a quickview preview of that file. It does not work in Pages when I choose Open and am given a list of files to select from. This was not the case in older versions of Pages. Is there a workaround, other than doing quickview in the Finder before going to Pages.

    On Yosemite, Pages documents that are in a package (folder) format are viewable with Quick Look in the Pages v5.5.1 file chooser. Pages documents that are in the Single File (compressed, renamed folder) format are viewable in diminished size with Quick Look. Other documents that can be opened in the version(s) of Pages on your Mac will also open properly in Quick Look from the file chooser.

  • Full-screen (spacebar) preview quality testing

    [For background story, please read http://forums.adobe.com/thread/1056763 but be warned, it's very l-o-n-g!]
    In brief: some people have noted that Bridge full-screen (spacebar) previews (FSPs) don't accurately reflect the sharpness of a photograph. Sometimes this can be explained by individual configuration problems, but it's clear that this is a common issue amongst people using Bridge to assess/score photograph sharpness, without having to build/examine 100% previews for every image.
    [It's worth noting that one common reason why FSPs aren't very sharp is because the Bridge advanced preference "Generate Monitor-Size Previews" hasn't been ticked, as this produces a higher resolution image cache.  Another cause of very fuzzy previews is random and unexplained, but can usually be solved by restarting Bridge and/or clearing the cache for the selection.]
    This discussion concerns the lack of sharpness seen only in FSPs.  It can be described as "a subtle but significant loss of detail and sharpness, similar to a slightly out of focus photograph"; imagine a photo with a little bit of blur filter, or a Photoshop PSD at a non-standard zoom setting.  This "softening" of the image is caused by Bridge asking the graphics processor to resize the image cache to fit the display.  If you select the Bridge advanced preference "Use Software Rendering", you can improve a poor FSP slightly, at the expense of speed, by bypassing the graphics processor.
    The test
    Visit this web page and download the last image ("2362x3543 pixel, 4.5 Mb") to your computer.
    Browse to this image in Bridge, and view it full-screen by pressing Spacebar.  Take a screen capture, and save it as a TIFF or PSD.
    Adjust your slideshow settings (Ctrl/Cmd-Shift-L), picking "Scaled to Fill", then click on "Play".  Save the screen capture, as above.
    You now have two screen captures: one FSP, and one cache JPEG reference shot.  Examine them side by side at 100%, or layer them in Photoshop and use the hide layer button to flick between images.  Pay particular attention to the two left-hand photos, the sharpness check text, and the converging lines.
    Make a note of your computer's operating system, graphics processor and driver version, as well as your largest display's pixel dimensions.
    Post this information below, together with high quality (10) JPEGs of both screen captures, labelled FSP and REF, and any observations, so we can all see.

    OK, it usually takes me a while to let the penny drop, especially when it comes to maths...
    I also am busy with the transition of my new Mac pro but with al this here are my results. I include several screenshots but due to upload limit of 2 MB per image in here I downsized the original screenshots a lot, but hopefully it will be clear.
    For full screen screenshots I have the asked FSP and REF but also the 100% preview in Bridge with space bar and click. Don't know what your file size is but using EOS 1Dx with 18 MP CR2 files (converted to DNG) it does take me about 1,5 - 2 seconds for both loupe and FSP to build a 100 % preview, and I seem to recall this was not very different behavior on my previous (6 year old) Mac Pro.
    You are right (of course... :-) ) regarding the difference between FSP and REF, when studying closely there is a significant detail difference between the FSP and the REF. However, only the 100 % preview matches the original jpeg. The FSP file is on closer look not so good with details but the REF file is only slightly better, both are not correct and therefor the 100 % is still needed.
    Here is the FSP screenshot:
    and here the REF screenshot:
    also the 100 % preview in full screen screenshot:
    and finally a composed file with details from original, 100 % REF and FSP:
    As said before, at first sight I can't spot significant difference between all options and the full screen (as the preview panel HQ preview) let's me spot the vast majority of unsharpness issues, hence my multiple rounds of sorting and incases of doubt the 100 % option.
    So while your theory is correct I'm afraid I  (still) doubt the usefulness of this all. If neither the FSP and the REF (although the latter does show a bit better result) can match the results of the original but the 100 % does it well I don't see an easy solution for improvement.
    I agree with the quality from the screenshots Curt provided, but Curt also uses the embedded thumbnail instead of HQ preview option. Depending on his needs and hard ware availability it would be nice to see new results with the HQ and monitor sized previews options enabled.
    regards
    Omke

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

  • Rename a Jtree node directly & Popup Menu

    Pls assist with codes to rename a Jree node directly without using a dialog box or optionpane. I tried
    tree.startEditingAtPath(/* path of selected node*/);
    to go to edit mode and it does not work.
    II. Is it possible to attach different popmenu to the root, separate from the parent and child? Pls assist with code as the popupmenu i use at the moment shows up on the nodes(root, parent, leaf).
    I have benefiited greatly from questions asked and answers proferred at this forum and I use this opportunity to thank everyone greatly as I have migrated to Java based on all the materials sourced on the net.
    [email protected]

    public class AutomatedTreeMouseHandler extends MouseAdapter {
         public void mousePressed(MouseEvent e) {
              JTree tree = (JTree) (e.getSource());
              int x = e.getX();
              int y = e.getY();
              TreePath path = tree.getPathForLocation(x, y);
              if (path != null) {
                   // generate your popup here
    Dennis,
    are you saying that i have to define the popmenu for each category of node in the mouseadapter and att'd these to the tree depending on whether root, leaf or whatever type of node is selected?
    I will try this and revert.
    I can not make anything out of the reference giving with regard to renaming a node in edit mode.
    Pls provide more explanation and sample code, if necessary.
    Thanks a million.

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Problem in Jtree while retrieving values from a hashtable

    Hi
    I am trying to show some values in a Jtree.I am receiving the values in a hashtable.The hashtable contains unique key but duplicate values.i want to show that values of that hashtable in a tree(but unique values)and under each value show all the key of it.can you please tell me how to do that.
    thanks

    If i understand right, you want to do something like this:
                   Hashtable values = yourhashtable;        
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("Values");
              HashMap<Object, DefaultMutableTreeNode> nodes = new HashMap<Object, DefaultMutableTreeNode>();
              Iterator ii = values.keySet().iterator();
              while (ii.hasNext()) {
                   Object key = ii.next();
                   Object value = values.get(key);
                   if (nodes.containsKey(value)) {
                        DefaultMutableTreeNode node = nodes.get(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                   } else {
                        DefaultMutableTreeNode node = new DefaultMutableTreeNode(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                        nodes.put(value, node);
                        root.add(node);
              JTree tree = new JTree(root);Hope this helps,
    Alex.

  • My MacBook Pro keeps on randomly scrolling on webpages, putting several spaces when I don't press the spacebar and only sometimes makes a space when I press the spacebar. Why is it doing this? Do I have a virus?

    I am currently struggling to write this due to my very erratic spacebar. When I press it, it only creates a space about two thirds of the time. When I don't press it, it creates spaces, often several, in the middle of words.  This is incredibly annoying and time consuming when writing. If I'm on iTunes or DVD player, it means the media is constantly stopping and starting.
    When I am on webpages they will often scroll straight to the bottom, and when I try to scroll back up it won't allow me to and the screen will look like it's jumping, like my instruction for it to scroll up is fighting against an external instruction forcing it down. This 'fighting' effect is also seen with the spacebar issue when it makes several spaces and I press backspace to try and delete the spaces.
    I have a MacBook Pro bought in July 2012 using Mac OS X 10.7.5. I use ESET Cybersecurity, which hasn't identified any viruses. I have deleted all internet downloads that aren't from well-known websites, yet the problem persists. It has been happening on and off for about a week, during which time I have turned the computer on and off many times, though today it has been far worse than before. I am worried I have a virus, though can't seem to locate one.
    Please, if you can shed any light on the situation, please do! I'm not a techy person at all, so there may be a very obvious reason and solution for this, in which case I apologise for this waste of time. Still, any help would be very very appreciated, thank you!

    You are still under warranty.  Call Apple Care. Make sure you get a case number as all repairs have an additional 90 days of warranty. 
    #1 - You have 14 days from the date of purchase to return your computer with no questions asked.
    #2 - You have 90 days of FREE phone tech support.
    #3 - You have the standard one year Apple warranty.
    #4 - If you've purchased an AppleCare Protection Plan, your warranty last for 3 years.   You can obtain AppleCare anytime up to the first year of the purchase of your computer.
    Take FULL advantage of your warranty.  Posting on a message board should be done as a last resort and if you are out of warranty or Apple Care has expired.

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • Problem with JTree

    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
        private TreePanel treePanel;
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (treePanel = new TreePanel ());
            getContentPane ().add (new SearchPanel (), BorderLayout.SOUTH);
            pack ();
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public Dimension getPreferredSize () {
            return new Dimension (600, 600);
        private class TreePanel extends JPanel {
            private DefaultTreeModel model;
            private JTree tree;
            public TreePanel () {
                model = new DefaultTreeModel (createRoot ());
                tree = new JTree (model);
                tree.setRootVisible (false);
                tree.setShowsRootHandles (true);
                setLayout (new BorderLayout ());
                add (new JScrollPane (tree));
            private TreeNode createRoot () {
                DefaultMutableTreeNode root = new DefaultMutableTreeNode ("");
                add (root, 1, 3);
                return root;
            private void add (DefaultMutableTreeNode node, int i, int n) {
                for (int l = 0; l < 26; l ++) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode (((String) node.getUserObject ()) + (char) ('a' + l));
                    if (i < n) {
                        add (child, i + 1, n);
                    node.add (child);
            public void searchAndExpand (String text) {
                TreeNode[] path = search ((DefaultMutableTreeNode) model.getRoot (), text);
                if (path != null) {
                    TreePath treePath = new TreePath (path);
                    tree.scrollPathToVisible (treePath);
                    tree.setSelectionPath (treePath);
            private TreeNode[] search (DefaultMutableTreeNode node, Object object) {
                TreeNode[] path = null;
                if (node.getUserObject ().equals (object)) {
                    path = model.getPathToRoot (node);
                } else {
                    int i = 0;
                    int n = model.getChildCount (node);
                    while ((i < n) && (path == null)) {
                        path = search ((DefaultMutableTreeNode) model.getChild (node, i), object);
                        i ++;
                return path;
        private class SearchPanel extends JPanel {
            public SearchPanel () {
                JTextField searchField = new JTextField (10);
                searchField.addActionListener (new ActionListener () {
                    public void actionPerformed (ActionEvent event) {
                        treePanel.searchAndExpand (((JTextField) event.getSource ()).getText ());
                setLayout (new GridBagLayout ());
                add (searchField, new GridBagConstraints ());
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

Maybe you are looking for