Tree in awt

Hi
I wanted to use awt and there are 2 major features that i am looking for. Is it possible for me to implement those in awt and if yes can i get some examples on them
1) I need a collapsable tree structure on left pane - Do we have this tree component.
2) Is there a browser control that i can plugin. Or is there is facilty that i can plugin browser control that opens pdf. I need to open pdf in that ?
thanks

I'm afraid the answer are:
-No
-No
But you can do that with swing...

Similar Messages

  • Synchronization on awt component

    I was facing some deadlock issues on the awt component and trying to resolve the problems. I have searched using google and also in this forum but not much information that i can found. Anyone have some good article on sychonization on awt component ?
    By the way, I have some question on the synchronization issues on awt component. Questions as below :
    1. we should only synchronize out component by synchronized on getTreeLock() ? From what i know is that anything to do which layout and changing the structure of tree of awt component should synchronize the tree lock. Am i correct on this ?
    2. since paint() method only being execute by AWT-Thread (correct ?), the paint() method shouldn't be synchonized ? If I was refering to a lot of informations in my paint method when doing painting, how i can make sure those informations/data was synchronized ?
    3. It was recommended that any layout process of component should be done by AWT-Thread (Event Dispatching Thread) ? Currently my product have to compatible with jre 1.1. which invokeLater() only introduced in java 1.2. How can I layout my component in AWT-Thread ?

    Hi!
    Sorry to read that. Unfortunately, Firefox Sync is not a back up service and the information is stored in the servers only temporarily so the rest of your devices can get the information.

  • Urgent about AWT

    Dear all,
    I have two questions. I have to use only AWT to build a GUI for Presence service. (like Instant Messaging) and I need to draw a tree of all persons subscribed to (that's the most esthetic way)
    And i need to know if there is a way to build trees in AWT.
    Moreover I would like to know how to make a color translucent or opaque.
    Thanks for your help.
    Lamine.

    trees, i wouldn't know
    translucency/opacity, the term you need to search for is 'alpha value'. there should be something in the java2d package.
    cheers,
    lex

  • SOS: GUI - without JRE?

    Hi gurus,
    I'm rewriting a client side.of a chat system.
    It's written in Swing. I have a few questions:
    1.) Is it possible to write a Graphic User Interface (GUI)
    without the need for user to install Java Runtime Environment (JRE)?
    If it's possible how do I do it?
    [Through Internet Explorer's (IE) Virtual Machine (VM)? or simply rewrite the SWING into AWT?]
    2.) An programmer told me about a trick: wrap AWT arround SWING so that the SWING-code could run under AWT without any problems. Do you know how it works?
    I'm posting these question here because I couldn't find any useful information about it.
    All I found is VM specification, SWING, Applet with JRE. Everything require JRE.
    I don't see any way arround it.
    I believe some of you are smarter and maybe able to help me out. I'd apreciate everyhelp.
    Steven Ho

    Hi !
    1. no JRE or Java at all
    - You export the graphics. So The client machine draws olny the graphics, but it does not contain any code.
    2. Through Internet Explorer's (IE) Virtual Machine (VM):
    If it is a Java 1.1.8 Application, just add the swing package of the sun site to the classpath.
    I never tried this, so I can't say you how to do this.
    3. Using the Sun JavaPlugin.
    Just download it on the client machine.
    It contains the whole JDK 1.3 or JDK1.4 functionality, inclusive swing.
    4. wrap AWT arround SWING:
    I would not do this, because the functionality of AWT is a subset of SWING. For example you have no trees in AWT, like JTree. In order to this you can't wrap an "AWT Tree" to a JTree.
    Hope this helps,
    Witold.

  • Getting Image Bytes

    Hi
    I have a bit of a problem. I am receving an image from SOAP call, and the SOAP implementation is creating an object of type sun.awt.windows.WImage. The problem is I need to out put this to a webbrowser from the servlet it is executing in. I have never dealt much with this sort of front end stuff. Does anybody have any ideas?
    Do I need to get the objects stream of bytes.
    Thanks for this!
    A.

    Sounds like your implementation is violating a couple of rules of cleanliness. Last I checked, no one but Sun is supposed to use the sun.* packages.
    Any way about it, I checked the inheritance tree; sun.awt.windows.WImage, by and by, implements the java.awt.Image interface. So you can do anything with it that you can do with an Image.
    Hope that helps!

  • EXCEPTION_ACCESS_VIOLATION Library: awt.dll

    Hi to all! I've been searching in all the forums to try to find a fix or at least an explanation of an exception that I get, but until now I have not seen any answer, so... here it goes my problem:
    An unexpected exception has been detected in native code outside the VM.
    Unexpected Signal : EXCEPTION_ACCESS_VIOLATION occurred at PC=0x6D0238F7
    Function=Java_sun_java2d_loops_MaskFill_MaskFill+0x1F4C7
    Library=C:\Archivos de programa\Java\j2re1.4.1_01\bin\awt.dll
    Current Java thread:
         at sun.java2d.loops.Blit.Blit(Native Method)
         at sun.java2d.pipe.DrawImage.blitSurfaceData(DrawImage.java:658)
         at sun.java2d.pipe.DrawImage.renderSurfaceData(DrawImage.java:386)
         at sun.java2d.pipe.DrawImage.clipAndRenderSurfaceData(DrawImage.java:364)
         at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:66)
         at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:50)
         at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:749)
         at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2803)
         at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2793)
         at javax.swing.plaf.metal.MetalIconFactory$FolderIcon16.paintIcon(MetalIconFactory.java:1417)
         at javax.swing.plaf.basic.BasicLabelUI.paint(BasicLabelUI.java:152)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:541)
         at javax.swing.JComponent.paint(JComponent.java:808)
         at javax.swing.tree.DefaultTreeCellRenderer.paint(DefaultTreeCellRenderer.java:397)
         at javax.swing.CellRendererPane.paintComponent(CellRendererPane.java:134)
         at javax.swing.plaf.basic.BasicTreeUI.paintRow(BasicTreeUI.java:1380)
         at javax.swing.plaf.basic.BasicTreeUI.paint(BasicTreeUI.java:1171)
         at javax.swing.plaf.metal.MetalTreeUI.paint(MetalTreeUI.java:143)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:541)
         at javax.swing.JComponent.paint(JComponent.java:808)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         - locked <05C6CB78> (a java.awt.Component$AWTTreeLock)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JViewport.paint(JViewport.java:707)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         - locked <05C6CB78> (a java.awt.Component$AWTTreeLock)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         - locked <05C6CB78> (a java.awt.Component$AWTTreeLock)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         - locked <05C6CB78> (a java.awt.Component$AWTTreeLock)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JLayeredPane.paint(JLayeredPane.java:552)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         - locked <05C6CB78> (a java.awt.Component$AWTTreeLock)
         at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4778)
         at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)
         at javax.swing.JComponent.paint(JComponent.java:798)
         at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
         at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
         at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
         at java.awt.Container.paint(Container.java:1309)
         at sun.awt.RepaintArea.paint(RepaintArea.java:177)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:260)
         at java.awt.Component.dispatchEventImpl(Component.java:3658)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3439)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Dynamic libraries:
    0x00400000 - 0x00419000      C:\Archivos de programa\Internet Explorer\iexplore.exe
    0x77F40000 - 0x77FED000      C:\WINDOWS\System32\ntdll.dll
    0x77E40000 - 0x77F33000      C:\WINDOWS\system32\kernel32.dll
    0x77BE0000 - 0x77C33000      C:\WINDOWS\system32\msvcrt.dll
    0x77D10000 - 0x77D9C000      C:\WINDOWS\system32\USER32.dll
    0x77C40000 - 0x77C80000      C:\WINDOWS\system32\GDI32.dll
    0x77DA0000 - 0x77E3E000      C:\WINDOWS\system32\ADVAPI32.dll
    0x78000000 - 0x78086000      C:\WINDOWS\system32\RPCRT4.dll
    0x772A0000 - 0x77304000      C:\WINDOWS\system32\SHLWAPI.dll
    0x76980000 - 0x76ACA000      C:\WINDOWS\System32\SHDOCVW.dll
    0x78090000 - 0x78174000      C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.10.0_x-ww_f7fb5805\comctl32.dll
    0x773A0000 - 0x77BA1000      C:\WINDOWS\system32\SHELL32.dll
    0x77310000 - 0x7739B000      C:\WINDOWS\system32\comctl32.dll
    0x00900000 - 0x00A21000      C:\WINDOWS\system32\ole32.dll
    0x5B150000 - 0x5B184000      C:\WINDOWS\System32\uxtheme.dll
    0x75F30000 - 0x7602C000      C:\WINDOWS\System32\BROWSEUI.dll
    0x723D0000 - 0x723E3000      C:\WINDOWS\System32\browselc.dll
    0x75EF0000 - 0x75F0E000      C:\WINDOWS\system32\appHelp.dll
    0x76F90000 - 0x77008000      C:\WINDOWS\System32\CLBCATQ.DLL
    0x770F0000 - 0x7717B000      C:\WINDOWS\system32\OLEAUT32.dll
    0x77010000 - 0x770E0000      C:\WINDOWS\System32\COMRes.dll
    0x77BD0000 - 0x77BD7000      C:\WINDOWS\system32\VERSION.dll
    0x761B0000 - 0x76249000      C:\WINDOWS\system32\WININET.dll
    0x76270000 - 0x762FC000      C:\WINDOWS\system32\CRYPT32.dll
    0x76250000 - 0x7625F000      C:\WINDOWS\system32\MSASN1.dll
    0x76F50000 - 0x76F60000      C:\WINDOWS\System32\Secur32.dll
    0x765D0000 - 0x76620000      C:\WINDOWS\System32\cscui.dll
    0x765B0000 - 0x765CB000      C:\WINDOWS\System32\CSCDLL.dll
    0x76630000 - 0x7671B000      C:\WINDOWS\System32\SETUPAPI.dll
    0x10000000 - 0x1000B000      C:\Archivos de programa\Adobe\Acrobat 6.0\Reader\ActiveX\AcroIEHelper.dll
    0x00D50000 - 0x00D6C000      C:\Archivos de programa\Norton AntiVirus\NavShExt.dll
    0x00D70000 - 0x00D8A000      C:\WINDOWS\System32\ccTrust.dll
    0x76030000 - 0x76091000      C:\WINDOWS\System32\MSVCP60.dll
    0x76AE0000 - 0x76AF5000      C:\WINDOWS\System32\ATL.DLL
    0x760A0000 - 0x7611A000      C:\WINDOWS\system32\urlmon.dll
    0x76120000 - 0x761AC000      C:\WINDOWS\System32\shdoclc.dll
    0x74700000 - 0x7478F000      C:\WINDOWS\System32\mlang.dll
    0x71A50000 - 0x71A59000      C:\WINDOWS\System32\wsock32.dll
    0x71A30000 - 0x71A45000      C:\WINDOWS\System32\WS2_32.dll
    0x71A20000 - 0x71A28000      C:\WINDOWS\System32\WS2HELP.dll
    0x719D0000 - 0x71A0C000      C:\WINDOWS\system32\mswsock.dll
    0x71A10000 - 0x71A18000      C:\WINDOWS\System32\wshtcpip.dll
    0x76EA0000 - 0x76ED7000      C:\WINDOWS\System32\RASAPI32.DLL
    0x76E50000 - 0x76E61000      C:\WINDOWS\System32\rasman.dll
    0x71BC0000 - 0x71C0E000      C:\WINDOWS\System32\NETAPI32.dll
    0x76E70000 - 0x76E9B000      C:\WINDOWS\System32\TAPI32.dll
    0x76E40000 - 0x76E4D000      C:\WINDOWS\System32\rtutils.dll
    0x76B00000 - 0x76B2D000      C:\WINDOWS\System32\WINMM.dll
    0x72250000 - 0x72255000      C:\WINDOWS\System32\sensapi.dll
    0x01350000 - 0x01551000      C:\WINDOWS\System32\msi.dll
    0x75E40000 - 0x75EE8000      C:\WINDOWS\System32\SXS.DLL
    0x75A20000 - 0x75AC6000      C:\WINDOWS\system32\USERENV.dll
    0x76EE0000 - 0x76F05000      C:\WINDOWS\System32\DNSAPI.dll
    0x76F70000 - 0x76F77000      C:\WINDOWS\System32\winrnr.dll
    0x76F20000 - 0x76F4D000      C:\WINDOWS\system32\WLDAP32.dll
    0x76F80000 - 0x76F85000      C:\WINDOWS\System32\rasadhlp.dll
    0x747A0000 - 0x74A57000      C:\WINDOWS\System32\mshtml.dll
    0x513E0000 - 0x5140D000      C:\Archivos de programa\Archivos comunes\Microsoft Shared\VS7Debug\pdm.dll
    0x51300000 - 0x51328000      C:\Archivos de programa\Archivos comunes\Microsoft Shared\VS7Debug\msdbg2.dll
    0x74680000 - 0x746A6000      C:\WINDOWS\System32\msimtf.dll
    0x746B0000 - 0x746F4000      C:\WINDOWS\System32\MSCTF.dll
    0x74650000 - 0x74677000      C:\WINDOWS\System32\MSLS31.DLL
    0x76340000 - 0x7635C000      C:\WINDOWS\System32\IMM32.DLL
    0x32520000 - 0x32532000      C:\Archivos de programa\Microsoft Office\Office10\msohev.dll
    0x767B0000 - 0x767D4000      C:\WINDOWS\system32\schannel.dll
    0x020D0000 - 0x020EB000      C:\Archivos de programa\Archivos comunes\Symantec Shared\Script Blocking\scrauth.dll
    0x02200000 - 0x0221E000      C:\Archivos de programa\Archivos comunes\Symantec Shared\Script Blocking\ScrBlock.dll
    0x76BF0000 - 0x76C1B000      C:\WINDOWS\System32\wintrust.dll
    0x76C50000 - 0x76C72000      C:\WINDOWS\system32\IMAGEHLP.dll
    0x0FFD0000 - 0x0FFF3000      C:\WINDOWS\System32\rsaenh.dll
    0x73CD0000 - 0x73CE0000      C:\WINDOWS\System32\cryptnet.dll
    0x75C00000 - 0x75C91000      c:\windows\system32\jscript.dll
    0x74C40000 - 0x74CAF000      C:\WINDOWS\System32\mshtmled.dll
    0x72CA0000 - 0x72CA9000      C:\WINDOWS\System32\wdmaud.drv
    0x72C90000 - 0x72C98000      C:\WINDOWS\System32\msacm32.drv
    0x77BB0000 - 0x77BC4000      C:\WINDOWS\System32\MSACM32.dll
    0x02A80000 - 0x02A87000      C:\WINDOWS\System32\midimap.dll
    0x6D7E0000 - 0x6D7EF000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\npjpi141_01.dll
    0x6D740000 - 0x6D752000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\jpiexp32.dll
    0x6D780000 - 0x6D794000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\jpishare.dll
    0x6D330000 - 0x6D45A000      C:\ARCHIV~1\Java\J2RE14~1.1_0\bin\client\jvm.dll
    0x6D1D0000 - 0x6D1D7000      C:\ARCHIV~1\Java\J2RE14~1.1_0\bin\hpi.dll
    0x6D300000 - 0x6D30D000      C:\ARCHIV~1\Java\J2RE14~1.1_0\bin\verify.dll
    0x6D210000 - 0x6D229000      C:\ARCHIV~1\Java\J2RE14~1.1_0\bin\java.dll
    0x6D320000 - 0x6D32D000      C:\ARCHIV~1\Java\J2RE14~1.1_0\bin\zip.dll
    0x6D000000 - 0x6D0FB000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\awt.dll
    0x72F80000 - 0x72FA3000      C:\WINDOWS\System32\WINSPOOL.DRV
    0x6D180000 - 0x6D1D0000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\fontmanager.dll
    0x736E0000 - 0x73724000      C:\WINDOWS\System32\ddraw.dll
    0x73B40000 - 0x73B46000      C:\WINDOWS\System32\DCIMAN32.dll
    0x6DE20000 - 0x6DE91000      C:\WINDOWS\System32\D3DIM.DLL
    0x6D6E0000 - 0x6D6F1000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\jpicom32.dll
    0x6D2D0000 - 0x6D2DE000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\net.dll
    0x6D130000 - 0x6D152000      C:\Archivos de programa\Java\j2re1.4.1_01\bin\dcpr.dll
    0x6DA20000 - 0x6DA9D000      C:\WINDOWS\system32\DBGHELP.dll
    0x76BB0000 - 0x76BBB000      C:\WINDOWS\System32\PSAPI.DLL
    Local Time = Fri Dec 05 18:20:37 2003
    Elapsed Time = 161
    # The exception above was detected in native code outside the VM
    # Java VM: Java HotSpot(TM) Client VM (1.4.1_01-b01 mixed mode)
    Now let me tell you what I am doing. I have an applet which constructs a JTree with some leafs and parents. When I first load the applet (say coming from a link) it works perfectly, but if I reload the page then the application explodes! This is happening in Windows XP (SP1) with IE 6.0.2. The funny thing, is that I have tested in a lot of other Windows XP with the same configuration (software, not the same hardware) and all works perfectly! The PC where I'm getting the exception is a Compaq Evo laptop.
    If you have some idea of what is going on, or better than that, if you have an idea on how to fix this, please let me know.
    Feel fee to email me at:
    [email protected]

    I am also seeing this error but at UNIX. As soon as I invoke a call to the JTree constructor (TreeModel) , it explodes!! Can someone provide an clue?

  • How to resize a custom tree node like you would a JFrame window?

    Hello,
    I am trying to resize a custom tree node like you would a JFrame window.
    As with a JFrame, when your mouse crosses the Border, the cursor should change and you are able to drag the edge to resize the node.
    However, I am faced with a problem. Border cannot detect this and I dont want to use a mouse motion listener (with a large number of nodes, I fear it will be inefficient, calculating every node's position constantly).
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.util.EventObject;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeSelectionModel;
    public class ResizeNode extends JPanel {
           AnilTreeCellRenderer2 atcr;
           AnilTreeCellEditor2 atce;
           DefaultTreeModel treeModel;
           JTree tree;
           DefaultMutableTreeNode markedNode = null;
         public ResizeNode() {
                super(new BorderLayout());
                   treeModel = new DefaultTreeModel(null);
                   tree = new JTree(treeModel);          
                  tree.setEditable(true);
                   tree.getSelectionModel().setSelectionMode(
                             TreeSelectionModel.SINGLE_TREE_SELECTION);
                   tree.setShowsRootHandles(true);
                  tree.setCellRenderer(atcr = new AnilTreeCellRenderer2());
                  tree.setCellEditor(atce = new AnilTreeCellEditor2(tree, atcr));
                   JScrollPane scrollPane = new JScrollPane(tree);
                   add(scrollPane,BorderLayout.CENTER);
         public void setRootNode(DefaultMutableTreeNode node) {
              treeModel.setRoot(node);
              treeModel.reload();
           public static void main(String[] args){
                ResizeNode tb = new ResizeNode();
                tb.setPreferredSize(new Dimension(400,200));
                  JFrame frame = new JFrame("ResizeNode");
                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  frame.setContentPane(tb);
                  frame.setSize(400, 200);
                  frame.pack();
                  frame.setVisible(true);
                  tb.populate();
         private void populate() {
              TextAreaNode2 r = new TextAreaNode2(this);
               setRootNode(r);
               TextAreaNode2 a = new TextAreaNode2(this);
               treeModel.insertNodeInto(a, r, r.getChildCount());          
    class AnilTreeCellRenderer2 extends DefaultTreeCellRenderer{
    TreeBasic panel;
    DefaultMutableTreeNode currentNode;
      public AnilTreeCellRenderer2() {
         super();
    public Component getTreeCellRendererComponent
       (JTree tree, Object value, boolean selected, boolean expanded,
       boolean leaf, int row, boolean hasFocus){
         TextAreaNode2 currentNode = (TextAreaNode2)value;
         NodeGUI2 gNode = (NodeGUI2) currentNode.gNode;
        return gNode.box;
    class AnilTreeCellEditor2 extends DefaultTreeCellEditor{
      DefaultTreeCellRenderer rend;
      public AnilTreeCellEditor2(JTree tree, DefaultTreeCellRenderer r){
        super(tree, r);
        rend = r;
      public Component getTreeCellEditorComponent(JTree tree, Object value,
       boolean isSelected, boolean expanded, boolean leaf, int row){
        return rend.getTreeCellRendererComponent(tree, value, isSelected, expanded,
         leaf, row, true);
      public boolean isCellEditable(EventObject event){
        return true;
    class NodeGUI2 {
         final ResizeNode view;
         Box box = Box.createVerticalBox();
         final JTextArea aa = new JTextArea( 1, 5 );
         final JTextArea aaa = new JTextArea( 1, 8 );
         NodeGUI2( ResizeNode view_ ) {
              this.view = view_;
              box.add( aa );
              aa.setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, Color.GREEN ) );
              box.add( aaa );
              box.setBorder( BorderFactory.createMatteBorder( 5, 5, 5, 5, Color.CYAN ) );
         private Dimension getEditorPreferredSize() {
              Insets insets = box.getInsets();
              Dimension boxSize = box.getPreferredSize();
              Dimension aaSize = aa.getPreferredSize();
              Dimension aaaSize = aaa.getPreferredSize();
              int height = aaSize.height + aaaSize.height + insets.top + insets.bottom;
              int width = Math.max( aaSize.width, aaaSize.width );
              if ( width < boxSize.width )
                   width += insets.right + insets.left + 3;     // 3 for cursor
              return new Dimension( width, height );               
    class TextAreaNode2 extends DefaultMutableTreeNode {  
         NodeGUI2 gNode;
         TextAreaNode2(ResizeNode view_) {     
              gNode = new NodeGUI2(view_);
    }

    the node on the tree is only painted on using the
    renderer to do the painting work. A mouse listener
    has to be added to the tree, and when moved over an
    area, you have to determine if you are over the
    border and which direction to update the cursor and
    to know which way to resize when dragged. One of the
    BasicRootPaneUI has some code that can help determine
    that.Thanks for replying. What is your opinion on this alternative idea that I just had?
    I am wondering if it might be easier to have a toggle button in the node that you click when you want to resize the node. Then a mouse-down and dragging the mouse will resize the node. Mouse-up will reset the toggle button, and so will mouse down in an invalid area.
    Anil

  • How can I display the tooltip in a tree node?

    I implement a TreeCellRenderer and has already set the tooltiptext through the following code:
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                               boolean selected, boolean expanded,
                               boolean leaf, int row,
                                  boolean hasFocus) {
            Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
            if(Leaf.class.isInstance(userObject)) {
                    Leaf leaf = (Leaf)userObject;
                    setToolTipText(leaf.getString());
        }Why can't the tree display the tooltip when a move the mouse on the leaf of the tree?
    Thank you!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test3 extends JFrame {
    public Test3() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    JTree jt = new JTree() {
    public String getToolTipText(MouseEvent evt) {
    if (getRowForLocation(evt.getX(), evt.getY()) == -1)
    return null;
    TreePath curPath = getPathForLocation(evt.getX(),
    evt.getY());
    return curPath.getLastPathComponent().toString();
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    jt.setToolTipText("");
    setSize(400, 400);
    setVisible(true);
    public static void main(String[] args) { new Test3();
    }It sounds a solution. I use the following code and also can display the tooltip,but there's also a problem:
        mytree.setCellRenderer(new MyTreeCellRenderer());
        ToolTipManager.sharedInstance().registerComponent(mytree);the above code only effective when the function getTreeCellRendererComponent in MyTreeCellRenderer like the following:
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                               boolean selected, boolean expanded,
                               boolean leaf, int row,
                                  boolean hasFocus) {
         String  stringValue = tree.convertValueToText(value, selected,
                                expanded, leaf, row, hasFocus);
         setText(stringValue);
         setToolTipText(stringValue); //Tooltips used by the tree
         /* Set the icon of the node */
                         Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
         if(Device.class.isInstance(userObject)) {
             setIcon(deviceIcon);
         } else {
             setIcon(nullIcon);
             Business b = (Business)userObject;
         setFont(defaultFont);
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         this.hasFocus = hasFocus;
         if(selected) // && hasFocus)
             setForeground(Color.white);
         else
             setForeground(Color.black);
         return this;
        }but when the code is bellow,it displays nothing(Only the leaf node need tooltip):
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                               boolean selected, boolean expanded,
                               boolean leaf, int row,
                                  boolean hasFocus) {
         String  stringValue = tree.convertValueToText(value, selected,
                                expanded, leaf, row, hasFocus);
         setText(stringValue);
         //setToolTipText(stringValue); //Tooltips used by the tree
         /* Set the icon of the node */
                         Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
                         if(Device.class.isInstance(userObject)) {
             setIcon(deviceIcon);
         } else {
             setIcon(nullIcon);
             Business b = (Business)userObject;
             if(b.isShowOrder())
                 setToolTipText(b.getContaId());  // only some node need tooltip, not all  node
         setFont(defaultFont);
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         this.hasFocus = hasFocus;
         if(selected) // && hasFocus)
             setForeground(Color.white);
         else
             setForeground(Color.black);
         return this;
        }Anyone knows why?

  • Useful Code of the Day:  Hideable Tree Nodes

    Someone posted about how they could selectively hide tree nodes, and I already had this AbstractTreeModel class (which does some things DefaultTreeModel does and some it doesn't) and a concrete subclass for TreeNode objects, so I was thinking how one could do hideable nodes. So I came up with this solution.
    There's 4 classes here:
    - AbstractTreeModel is the base for the concrete TreeNodeTreeModel
    - TreeNodeTreeModel extends AbstractTreeModel to support TreeNodes (DefautlMutableTreeNode, etc.)
    - HideableMutableTreeNode which is a DefautlMutableTreeNode subclass which has a visible field (with is/set methods, of course).
    - HideableTreeModel is the hideable model which is a subclass of TreeNodeTreeModel.
    A HideableMutableTreeNode can be set invisible directly, but the tree still needs to be notified to update. So it's best to use the methods in HideableTreeModel which set a node's visibility which notify the tree of changes accordingly. Methods are also provided to check a full path's visibility or ensure a node including all parent nodes are visible.
    A HideableTreeModel can take any TreeNode class, it doesn't have to be all HideableMutableTreeNodes, but only HideableMutableTreeNodes can be made invisible, of course. Any other TreeNode type would just be considered visible.
    Hiding nodes works basically by making the tree think there's less nodes then there are. And to do this, the node counts and child index search just works by looping thru the parent's children. This has potential perfomance drawbacks of course, since one has to loop thru the node's children to get nodes every time. This could be alleviated by not supporting non-hideable nodes changing the internal maintenance of HideableMutableTreeNode contents. But I'll leave that to whoever really needs it. It shouldn't be a problem if there are are a relatively small set of child nodes in any given parent.
    Also, note that the root node in the model cannot be made invisible, cuz it'd be redundant since JTree can be set to hide the root node.
    // *** HideableTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>HideableTreeModel</code> is an <code>TreeNodeTreeModel</code>
    * implementation for <code>HideableMutableTreeNode</code> objects.  The
    * model can also take any other <code>javax.swing.tree.TreeNode</code>
    * objects. 
    public class HideableTreeModel extends TreeNodeTreeModel {
          * Creates a new <code>HideableTreeModel</code> object.
          * @param  root  the root node
         public HideableTreeModel(TreeNode root) {
              super(root);
          * Checks if the specified node is visible.  A node can only be
          * hidden if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this only test the visibility of the specified node, not
          * whether a parent node is visible.  Use <code>isPathToNodeVisible(Object)</code>
          * to check if the full path is visible. 
          * @param  node  the node
          * @param  true if the node is visible, else false
         public boolean isNodeVisible(Object node) {
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        return ((HideableMutableTreeNode)node).isVisible();
              return true;
          * Sets the specified node to be hidden.  A node can only be made hidden
          * if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility.  <br />
          * <br />
          * Note that this will not alter the visibility of any nodes in the
          * specified node's path to the root node.  Use
          * <code>ensurePathToNodeVisible(Object)</code> instead to make sure the
          * full path down to that node is visible.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility. 
          * @param  node  the node
          * @param  v     true for visible, false for hidden
          * @param  true if the node's visibility could actually change, else false
         public boolean setNodeVisible(Object node, boolean v) {
              // can't hide root
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        HideableMutableTreeNode n = (HideableMutableTreeNode)node;
                        // don't fix what ain't broke...
                        if(v != n.isVisible()) {
                             TreeNode parent = n.getParent();
                             if(v) {
                                  // need to get index after showing...
                                  n.setVisible(v);
                                  int index = getIndexOfChild(parent, n);
                                  super.nodeInserted(parent, n, index);
                             } else {
                                  // need to get index before hiding...
                                  int index = getIndexOfChild(parent, n);
                                  n.setVisible(v);
                                  super.nodeRemoved(parent, n, index);
                        return true;
              return false;
          * Checks if the specified node is visible and all nodes above it are
          * visible. 
          * @param  node  the node
          * @param  true if the path is visible, else false
         public boolean isPathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   if(!isNodeVisible(path)) {
                        return false;
              return true;
         * Sets the specified node and all nodes above it to be visible.
         * Note that this method will notify the tree to reflect any changes to
         * node visibility.
         * @param node the node
         public void ensurePathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   setNodeVisible(path[i], true);
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0, j = -1; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             j++;
                        if(j == index) {
                             return pc;
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              int count = 0;
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             count++;
              return count;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              int index = -1;
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   TreeNode c = (TreeNode)child;
                   if(isNodeVisible(c)) {
                        index = 0;
                        for(int i = 0; i < p.getChildCount(); i++) {
                             TreeNode pc = (TreeNode)p.getChildAt(i);
                             if(pc.equals(c)) {
                                  return index;
                             if(isNodeVisible(pc)) {
                                  index++;
              return index;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              HideableMutableTreeNode root = new HideableMutableTreeNode("root");
              root.add(new HideableMutableTreeNode("child_1"));
              final HideableMutableTreeNode c2 = new HideableMutableTreeNode("child_2");
              c2.setVisible(false);
              final HideableMutableTreeNode c2a = new HideableMutableTreeNode("child_2_A");
              c2.add(c2a);
              c2.add(new HideableMutableTreeNode("child_2_B"));
              root.add(c2);
              HideableMutableTreeNode c3 = new HideableMutableTreeNode("child_3");
              HideableMutableTreeNode cC = new HideableMutableTreeNode("child_3_C");
              cC.setVisible(false);
              c3.add(cC);
              c3.add(new HideableMutableTreeNode("child_3_D"));
              root.add(c3);
              root.add(new HideableMutableTreeNode("child_4"));
              root.add(new HideableMutableTreeNode("child_5"));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode("child_6");
              c6.add(new DefaultMutableTreeNode("child_6_A"));
              c6.add(new DefaultMutableTreeNode("child_6_B"));
              root.add(c6);
              final HideableTreeModel model = new HideableTreeModel(root);
              JTree tree = new JTree(model);
              f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
              JButton b = new JButton("toggle");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.setNodeVisible(c2, !model.isNodeVisible(c2));
                        //model.ensurePathToNodeVisible(c2a);
              f.getContentPane().add(b, BorderLayout.SOUTH);
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** HideableMutableTreeNode ***
    import javax.swing.*;
    import javax.swing.tree.*;
    * <code>HideableMutableTreeNode</code> is a <code>DefaultMutableTreeNode</code>
    * implementation that works with <code>HideableTreeModel</code>.
    public class HideableMutableTreeNode extends DefaultMutableTreeNode {
         * The node is visible flag.
         public boolean visible = true;
         * Creates a tree node that has no parent and no children, but which
         * allows children.
         public HideableMutableTreeNode() {
              super();
         * Creates a tree node with no parent, no children, but which allows
         * children, and initializes it with the specified user object.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         public HideableMutableTreeNode(Object userObject) {
              super(userObject);
         * Creates a tree node with no parent, no children, initialized with the
         * specified user object, and that allows children only if specified.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         * @param allowsChildren - if true, the node is allowed to have child
         * nodes -- otherwise, it is always a leaf node
         public HideableMutableTreeNode(Object userObject, boolean allowsChildren) {
              super(userObject, allowsChildren);
         * Checks if the node is visible.
         * @return true if the node is visible, else false
         public boolean isVisible() {
              return this.visible;
         * Sets if the node is visible.
         * @param v true if the node is visible, else false
         public void setVisible(boolean v) {
              this.visible = v;
    // *** TreeNodeTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>TreeNodeTreeModel</code> is an <code>AbstractTreeModel</code>
    * implementation for <code>javax.swing.tree.TreeNode</code> objects.
    public class TreeNodeTreeModel extends AbstractTreeModel {
         * Creates a new <code>TreeNodeTreeModel</code> object.
         * @param root the root node
         public TreeNodeTreeModel(TreeNode root) {
              super();
              setRoot(root);
         * Returns the parent of the child node.
         * @param node the child node
         * @return the parent or null if root
         public Object getParent(Object node) {
              if(node != getRoot() && (node instanceof TreeNode)) {
                   return ((TreeNode)node).getParent();
              return null;
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildAt(index);
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildCount();
              return 0;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   return ((TreeNode)parent).getIndex((TreeNode)child);
              return -1;
         * Returns true if node is a leaf.
         * @param node the node
         * @return true if the node is a leaf
         public boolean isLeaf(Object node) {
              if(node instanceof TreeNode) {
                   return ((TreeNode)node).isLeaf();
              return true;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
              root.add(new DefaultMutableTreeNode("child_1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("child_2");
              c2.add(new DefaultMutableTreeNode("child_2_A"));
              c2.add(new DefaultMutableTreeNode("child_2_B"));
              root.add(c2);
              root.add(new DefaultMutableTreeNode("child_3"));
              root.add(new DefaultMutableTreeNode("child_4"));
              JTree tree = new JTree(new TreeNodeTreeModel(root));
              f.getContentPane().add(new JScrollPane(tree));
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** AbstractTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public abstract class AbstractTreeModel implements TreeModel {
         * The list of tree model listeners.
         private Vector modelListeners = new Vector();
         * The root object of the tree.
         private Object root = null;
         * Basic no-op constructor.
         public AbstractTreeModel() {
         * Gets the root object of the tree.
         * @return the root object
         public Object getRoot() {
              return this.root;
         * Sets the root object of the tree.
         * @param r the root object
         protected void setRoot(Object r) {
              this.root = r;
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @return the path to the object or <CODE>null</CODE>
         public Object[] getPathToRoot(Object node) {
              return getPathToRoot(node, 0);
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @param i the current index
         * @return the path to the object or <CODE>null</CODE>
         private Object[] getPathToRoot(Object node, int i) {
              Object anode[];
              if(node == null) {
                   if(i == 0) {
                        return null;
                   anode = new Object[i];
              } else {
                   i++;
                   if(node == getRoot()) {
                        anode = new Object[i];
                   } else {
                        anode = getPathToRoot(getParent(node), i);
                   anode[anode.length - i] = node;
              return anode;
         * Gets the parent object of the specified object. This method is not
         * part of the <code>javax.swing.tree.TreeModel</code> interface, but is
         * required to support the <code>getPathToRoot(Object)</code> method,
         * which is widely used in this class. Therefore, it is important to
         * correctly implement this method.
         * @param obj the object
         * @parma the parent object or null if no parent or invalid object
         protected abstract Object getParent(Object obj);
         * Adds a listener for the <CODE>TreeModelEvent</CODE> posted after the
         * tree changes.
         * @param l the tree model listener
         public void addTreeModelListener(TreeModelListener l) {
              modelListeners.addElement(l);
         * Removes a listener previously added with addTreeModelListener().
         * @param l the tree model listener
         public void removeTreeModelListener(TreeModelListener l) {
              modelListeners.removeElement(l);
         * Forces the tree to reload. This is useful when many changes occur
         * under the root node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed. To maintain
         * the expanded nodes, see the <code>getExpandedPaths(JTree)</code>
         * and <code>expandPaths(JTree, ArrayList)</code> methods.
         * @see #getExpandedPaths(JTree)
         * @see #expandPaths(JTree, ArrayList)
         public void reload() {
              reload(getRoot());
         * Forces the tree to repaint. This is useful when many changes occur
         * under a specific node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed below the
         * updated node.
         * @param node the node that changed
         public void reload(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeStructureChanged(new TreeModelEvent(this, tp));
         * Messaged when the user has altered the value for the item identified
         * by <CODE>path</CODE> to <CODE>newValue</CODE>.
         * @param path the path to the changed object
         * @param newValue the new value
         public void valueForPathChanged(TreePath path, Object newValue) {
              nodeChanged(path.getLastPathComponent());
         * Notifies the tree that nodes were inserted. The index is looked up
         * automatically.
         * @param node the parent node
         * @param child the inserted child node
         public void nodeInserted(Object node, Object child) {
              nodeInserted(node, child, -1);
         * Notifies the tree that nodes were inserted.
         * @param node the parent node
         * @param child the inserted child node
         * @param index the index of the child
         public void nodeInserted(Object node, Object child, int index) {
              if(index < 0) {
                   index = getIndexOfChild(node, child);
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that nodes were removed. The index is required
         * since by this point, the object will no longer be in the tree.
         * @param node the parent node
         * @param child the removed child node
         * @param index the index of the child
         public void nodeRemoved(Object node, Object child, int index) {
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesRemoved(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that a node was changed.
         * @param node the changed node
         public void nodeChanged(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null));
         * Fires "tree nodes changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesChanged(event);
         * Fires "tree nodes inserted" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesInserted(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesInserted(event);
         * Fires "tree nodes removed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesRemoved(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesRemoved(event);
         * Fires "tree structure changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeStructureChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeStructureChanged(event);
         * Records the list of currently expanded paths in the specified tree.
         * This method is meant to be called before calling the
         * <code>reload()</code> methods to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public ArrayList getExpandedPaths(JTree tree) {
              ArrayList expandedPaths = new ArrayList();
              addExpandedPaths(tree, tree.getPathForRow(0), expandedPaths);
              return expandedPaths;
         * Adds the expanded descendants of the specifed path in the specified
         * tree to the internal expanded list.
         * @param tree the tree
         * @param path the path
         * @param pathlist the list of expanded paths
         private void addExpandedPaths(JTree tree, TreePath path, ArrayList pathlist) {
              Enumeration enum = tree.getExpandedDescendants(path);
              while(enum.hasMoreElements()) {
                   TreePath tp = (TreePath)enum.nextElement();
                   pathlist.add(tp);
                   addExpandedPaths(tree, tp, pathlist);
         * Re-expands the expanded paths in the specified tree. This method is
         * meant to be called before calling the <code>reload()</code> methods
         * to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public void expandPaths(JTree tree, ArrayList pathlist) {
              for(int i = 0; i < pathlist.size(); i++) {
                   tree.expandPath((TreePath)pathlist.get(i));

    Hey
    I'm not trying to show anyone up here, but having just built a tree model for displaying an XML document in a tree, I thought this seemed like a neat exercise.
    I implemented this very differently from the @OP. I only have one class, HiddenNodeTreeModel. All the hidden node data is stored in the model itself in my class. The advantage of what I've created is it will work with any TreeModel. The disadvantage is that I think it's not going to be very scalable - the additional computing to get the number of child nodes and to adjust indexes is heavy. So if you need a scalable solution definitely don't use this.
    Anyway here you go
    HiddenNodeTreeModel.java
    ======================
    package tjacobs.ui.tree;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import tjacobs.ui.WindowUtilities;
    public class HiddenNodeTreeModel implements TreeModel {
         TreeModel mModel;
         ArrayList<Object> mHidden = new ArrayList<Object>();
         public HiddenNodeTreeModel (TreeModel model) {
              mModel = model;
         public void addTreeModelListener(TreeModelListener arg0) {
              mModel.addTreeModelListener(arg0);
         private ArrayList<Integer> getHiddenChildren(Object parent) {
              ArrayList<Integer> spots = new ArrayList<Integer>();
              Iterator _i = mHidden.iterator();
              while (_i.hasNext()) {
                   Object hidden = _i.next();
                   int idx = mModel.getIndexOfChild(parent, hidden);
                   if (idx != -1) {
                        spots.add(idx);
              return spots;
         public Object getChild(Object arg0, int index) {
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        index++;
              return mModel.getChild(arg0, index);
         public int getChildCount(Object arg0) {
              ArrayList list = getHiddenChildren(arg0);
              System.out.println("size = " + list.size());
              return mModel.getChildCount(arg0) - list.size();
         public int getIndexOfChild(Object arg0, Object arg1) {
              int index = mModel.getIndexOfChild(arg0, arg1);
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              int toSub = 0;
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        toSub++;
              return index - toSub;
         public Object getRoot() {
              // TODO Auto-generated method stub
              return mModel.getRoot();
         public boolean isLeaf(Object arg0) {
              // TODO Auto-generated method stub
              return mModel.isLeaf(arg0);
         public void removeTreeModelListener(TreeModelListener arg0) {
              mModel.removeTreeModelListener(arg0);
         public void valueForPathChanged(TreePath arg0, Object arg1) {
              mModel.valueForPathChanged(arg0, arg1);
         public void hideNode(Object node) {
              if (node instanceof TreePath) {
                   node = ((TreePath)node).getLastPathComponent();
              mHidden.add(node);
         public void showNode(Object node) {
              mHidden.remove(node);
         public void showAll() {
              mHidden.clear();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              DefaultMutableTreeNode A = new DefaultMutableTreeNode("A");
              DefaultMutableTreeNode B = new DefaultMutableTreeNode("B");
              DefaultMutableTreeNode C = new DefaultMutableTreeNode("C");
              DefaultMutableTreeNode D = new DefaultMutableTreeNode("D");
              DefaultMutableTreeNode E = new DefaultMutableTreeNode("E");
              DefaultMutableTreeNode F = new DefaultMutableTreeNode("F");
              A.add(B);
              B.add(C);
              B.add(D);
              B.add(E);
              E.add(F);
              DefaultTreeModel model = new DefaultTreeModel(A);
              final HiddenNodeTreeModel hmodel = new HiddenNodeTreeModel(model);
              final JTree tree = new JTree(hmodel);
              JFrame jf = new JFrame("HiddenNodeTreeModel Test");
              jf.add(tree);
              JMenuBar bar = new JMenuBar();
              jf.setJMenuBar(bar);
              JMenu menu = new JMenu("Options");
              bar.add(menu);
              final JMenuItem hide = new JMenuItem("Hide");
              final JMenuItem show = new JMenuItem("ShowAll");
              menu.add(hide);
              menu.add(show);
              ActionListener al = new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        if (ae.getSource() == hide) {
                             hmodel.hideNode(tree.getSelectionPath());
                             tree.updateUI();
                        else {
                             hmodel.showAll();
                             tree.updateUI();
              hide.addActionListener(al);
              show.addActionListener(al);
              jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf.setBounds(100,100,100,100);
              jf.setVisible(true);
    }

  • About to use my tree for firewood

    I was wondering if someone could maybe clue me into a problem that I am having with my DefaultMutableTree. See, I call a recursive method to get the file system of the computer, which is what is added to the tree. So the user is looking at a tree structure of the file system of their computer. My problem is that when I compile and run my program the tree shows up fine, with no hitches. I have given my code to other friends, and for some of them it does not show up, and throws a null pointer exception at the internal interface of this recursive method. I was wondering what might be causing this? My friends that have problems with the code are running either WIN XP, or Mac OS 10.1.4. Here is the code for the initialization of the tree (This will look ugly on the post, so I would hope that you would take the time to copy and paste this into your editor :D)
    //code start.
    import java.io.*;
    import java.io.File;
    import java.lang.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.beans.*;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.TreeSelectionModel;
    public class File_Encryptor extends JFrame {
    private JFrame thisFrame = this;
              private JTree tree;
    private JMenuBar jMenuBar1 = new JMenuBar();
              private JMenuItem menuOpen = new JMenuItem("Open");
              private JMenuItem menuSave = new JMenuItem("Save");
              private JMenuItem menuClose = new JMenuItem("Close");
              private JMenuItem menuQuit = new JMenuItem("Quit");
              private JMenuItem menuAbout = new JMenuItem("About this software...");
              private JMenuItem menuAdd = new JMenuItem("Add key and user");
              private JMenuItem menuChange = new JMenuItem("Change buddy key");
              private JMenuItem menuSend = new JMenuItem("Send your buddy key");
              private JMenuItem menuDelete = new JMenuItem("Delete selected buddy key");
              private JMenuItem menuReset = new JMenuItem("Reset your key");
              private JMenuItem menuChangeLogin = new JMenuItem("Change Login");
              private JMenuItem menuHelp = new JMenuItem("Help...");
              private JButton openDir = new JButton("Open path");
              private JTextField jTextField1 = new JTextField();
              private JScrollPane treeView;
              private JScrollPane imageView;
              private JScrollPane textView;
              private String ROOT;
              private File root;
              private DefaultMutableTreeNode top;
              final private DefaultMutableTreeNode FILLER = new DefaultMutableTreeNode(new FileInfo ("about:blank", "about:blank"));
         public File_Encryptor() throws FileNotFoundException, InterruptedException, IOException, ClassNotFoundException {
    super("FILE ENCRYPTOR 1.0");
                   addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                   ROOT = getRoot(System.getProperty("user.home"));
                   root = new File(ROOT);                    
                   try{
                   //Create the nodes.
                   top = unfold(root);
                   top.setUserObject(new FileInfo(ROOT,ROOT));
                   tree = new JTree(top);
                   tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
                   Object nodage = top.getNextNode().getUserObject();
                   FileInfo leaf = (FileInfo) nodage;
                   tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
    tree.getLastSelectedPathComponent();
    if (node == null) return;
              try{
                        Object nodeInfo = node.getUserObject();
                        FileInfo temp = (FileInfo) nodeInfo;
                        if((node.isLeaf()) && (!(node.isRoot())))
                             System.out.println(temp.Path());
                             //figure out how to place file in editor pane.
                        else
                             return;
                   catch(Exception fubar)
                        fubar.printStackTrace();
                   treeView = new JScrollPane(tree);
                   treeView.setSize(150,450);
                   jTextField1.setMaximumSize(new Dimension(50, 100));
                   jTextField1.setText("PATH");
                   this.getContentPane().add(jTextField1, BorderLayout.EAST);
                   this.getContentPane().add(treeView, BorderLayout.WEST);
    catch(Exception e) {
    e.printStackTrace();
                   jMenuBar1.setBorder(BorderFactory.createEtchedBorder());
                   JMenu menu = new JMenu("File");
                   JMenu about = new JMenu("Help");
                   JMenu keys = new JMenu("Keys");
                   JMenu change = new JMenu("Login");
                   menuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.META_MASK));
                   menuQuit.setEnabled(true);
                   menuQuit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             System.exit(0);
                   menu.add(menuQuit);
                   jMenuBar1.add(menu);
                   jMenuBar1.add(keys);
                   jMenuBar1.add(change);
                   jMenuBar1.add(about);
                   this.setJMenuBar(jMenuBar1);
              public class FileInfo {
              private String path = "";
              private String name = "";
              public FileInfo(String p , String n){
                   path = p;
                   name = n;
              public String toString(){
                   return name;
              public String Path(){
                   return path;
              public static String getFileEx(String po){
              String ext = "";
              int i = po.lastIndexOf('.');
              if(i > 0)
                   ext = po.substring(i-1);
              else
                   ext = null;
              return ext;
              private DefaultMutableTreeNode unfold(File path) {
                   DefaultMutableTreeNode node = new DefaultMutableTreeNode("");
                   Vector Files = new Vector();
                   Vector Direc = new Vector();
                   if((path.isDirectory()) && (path.list().length != 0))
                        node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
                        File [] childs = path.listFiles();
                        for(int j = 0; j < childs.length; j++)
                             if(childs[j].isDirectory())
                                  Direc.addElement(childs[j]);
                             else
                                  Files.addElement(childs[j]);
                        for(int g = 0; g < Files.size(); g++)
                             Direc.addElement((File)Files.elementAt(g));
                        for(int i = 0; i < Direc.size(); i++)
                             node.add(unfold((File)Direc.elementAt(i)));
                   else if(!(path.isDirectory()))
                        node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
                   else
                        node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
                        node.add(new DefaultMutableTreeNode(new FileInfo(null,"<EMPTY FOLDER>")));
                   return node;
              public static String getRoot(String path)
                   int find = path.indexOf(System.getProperty("file.separator"));
                   String root = path.substring(0,find + 1);
                   return root;
    public static void main( String [ ] args )throws FileNotFoundException, InterruptedException, IOException, ClassNotFoundException {
    File_Encryptor show = new File_Encryptor();
    show.setSize(700, 500);
    show.setResizable(false);
    //show.setLocation(100,100);
    show.setVisible(true);
    //code end.
    //well there it is. Hope someone can help me with my problem.
    //I know this code is ugly, but I was trying a bunch of different
    //things hoping something would work. but ehh no such luck.
    //I am running windows 98, yea that's prolly my problem.
    //thank you for your time.

    This will make the code less ugly.
    > //code start.
    import java.io.*;
    import java.io.File;
    import java.lang.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.beans.*;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.TreeSelectionModel;
    public class File_Encryptor extends JFrame {
    private JFrame thisFrame = this;
              private JTree tree;
    private JMenuBar jMenuBar1 = new JMenuBar();
              private JMenuItem menuOpen = new JMenuItem("Open");
              private JMenuItem menuSave = new JMenuItem("Save");
    private JMenuItem menuClose = new
    w JMenuItem("Close");
              private JMenuItem menuQuit = new JMenuItem("Quit");
    private JMenuItem menuAbout = new JMenuItem("About this software...");
    private JMenuItem menuAdd = new JMenuItem("Add key and user");
    private JMenuItem menuChange = new JMenuItem("Change buddy key");
    private JMenuItem menuSend = new JMenuItem("Send your buddy key");
    private JMenuItem menuDelete = new JMenuItem("Delete selected buddy key");
    private JMenuItem menuReset = new JMenuItem("Reset your key");
    private JMenuItem menuChangeLogin = new
    w JMenuItem("Change Login");
    private JMenuItem menuHelp = new
    w JMenuItem("Help...");
              private JButton openDir = new JButton("Open path");
              private JTextField jTextField1 = new JTextField();
              private JScrollPane treeView;
              private JScrollPane imageView;
              private JScrollPane textView;
              private String ROOT;
              private File root;
              private DefaultMutableTreeNode top;
    final private DefaultMutableTreeNode FILLER = new
    w DefaultMutableTreeNode(new FileInfo ("about:blank",
    "about:blank"));
    public File_Encryptor() throws FileNotFoundException,
    InterruptedException, IOException,
    ClassNotFoundException {
    super("FILE ENCRYPTOR 1.0");
                   addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e)
    dowEvent e) {
                        System.exit(0);
                   ROOT = getRoot(System.getProperty("user.home"));
                   root = new File(ROOT);                    
                   try{
                   //Create the nodes.
                   top = unfold(root);
                   top.setUserObject(new FileInfo(ROOT,ROOT));
                   tree = new JTree(top);
                   tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
                   Object nodage = top.getNextNode().getUserObject();
                   FileInfo leaf = (FileInfo) nodage;
    tree.addTreeSelectionListener(new
    ew TreeSelectionListener() {
    public void
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node =
    TreeNode node = (DefaultMutableTreeNode)
    tree.getLastSelectedPathComponent();
    if (node == null) return;
              try{
                        Object nodeInfo = node.getUserObject();
                        FileInfo temp = (FileInfo) nodeInfo;
                        if((node.isLeaf()) && (!(node.isRoot())))
                             System.out.println(temp.Path());
                             //figure out how to place file in editor pane.
                        else
                             return;
                   catch(Exception fubar)
                        fubar.printStackTrace();
                   treeView = new JScrollPane(tree);
                   treeView.setSize(150,450);
    jTextField1.setMaximumSize(new Dimension(50,
    0, 100));
                   jTextField1.setText("PATH");
    this.getContentPane().add(jTextField1,
    1, BorderLayout.EAST);
    this.getContentPane().add(treeView,
    w, BorderLayout.WEST);
    catch(Exception e) {
    e.printStackTrace();
                   jMenuBar1.setBorder(BorderFactory.createEtchedBorder
                   JMenu menu = new JMenu("File");
                   JMenu about = new JMenu("Help");
                   JMenu keys = new JMenu("Keys");
                   JMenu change = new JMenu("Login");
                   menuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEv
    nt.VK_Q, ActionEvent.META_MASK));
                   menuQuit.setEnabled(true);
                   menuQuit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             System.exit(0);
                   menu.add(menuQuit);
                   jMenuBar1.add(menu);
                   jMenuBar1.add(keys);
                   jMenuBar1.add(change);
                   jMenuBar1.add(about);
                   this.setJMenuBar(jMenuBar1);
              public class FileInfo {
              private String path = "";
              private String name = "";
              public FileInfo(String p , String n){
                   path = p;
                   name = n;
              public String toString(){
                   return name;
              public String Path(){
                   return path;
              public static String getFileEx(String po){
              String ext = "";
              int i = po.lastIndexOf('.');
              if(i > 0)
                   ext = po.substring(i-1);
              else
                   ext = null;
              return ext;
              private DefaultMutableTreeNode unfold(File path) {
    DefaultMutableTreeNode node = new
    ew DefaultMutableTreeNode("");
                   Vector Files = new Vector();
                   Vector Direc = new Vector();
    if((path.isDirectory()) && (path.list().length !=
    != 0))
    node = new DefaultMutableTreeNode(new
    new FileInfo(path.getPath(),path.getName()));
                        File [] childs = path.listFiles();
                        for(int j = 0; j < childs.length; j++)
                             if(childs[j].isDirectory())
                                  Direc.addElement(childs[j]);
                             else
                                  Files.addElement(childs[j]);
                        for(int g = 0; g < Files.size(); g++)
                             Direc.addElement((File)Files.elementAt(g));
                        for(int i = 0; i < Direc.size(); i++)
                             node.add(unfold((File)Direc.elementAt(i)));
                   else if(!(path.isDirectory()))
    node = new DefaultMutableTreeNode(new
    new FileInfo(path.getPath(),path.getName()));
                   else
    node = new DefaultMutableTreeNode(new
    new FileInfo(path.getPath(),path.getName()));
    node.add(new DefaultMutableTreeNode(new
    new FileInfo(null,"<EMPTY FOLDER>")));
                   return node;
              public static String getRoot(String path)
    int find =
    =
    path.indexOf(System.getProperty("file.separator"));
                   String root = path.substring(0,find + 1);
                   return root;
    public static void main( String [ ] args
    ] args )throws FileNotFoundException,
    InterruptedException, IOException,
    ClassNotFoundException {
    File_Encryptor show = new
    show = new File_Encryptor();
    show.setSize(700, 500);
    show.setResizable(false);
    //show.setLocation(100,100);
    show.setVisible(true);
    //code end.

  • About to use my tree for some firewood  :o(

    I was wondering if someone could maybe clue me into a problem that I am having with my DefaultMutableTree. See, I call a recursive method to get the file system of the computer, which is what is added to the tree. So the user is looking at a tree structure of the file system of their computer. My problem is that when I compile and run my program the tree shows up fine, with no hitches. I have given my code to other friends, and for some of them it does not show up, and throws a null pointer exception at the internal interface of this recursive method. I was wondering what might be causing this? My friends that have problems with the code are running either WIN XP, or Mac OS 10.1.4. Here is the code for the initialization of the tree (This will look ugly on the post, so I would hope that you would take the time to copy and paste this into your editor :D)
    //code start.
    import java.io.*;
    import java.io.File;
    import java.lang.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.beans.*;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.TreeSelectionModel;
    public class File_Encryptor extends JFrame {
    private JFrame thisFrame = this;
    private JTree tree;
    private JMenuBar jMenuBar1 = new JMenuBar();
    private JMenuItem menuOpen = new JMenuItem("Open");
    private JMenuItem menuSave = new JMenuItem("Save");
    private JMenuItem menuClose = new JMenuItem("Close");
    private JMenuItem menuQuit = new JMenuItem("Quit");
    private JMenuItem menuAbout = new JMenuItem("About this software...");
    private JMenuItem menuAdd = new JMenuItem("Add key and user");
    private JMenuItem menuChange = new JMenuItem("Change buddy key");
    private JMenuItem menuSend = new JMenuItem("Send your buddy key");
    private JMenuItem menuDelete = new JMenuItem("Delete selected buddy key");
    private JMenuItem menuReset = new JMenuItem("Reset your key");
    private JMenuItem menuChangeLogin = new JMenuItem("Change Login");
    private JMenuItem menuHelp = new JMenuItem("Help...");
    private JButton openDir = new JButton("Open path");
    private JTextField jTextField1 = new JTextField();
    private JScrollPane treeView;
    private JScrollPane imageView;
    private JScrollPane textView;
    private String ROOT;
    private File root;
    private DefaultMutableTreeNode top;
    final private DefaultMutableTreeNode FILLER = new DefaultMutableTreeNode(new FileInfo ("about:blank", "about:blank"));
    public File_Encryptor() throws FileNotFoundException, InterruptedException, IOException, ClassNotFoundException {
    super("FILE ENCRYPTOR 1.0");
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    ROOT = getRoot(System.getProperty("user.home"));
    root = new File(ROOT);
    try{
    //Create the nodes.
    top = unfold(root);
    top.setUserObject(new FileInfo(ROOT,ROOT));
    tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
    Object nodage = top.getNextNode().getUserObject();
    FileInfo leaf = (FileInfo) nodage;
    tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
    tree.getLastSelectedPathComponent();
    if (node == null) return;
    try{
    Object nodeInfo = node.getUserObject();
    FileInfo temp = (FileInfo) nodeInfo;
    if((node.isLeaf()) && (!(node.isRoot())))
    System.out.println(temp.Path());
    //figure out how to place file in editor pane.
    else
    return;
    catch(Exception fubar)
    fubar.printStackTrace();
    treeView = new JScrollPane(tree);
    treeView.setSize(150,450);
    jTextField1.setMaximumSize(new Dimension(50, 100));
    jTextField1.setText("PATH");
    this.getContentPane().add(jTextField1, BorderLayout.EAST);
    this.getContentPane().add(treeView, BorderLayout.WEST);
    catch(Exception e) {
    e.printStackTrace();
    jMenuBar1.setBorder(BorderFactory.createEtchedBorder());
    JMenu menu = new JMenu("File");
    JMenu about = new JMenu("Help");
    JMenu keys = new JMenu("Keys");
    JMenu change = new JMenu("Login");
    menuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.META_MASK));
    menuQuit.setEnabled(true);
    menuQuit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    menu.add(menuQuit);
    jMenuBar1.add(menu);
    jMenuBar1.add(keys);
    jMenuBar1.add(change);
    jMenuBar1.add(about);
    this.setJMenuBar(jMenuBar1);
    public class FileInfo {
    private String path = "";
    private String name = "";
    public FileInfo(String p , String n){
    path = p;
    name = n;
    public String toString(){
    return name;
    public String Path(){
    return path;
    public static String getFileEx(String po){
    String ext = "";
    int i = po.lastIndexOf('.');
    if(i > 0)
    ext = po.substring(i-1);
    else
    ext = null;
    return ext;
    private DefaultMutableTreeNode unfold(File path) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode("");
    Vector Files = new Vector();
    Vector Direc = new Vector();
    if((path.isDirectory()) && (path.list().length != 0))
    node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
    File [] childs = path.listFiles();
    for(int j = 0; j < childs.length; j++)
    if(childs[j].isDirectory())
    Direc.addElement(childs[j]);
    else
    Files.addElement(childs[j]);
    for(int g = 0; g < Files.size(); g++)
    Direc.addElement((File)Files.elementAt(g));
    for(int i = 0; i < Direc.size(); i++)
    node.add(unfold((File)Direc.elementAt(i)));
    else if(!(path.isDirectory()))
    node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
    else
    node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
    node.add(new DefaultMutableTreeNode(new FileInfo(null,"<EMPTY FOLDER>")));
    return node;
    public static String getRoot(String path)
    int find = path.indexOf(System.getProperty("file.separator"));
    String root = path.substring(0,find + 1);
    return root;
    public static void main( String [ ] args )throws FileNotFoundException, InterruptedException, IOException, ClassNotFoundException {
    File_Encryptor show = new File_Encryptor();
    show.setSize(700, 500);
    show.setResizable(false);
    //show.setLocation(100,100);
    show.setVisible(true);
    //code end.
    //well there it is. Hope someone can help me with my problem.
    //I know this code is ugly, but I was trying a bunch of different
    //things hoping something would work. but ehh no such luck.
    //I am running windows 98, yea that's prolly my problem.
    //thank you for your time.

    I ran this on XP and got the null pointer exception...
    it's likely that it's running into a file or directory that it can't list (in my case it was a mount on a different directory ntfs is kinda cool)... SO... to handle that problem I just put the whole method in a try / catch block
    it was just the method unfold ... the fix returns a blank treenode... it should probably return null and the caller should see that as a sign to not add it to the tree...
         private DefaultMutableTreeNode unfold(File path) {
              DefaultMutableTreeNode node = new DefaultMutableTreeNode("");
              try
                   Vector Files = new Vector();
                   Vector Direc = new Vector();
                   if(path==null)
                        return(node);
                   if((path.isDirectory()) && (path.list().length != 0))
                   node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
                   File [] childs = path.listFiles();
                   for(int j = 0; j < childs.length; j++)
                   if(childs[j].isDirectory())
                   Direc.addElement(childs[j]);
                   else
                   Files.addElement(childs[j]);
                   for(int g = 0; g < Files.size(); g++)
                   Direc.addElement((File)Files.elementAt(g));
                   for(int i = 0; i < Direc.size(); i++)
                   node.add(unfold((File)Direc.elementAt(i)));
                   else if(!(path.isDirectory()))
                   node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
                   else
                   node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
                   node.add(new DefaultMutableTreeNode(new FileInfo(null,"<EMPTY FOLDER>")));
              catch (Exception e)
              return node;
         }

  • About to use my friggin tree for firewood  :o(

    I was wondering if someone could maybe clue me into a problem that I am having with my DefaultMutableTree. See, I call a recursive method to get the file system of the computer, which is what is added to the tree. So the user is looking at a tree structure of the file system of their computer. My problem is that when I compile and run my program the tree shows up fine, with no hitches. I have given my code to other friends, and for some of them it does not show up, and throws a null pointer exception at the internal interface of this recursive method. I was wondering what might be causing this? My friends that have problems with the code are running either WIN XP, or Mac OS 10.1.4. Here is the code for the initialization of the tree (This will look ugly on the post, so I would hope that you would take the time to copy and paste this into your editor :D)
    //code start.
    import java.io.*;
    import java.io.File;
    import java.lang.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.beans.*;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.TreeSelectionModel;
    public class File_Encryptor extends JFrame {
    private JFrame thisFrame = this;
    private JTree tree;
    private JMenuBar jMenuBar1 = new JMenuBar();
    private JMenuItem menuOpen = new JMenuItem("Open");
    private JMenuItem menuSave = new JMenuItem("Save");
    private JMenuItem menuClose = new JMenuItem("Close");
    private JMenuItem menuQuit = new JMenuItem("Quit");
    private JMenuItem menuAbout = new JMenuItem("About this software...");
    private JMenuItem menuAdd = new JMenuItem("Add key and user");
    private JMenuItem menuChange = new JMenuItem("Change buddy key");
    private JMenuItem menuSend = new JMenuItem("Send your buddy key");
    private JMenuItem menuDelete = new JMenuItem("Delete selected buddy key");
    private JMenuItem menuReset = new JMenuItem("Reset your key");
    private JMenuItem menuChangeLogin = new JMenuItem("Change Login");
    private JMenuItem menuHelp = new JMenuItem("Help...");
    private JButton openDir = new JButton("Open path");
    private JTextField jTextField1 = new JTextField();
    private JScrollPane treeView;
    private JScrollPane imageView;
    private JScrollPane textView;
    private String ROOT;
    private File root;
    private DefaultMutableTreeNode top;
    final private DefaultMutableTreeNode FILLER = new DefaultMutableTreeNode(new FileInfo ("about:blank", "about:blank"));
    public File_Encryptor() throws FileNotFoundException, InterruptedException, IOException, ClassNotFoundException {
    super("FILE ENCRYPTOR 1.0");
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    ROOT = getRoot(System.getProperty("user.home"));
    root = new File(ROOT);
    try{
    //Create the nodes.
    top = unfold(root);
    top.setUserObject(new FileInfo(ROOT,ROOT));
    tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
    Object nodage = top.getNextNode().getUserObject();
    FileInfo leaf = (FileInfo) nodage;
    tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
    tree.getLastSelectedPathComponent();
    if (node == null) return;
    try{
    Object nodeInfo = node.getUserObject();
    FileInfo temp = (FileInfo) nodeInfo;
    if((node.isLeaf()) && (!(node.isRoot())))
    System.out.println(temp.Path());
    //figure out how to place file in editor pane.
    else
    return;
    catch(Exception fubar)
    fubar.printStackTrace();
    treeView = new JScrollPane(tree);
    treeView.setSize(150,450);
    jTextField1.setMaximumSize(new Dimension(50, 100));
    jTextField1.setText("PATH");
    this.getContentPane().add(jTextField1, BorderLayout.EAST);
    this.getContentPane().add(treeView, BorderLayout.WEST);
    catch(Exception e) {
    e.printStackTrace();
    jMenuBar1.setBorder(BorderFactory.createEtchedBorder());
    JMenu menu = new JMenu("File");
    JMenu about = new JMenu("Help");
    JMenu keys = new JMenu("Keys");
    JMenu change = new JMenu("Login");
    menuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.META_MASK));
    menuQuit.setEnabled(true);
    menuQuit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    menu.add(menuQuit);
    jMenuBar1.add(menu);
    jMenuBar1.add(keys);
    jMenuBar1.add(change);
    jMenuBar1.add(about);
    this.setJMenuBar(jMenuBar1);
    public class FileInfo {
    private String path = "";
    private String name = "";
    public FileInfo(String p , String n){
    path = p;
    name = n;
    public String toString(){
    return name;
    public String Path(){
    return path;
    public static String getFileEx(String po){
    String ext = "";
    int i = po.lastIndexOf('.');
    if(i > 0)
    ext = po.substring(i-1);
    else
    ext = null;
    return ext;
    private DefaultMutableTreeNode unfold(File path) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode("");
    Vector Files = new Vector();
    Vector Direc = new Vector();
    if((path.isDirectory()) && (path.list().length != 0))
    node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
    File [] childs = path.listFiles();
    for(int j = 0; j < childs.length; j++)
    if(childs[j].isDirectory())
    Direc.addElement(childs[j]);
    else
    Files.addElement(childs[j]);
    for(int g = 0; g < Files.size(); g++)
    Direc.addElement((File)Files.elementAt(g));
    for(int i = 0; i < Direc.size(); i++)
    node.add(unfold((File)Direc.elementAt(i)));
    else if(!(path.isDirectory()))
    node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
    else
    node = new DefaultMutableTreeNode(new FileInfo(path.getPath(),path.getName()));
    node.add(new DefaultMutableTreeNode(new FileInfo(null,"<EMPTY FOLDER>")));
    return node;
    public static String getRoot(String path)
    int find = path.indexOf(System.getProperty("file.separator"));
    String root = path.substring(0,find + 1);
    return root;
    public static void main( String [ ] args )throws FileNotFoundException, InterruptedException, IOException, ClassNotFoundException {
    File_Encryptor show = new File_Encryptor();
    show.setSize(700, 500);
    show.setResizable(false);
    //show.setLocation(100,100);
    show.setVisible(true);
    //code end.
    //well there it is. Hope someone can help me with my problem.
    //I know this code is ugly, but I was trying a bunch of different
    //things hoping something would work. but ehh no such luck.
    //I am running windows 98, yea that's prolly my problem.
    //thank you for your time.

    So you consider this exact post appropriate for both the Advanced Language Topics and New to Java Technology? Did you post this question anywhere else? Don't double post.
    Anyway, check the post in NtJT. The answer is there.

  • Lack of Generic Tree support

    I am wondering how people feel about the lack of the Tree type in Java? I find the Java types pretty weak generally, but at least there are several Set, Map, List implementation to choose from. There is no Tree, or perhaps there are too many. There is the UI tree classes (in swing), the Preference class has a tree like interface, JNDI, etc.
    I am wondering if this is a problem for others? We ended up creating our own Tree interface and implementations.
    Pat O

    Have you looked at the DefaultMutableTreeNode? Ifso, what is lacking in your opinion?
    It's Swing. I've used JVMs on headless Linux boxes
    which had serious issues with AWT to the extent that
    we simply did not use any AWT or Swing classes.No, it isn't. I mean, sure, it's in a javax.swing.something package, but it doesn't have any GUI components. I don't think headlessness should affect it in the least.
    I'm happy to be proven wrong, but only with malfunctioning code, not with a quick look at the name of the package.

  • How to cut, copy and paste a tree node in JTree?????

    Hi, Java GUI guru. Thank you for your help in advance.
    I am working on a File Explorer project with JTree. There are cut, copy and paste item menus in my menu bar. I need three EventAction methods or classes to implements the three tasks. I tried to use Clipboard to copy and paste tree node. But I can not copy any tree node from my tree.
    Are there any body has sample source code about cut, copy, and paste for tree? If possible, would you mind send me your sample source code to [email protected]
    I would appreciate you very very much for your help!!!!
    X.G.

    Hi, Paul Clapham:
    Thank you for your quick answer.
    I store the node in a DefaultMutableTreeNode variable, and assign it to another DefaultMutableTreeNode variable. I set up two classes (CopyNode and PasteNode). Here they are as follows:
    //CopyNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class CopyNode implements ActionListener{
    private TreeList jtree;
    String treeNodeName;
    TreePath currentSelection;
    DefaultMutableTreeNode currentNode;
    public CopyNode(TreeList t){
    jtree = t;
    public void actionPerformed(ActionEvent e){
    currentSelection = jtree.tree.getSelectionPath();
    if(currentSelection != null){
    currentNode = (DefaultMutableTreeNode)(currentSelection.getLastPathComponent());
    treeNodeName = currentNode.toString();
    //PasteNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class PasteNode extends DefaultMutableTreeNode{
    private TreeList jtree;
    CopyNode copyNode;
    public PasteNode(TreeList t){
    jtree = t;
    copyNode = new CopyNode(t);
    public DefaultMutableTreeNode addObject(Object child){
    DefaultMutableTreeNode parentNode = null;
    TreePath parentPath = jtree.tree.getSelectionPath();
    if(parentPath == null){
    parentNode = jtree.root;
    else{
    parentNode = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
    return addObject(parentNode, child, true);
    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible){
    DefaultMutableTreeNode childNode = copyNode.currentNode;
    if(parent == null){
    parent = jtree.root;
    jtree.treemodel.insertNodeInto(childNode, parent, parent.getChildCount());
    if(shouldBeVisible){
    jtree.tree.scrollPathToVisible(new TreePath(childNode.getPath()));
    return childNode;
    I used these two classes objects in "actionPerformed(ActionEvent e)" methods in my tree:
    //invoke copyNode
    copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(copyNode);
    //invoke pasteNode
    pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    pasteName.addObject(copyName.treeNodeName);
    When I run the drive code, making a copy some node from my tree list, I got bunch of error messages.
    Can you figour out what is wrong in my two classes? If you have sample code, would you mind mail me for reference.
    Thank you very much in advance.
    X.G.

  • XML : Transform DOM Tree to XML String in an applet since the JRE 1.4.2_05

    Hello,
    I build a DOM tree in my applet.
    Then I transform it to XML String.
    But since the JRE 1.4.2_05 it doesn't work.
    These lines failed because these variables became final:
    org.apache.xalan.serialize.CharInfo.XML_ENTITIES_RESOURCE = getClass().getResource("XMLEntities.res").toString();
    org.apache.xalan.processor.TransformerFactoryImpl.XSLT_PROPERTIES = getClass().getResource("XSLTInfo.properties").toString();The rest of the code :
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document domXML = builder.newDocument();
    // I build my DOM Tree
    StringWriter xmlResult = new StringWriter();
    Source source = new DOMSource(domXML);
    Result result = new StreamResult(xmlResult);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
    xformer.transform(source,result);Is there any other way to get an XML String from a DOM tree in an applet ?
    I'm so disappointed to note this big problem.

    Does anyone have an idea why I get this error message when try to use transform in an applet?
    Thanks...
    java.lang.ExceptionInInitializerError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at org.apache.xalan.serialize.SerializerFactory.getSerializer(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(Unknown Source)
         at matrix.CreateMtrx.SaveDoc(CreateMtrx.java:434)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at thinlet.Thinlet.invokeImpl(Unknown Source)
         at thinlet.Thinlet.invoke(Unknown Source)
         at thinlet.Thinlet.handleMouseEvent(Unknown Source)
         at thinlet.Thinlet.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
    XMLEntities.res      java.net.MalformedURLException: no protocol: XMLEntities.res
         at org.apache.xalan.serialize.CharInfo.<init>(Unknown Source)
         at org.apache.xalan.serialize.SerializerToXML.<clinit>(Unknown Source)
         ... 28 more

Maybe you are looking for