Tree (TreeView) in Applet

Hello,
could you please give a hint how I can use TreeView in applets?
Actually I need a code example of how to add a TreeView component to an applet.

Let me be your google agent. Rather than have you waste your time typing in a web search query, you can just click on this link:
http://www.google.com/search?hl=en&q=applet+TreeView+example

Similar Messages

  • Tree in java applet

    Please help
    i want to create a tree (the leaves label come from database ) in java applet... how can i start ?

    This is for a school assignment isn't it?
    The tutorial has how to read from a database, and about trees in it. There are even ready make classes for tree structures. So crack your book and give it a read, click on the tutorial link, and open the API... if it's not worth it to you, then why should it be to us?

  • Tree view in applet

    I want to show the file system in my hard-disk in the form of a tree, in a JSP page. Iam calling an applet in that jsp page. This applet in turn calls a java program which prepares a JTree object. But am getting an exception while calling this applet. It gives java.io.FilePermission exception. The java file cannot read the filesystem in the hard-disk. Can anyone please give a solution for this problem???

    By default, Applets do not have permisison to read information about client computers. You will need to sign the Applet jar file. There should be a tutorial somewhere - Google will find it.

  • Call tree treeview doesnt go down far enough?

    Hi,
    When running an instrumentation profile on an asp.net application in VS2013 why is that the full call tree is not shown even though the code underneath the last element in the treeview definitely has my code underneath?
    If I use Redgate ANTS profiler then the full tree output is shown. 
    The MS profiler stops after about 5 levels deep, I have tried changing the summary call depth to 10, have turned off "Just My Code", have turned off "ignore small functions" but still nothing..???
    Anyone got any thoughts?
    Thanks,

    Hi,
    >>why is that the full call tree is not shown even though the code underneath the last element in the treeview definitely has my code underneath?
    Could you share me a screen shot about the result in your side? Please also share us the result result with Redgate ANTS profiler with a different screen
    shot.
    If you mean that you get the result like this screen shot1 in VS IDE, it doesn't share all call trees like screen shot 2, I doubt that it is by design, we need to click the tree manually.
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Display tree in applet

    i have a program to convert Xml to tree structure. But i am not able to call it in JSP. So i want to convert to applet. how to convert it.
    package TreeGen;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import java.io.File;
    import java.io.IOException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Element;
    // Basic GUI components
    import javax.swing.JApplet;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    // GUI components for right-hand side
    import javax.swing.JSplitPane;
    import javax.swing.JEditorPane;
    // GUI support classes
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    // For creating borders
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    // For creating a TreeModel
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.applet.*;
    public class TreeGen extends JPanel
         static Document document;
         boolean compress = false;
         static final int windowHeight = 660;
         static final int leftWidth = 300;
         static final int rightWidth = 640;
         static final int windowWidth = leftWidth + rightWidth;
         public TreeGen()
         EmptyBorder eb = new EmptyBorder(5,5,5,5);
         BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
         CompoundBorder cb = new CompoundBorder(eb,bb);
         this.setBorder(new CompoundBorder(cb,eb));
         JTree tree = new JTree(new DomToTreeModelAdapter());
         JScrollPane treeView = new JScrollPane(tree);
         treeView.setPreferredSize(
              new Dimension( leftWidth, windowHeight ));
         final
         JEditorPane htmlPane = new JEditorPane("text/html","");
         htmlPane.setEditable(true);
         JScrollPane htmlView = new JScrollPane(htmlPane);
         htmlView.setPreferredSize(
              new Dimension( rightWidth, windowHeight ));
         tree.addTreeSelectionListener(
              new TreeSelectionListener()
              public void valueChanged(TreeSelectionEvent e)
                   TreePath p = e.getNewLeadSelectionPath();
                   if (p != null)
                   AdapterNode adpNode =
                        (AdapterNode) p.getLastPathComponent();
                   htmlPane.setText(adpNode.content());
         JSplitPane splitPane =
              new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                                  treeView,
                                  htmlView );
         splitPane.setContinuousLayout( false );
         splitPane.setDividerLocation( leftWidth );
         splitPane.setDividerSize(1);
         splitPane.setPreferredSize(
                   new Dimension( windowWidth + 10, windowHeight+10 ));
         this.setLayout(new BorderLayout());
         this.add("Center", splitPane );
         //return menuBar;
         } // constructor
         public static void main(String argv[])
              DocumentBuilderFactory factory =
                   DocumentBuilderFactory.newInstance();
              try {
              DocumentBuilder builder = factory.newDocumentBuilder();
              document = builder.parse("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/parser1/sample.xml");
                   makeFrame();
              } catch (SAXException sxe){
                   System.out.println("ERROR");
              Exception x = sxe;
              if (sxe.getException() != null)
                   x = sxe.getException();
              x.printStackTrace();
              } catch (ParserConfigurationException pce) {
                   pce.printStackTrace();
              } catch (IOException ioe) {
              ioe.printStackTrace();
         } // main
         public static void makeFrame()
              //JApplet app = new JApplet();
              //app.add
              JFrame frame = new JFrame("DOM Echo");
              frame.addWindowListener(
              new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {System.exit(0);}
              final TreeGen echoPanel =
              new TreeGen();
              frame.getContentPane().add("Center", echoPanel );
              frame.pack();
              Dimension screenSize =
              Toolkit.getDefaultToolkit().getScreenSize();
              int w = windowWidth + 10;
              int h = windowHeight + 10;
              //TreeGen tg = new TreeGen();
              //MenuDemo demo = new MenuDemo();
              //frame.setJMenuBar(demo.createMenuBar());
              //frame.setContentPane(demo.createContentPane());
              //Display the window.
              frame.setSize(w, h);
              frame.setVisible(true);
         } // makeFrame
         static final String[] typeName = {
              "none",
              "Element",
              "Attr",
              "Text",
              "CDATA",
              "EntityRef",
              "Entity",
              "ProcInstr",
              "Comment",
              "Document",
              "DocType",
              "DocFragment",
              "Notation",
         static final int ELEMENT_TYPE = 1;
         static final int ATTR_TYPE = 2;
         static final int TEXT_TYPE = 3;
         static final int CDATA_TYPE = 4;
         static final int ENTITYREF_TYPE = 5;
         static final int ENTITY_TYPE = 6;
         static final int PROCINSTR_TYPE = 7;
         static final int COMMENT_TYPE = 8;
         static final int DOCUMENT_TYPE = 9;
         static final int DOCTYPE_TYPE = 10;
         static final int DOCFRAG_TYPE = 11;
         static final int NOTATION_TYPE = 12;
    static String[] treeElementNames = {
              "slideshow",
              "slide",
              "title", // For slideshow #1
              "slide-title", // For slideshow #10
              "item",
         boolean treeElement(String elementName) {
         for (int i=0; i<treeElementNames.length; i++) {
              //System.out.println(treeElementNames);
              if ( elementName.equals(treeElementNames[i]) )
              return true;
         return false;
         public class AdapterNode
         org.w3c.dom.Node domNode;
         public AdapterNode(org.w3c.dom.Node node)
              domNode = node;
         public String toString()
              String s = typeName[domNode.getNodeType()];
              String nodeName = domNode.getNodeName();
              if (! nodeName.startsWith("#"))
              s += ": " + nodeName;
              if (compress)
              String t = content().trim();
              int x = t.indexOf("\n");
              if (x >= 0) t = t.substring(0, x);
              s += " " + t;
              return s;
              if (domNode.getNodeValue() != null)
              if (s.startsWith("ProcInstr"))
                   s += ", ";
              else
                   s += ": ";
              // Trim the value to get rid of NL's at the front
              String t = domNode.getNodeValue().trim();
              int x = t.indexOf("\n");
              if (x >= 0) t = t.substring(0, x);
              s += t;
              return s;
         public String content()
              String s = "";
              org.w3c.dom.NodeList nodeList = domNode.getChildNodes();
              for (int i=0; i<nodeList.getLength(); i++)
              org.w3c.dom.Node node = nodeList.item(i);
              int type = node.getNodeType();
              //System.out.println(type);
              AdapterNode adpNode = new AdapterNode(node); //inefficient, but works
              if (type == ELEMENT_TYPE)
                   if ( treeElement(node.getNodeName()) ) continue;
                   s += "<" + node.getNodeName() + ">";
                   s += adpNode.content();
                   s += "</" + node.getNodeName() + ">";
              else if (type == TEXT_TYPE)
                   s += node.getNodeValue();
              else if (type == ENTITYREF_TYPE)
                   s += adpNode.content();
              else if (type == CDATA_TYPE)
                   StringBuffer sb = new StringBuffer( node.getNodeValue() );
                   for (int j=0; j<sb.length(); j++)
                   if (sb.charAt(j) == '<')
                        sb.setCharAt(j, '&');
                        sb.insert(j+1, "lt;");
                        j += 3;
                   else if (sb.charAt(j) == '&')
                        sb.setCharAt(j, '&');
                        sb.insert(j+1, "amp;");
                        j += 4;
                   s += "<pre>" + sb + "\n</pre>";
              return s;
         public int index(AdapterNode child)
              int count = childCount();
              for (int i=0; i<count; i++)
              AdapterNode n = this.child(i);
              if (child.domNode == n.domNode) return i;
              return -1; // Should never get here.
         public AdapterNode child(int searchIndex)
              org.w3c.dom.Node node =
                   domNode.getChildNodes().item(searchIndex);
              if (compress)
              int elementNodeIndex = 0;
              for (int i=0; i<domNode.getChildNodes().getLength(); i++)
                   node = domNode.getChildNodes().item(i);
                   if (node.getNodeType() == ELEMENT_TYPE
                   && treeElement( node.getNodeName() )
                   && elementNodeIndex++ == searchIndex)
                   break;
              return new AdapterNode(node);
         public int childCount()
              if (!compress)
              return domNode.getChildNodes().getLength();
              int count = 0;
              for (int i=0; i<domNode.getChildNodes().getLength(); i++)
              org.w3c.dom.Node node = domNode.getChildNodes().item(i);
              if (node.getNodeType() == ELEMENT_TYPE
              && treeElement( node.getNodeName() ))
                   ++count;
              return count;
         public class DomToTreeModelAdapter
         implements javax.swing.tree.TreeModel
         public Object getRoot()
              return new AdapterNode(document);
         public boolean isLeaf(Object aNode)
              AdapterNode node = (AdapterNode) aNode;
              if (node.childCount() > 0) return false;
              return true;
         public int getChildCount(Object parent)
              AdapterNode node = (AdapterNode) parent;
              return node.childCount();
         public Object getChild(Object parent, int index)
              AdapterNode node = (AdapterNode) parent;
              return node.child(index);
         public int getIndexOfChild(Object parent, Object child)
              AdapterNode node = (AdapterNode) parent;
              return node.index((AdapterNode) child);
         public void valueForPathChanged(TreePath path, Object newValue)
         private Vector listenerList = new Vector();
         public void addTreeModelListener(TreeModelListener listener)
              if ( listener != null
              && ! listenerList.contains( listener ) )
              listenerList.addElement( listener );
         public void removeTreeModelListener(TreeModelListener listener)
              if ( listener != null )
              listenerList.removeElement( listener );
         public void fireTreeNodesChanged( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesChanged( e );
         public void fireTreeNodesInserted( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesInserted( e );
         public void fireTreeNodesRemoved( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesRemoved( e );
         public void fireTreeStructureChanged( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeStructureChanged( e );
    pls help.
    ramya

    There's already some applet code in there, although it's commented out. Did you add that?
    Anyway, the general principle for turning an app into an applet, is to replace the main() method with the Applet's (or JApplet's) init(), start(), and stop() methods. Also you won't be able to read data off the file system; use resources instead. (e.g., java.lang.Class.getResource)
    I'm not sure what this has to do with JSP.
    When you post code, please wrap it in &#91;code]&#91;/code] tags.

  • 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

  • Resize applet within a HTML frame

    Hi,
    I am using an applet to display a tree in a HTML frame of a web page.
    I would like to resize or refresh the applet when the HTML frame is resized. Is there a way for the applet to know when the HTML frame is resized?
    Any help will be appreciated.
    Thanks

    I tried using the componentResized() method to solve this problem but I was unsuccessful.
    Here is what I tried:
    My application consists of using a Java applet to display a tree in a HTML frame. In addition I put the tree in a scroll pane. I tried using addComponentListener(this) to get the componentResized() method to be involked. I tried adding the component listener to the scroll pane:
    JScrollPane treeView = new JScrollPane(tree);
    treeView.addComponentListener(this);
    I tried adding the component listener to the root pane:
    JRootPane root = getRootPane();
    root.addComponentListener(this);
    and I tried adding the comoponent listener to the glass pane and the content pane.
    The componentResized() method was involked when the tree was initially displayed in some of my attempts but I was never able to get the componentResized() method to be involked when I resized the html frame.
    I believe that I am having a problem determining which component to add the addComponentListener to so that the componentResized() method get invoked when I resize the html frame.

  • 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.

  • How to display a directory on server like JTree in applet?

    I want to display a directory on server like jtree.
    I use File("\\\\server\\directory") to present the root directory and use File.list() to display all file under root directory.Then I create Jtree object using files as treenode.
    at last i want to display the tree in my applet,but in browser an exception occured,it said " can not find Class TreeNode ".
    what can i do now ?
    thanks very much

    If you want to use JTree in an applet, there are two things you need to do.
    1. Use Swing components for the applet. i.e. extend JApplet instead of Applet. See the Swing tutorial if this is new to you.
    2. Find a way for the browser to access the Swing classes. The JVM that comes with the browser will not do this, so either distribute the classes with your applet or specify that the Sun Java plug-in be used. This will require a one-time download of a large file for each user.
    These deployment issues are the reason why most applets stay with straight AWT and JDK 1.1.8 which are supported by the browser's "built-in" JVM. You should consider these issues before deciding to use Swing in an applet.

  • Using TreeViewer and creating a pop-up menu?

    I am using Eclipse Ganymede(3.1?) to write my program. This project has multiple parts(most issues/progress can be tracked back in java-forums.org) and I am trying to get the last bit of my GUI finished. I have a TreeViewer that displays on top of a composite display(not a component) which is why I haven't been able to find a solution that works for me. My tree is interactive(double click nodes to expand, deepest nodes open up an editor view, auto refresh new nodes/deletes etc) and I'm trying to make a pop-up menu appear on right click that would give all the options the File menu gives. I haven't been able to find a work around on how to attach the menu since my TreeViewer is based on a composite instead of a component there is no where to attach the menu. I have been working on this one issue for a week with no progress and am at the point where I'm tempted to rewrite my entire project using JPanel and JPanes and Tree but I REALLY don't want to have to do this. This is my createPartControl method with the relevent sections.
    public void createPartControl(final Composite parent) {
    //          final Tree tree = new Tree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
              treeViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
    //          treeViewer = new TreeViewer(tree);
              treeViewer.setContentProvider(new ViewContentProvider());
              treeViewer.setLabelProvider(new ViewLabelProvider());
              treeViewer.setInput(createDummyModel());
    //Double click listener
              treeViewer.addOpenListener(new IOpenListener() {
                   public void open(final OpenEvent event) {
                        //double click expands/shrinks nodes, opens up target editors
    //Selection listener
              treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
                      public void selectionChanged(SelectionChangedEvent event) {
                           final IActionBars bars = getViewSite().getActionBars();
                           selObj = ((IStructuredSelection) event.getSelection()).getFirstElement();                      
                                      //...outputs selection to status bar
    //Mouse listener
              treeViewer.getTree().addMouseListener(new MouseAdapter(){
                 public void mouseUp(MouseEvent event){
                      if(event.button==3){         //right click
                           System.out.println(event.getSource());        //Tree{ }
                           System.out.println(event.display);             //org.eclipse.swt.widgets.Display@1e328e0
                           if(selObj instanceof Server){
                                System.out.println(treeViewer.getControl().toString());          //Same as event.getSource()
                                               /*code to have menu appear goes here*/
                                System.out.println("Server Menu");
                                //Delete Server
                                //Edit Server
                                //View Properties
         }Does anybody know a way I can attach a popup menu to the node I click on or if it's possible(and if so how would I go about) attaching it to the display beneath the TreeViewer and somehow setting the focus or making the popup a heavy component so it would appear on top?
    P.S there's alot more superfluous code in the listeners but they don't pertain to this so I removed them.

    Can anyone confirm that what I'm trying to do is not possible? I found this link which states an SWT bug of the header not being a control so it become unattachable. http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg38040.html
    Any truth in this and if so where can I track progress of the bug?

  • Drag into TreeView

    Hello everyone,
    I want to make an easy application where you have a tree and on the other side three images. In this example I used three rectangles each one with a different color.
    The user should be able to drag one of the rectangles to a tree item in order to add a new subitem.
    Everything is working, the only problem I have is that I also be able to drop anywhere in the whole tree "frame". I want that the user is only allowed to release over
    a tree item, not anywhere in the treeframe.
    My second question is, can I also drag the whole image / rectangle instead of this small windows standard box when a user tries to drag something? I read that this
    would be possible in JavaFX 8, there you are able to pass a whole image to the dragboard. My goal was to set the opacity of the draged rectangle to 20% and then stick
    the rectangle to the mouse and if the user release the mouse, the rectangle should go back to its orignal position with the full opacity. That would be a "nice to have", but
    the first problem is kind of important.
    This example should work out of the box:
    package de.hauke.edi;
    import java.io.IOException;
    import de.cargosoft.edi.eservicemanager.Main3.ModuleTreeItem;
    import javafx.animation.TranslateTransition;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.TreeCell;
    import javafx.scene.control.TreeItem;
    import javafx.scene.control.TreeView;
    import javafx.scene.image.ImageView;
    import javafx.scene.input.ClipboardContent;
    import javafx.scene.input.DragEvent;
    import javafx.scene.input.Dragboard;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.input.TransferMode;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.VBox;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    import javafx.util.Duration;
    public class Main4 extends Application {
        @Override
        public void start(Stage primaryStage) throws IOException {
            BorderPane border = new BorderPane();
            Scene scene = new Scene(border, 700, 700);
            // setup tree
            TreeView<String> tree = new TreeView<String>();
            TreeItem<String> rootItem = new TreeItem<String>("Root");
            rootItem.setExpanded(true);
            for (int i = 1; i < 6; i++) {
                TreeItem<String> item = new TreeItem<String>("Node" + i);
                rootItem.getChildren().add(item);
            tree.setRoot(rootItem);
            // setup boxes
            final Rectangle red = new Rectangle(100, 100);
            red.setFill(Color.RED);
            final Rectangle green = new Rectangle(100, 100);
            green.setFill(Color.GREEN);
            final Rectangle blue = new Rectangle(100, 100);
            blue.setFill(Color.BLUE);
            addDragFunction(red, "red");
            addDragFunction(green, "green");
            addDragFunction(blue, "blue");
            tree.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
                public TreeCell<String> call(TreeView<String> arg0) {
                    final TreeCell<String> treeCell = new TreeCell<String>() {
                        protected void updateItem(String item, boolean empty) {
                            super.updateItem(item, empty);
                            if (item != null) {
                                setText(item);
                    treeCell.setOnDragOver(new EventHandler<DragEvent>() {
                        public void handle(DragEvent event) {
                            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                            event.consume();
                    treeCell.setOnDragDropped(new EventHandler<DragEvent>() {
                        public void handle(DragEvent event) {
                            Dragboard db = event.getDragboard();
                            if (db.hasString()) {
                                TreeItem<String> item = new TreeItem<String>("New "+db.getString() + " colored element dropped");
                                treeCell.getTreeItem().getChildren().add(item);
                                treeCell.getTreeItem().setExpanded(true);
                            event.consume();
                    return treeCell;
            // add elements to stage
            VBox vbox = new VBox();
            vbox.getChildren().add(red);
            vbox.getChildren().add(green);
            vbox.getChildren().add(blue);
            border.setLeft(tree);
            border.setRight(vbox);
            primaryStage.setScene(scene);
            primaryStage.show();
        private void addDragFunction(final Rectangle control, final String code) {
            control.setOnDragDetected(new EventHandler<MouseEvent>() {
                public void handle(MouseEvent event) {
                    Dragboard db = control.startDragAndDrop(TransferMode.ANY);
                    /* put a string on dragboard */
                    ClipboardContent content = new ClipboardContent();
                    content.putString(code);
                    db.setContent(content);
                    event.consume();
            control.setOnDragDone(new EventHandler<DragEvent>() {
                public void handle(DragEvent event) {
                    event.consume();
        public static void main(String[] args) {
            launch(args);
    Thanks for any help!

    Everything is working, the only problem I have is that I also be able to drop anywhere in the whole tree "frame". I want that the user is only allowed to release over
    a tree item, not anywhere in the treeframe.
    Just surround the code in the handle methods for your setOnDragOver and setOnDragDropped handlers with
    if ( ! treeCell.isEmpty() ) { ... }
    You could add further logic here if you needed, e.g. to prevent the user dropping on the root or to limit the number of children dropped onto a single node.
    For the JavaFX 8 image functionality with the drag, in your setOnDragDetected handler, change the opacity, create an image from the control by calling snapshot(), and pass the image to the Dragboard's setDragView(...) method. In the setOnDragDone handler, revert the opacity.

  • Applet not loading in different os

    hi all,
    i have created an tree structure using applet for my website. the appplet is loading in all os except windows 2000professional and 2003 64 bit os.

    hi ,
    thanks for ur question. i want to know the solution how to get my applet in windows 2000 professional and 2003 64 bit os. what is the problem in these two os. is there any solution for these problem.
    thanks & regards

  • Components and applet not loading when running the application using JVM1.3

    I have my UI written in JavaScript.When I click a button,it opens a window showing the different components(images) and an applet containing a tree structure.The applet code is written in java
    This is working fine and the applet is loading properly when I use JVM1.4. But there is a problem when I use JVM1.3.1_09.The images appear broken and the applet doesnot load.(When I click on one of the broken images,the images appear correctly but the applet still doesn't load)
    Can anyone tell me what could be the reason behind this behavior??
    My sys config: win2k-SP4, IE5.0-SP4

    If you are using SDK 1.4 for compilation,
    recompile your classes with the option -target 1.1
    javac -target 1.1 MyClass.java

Maybe you are looking for

  • Time Machine showing multiple times in finder

    One of my clients is having an issue where throughout the week the time machine volume will slowly keep adding multiple copys of itself to his finder sidebar. It seems like it is not unmounting after a backup and will clutter the finder sidebar. A re

  • Error while starting Managedserver for 2nd server in cluster

    Hi we have 2 Unix servers of which one has Admin and managed server and second has only managed server. while starting managed server for 2nd unix server we are getting below error though it is in running state: KINDLY HELP!! changed Location=site:XX

  • How can I download YouTube in my I pad 2, How can I download YouTube in my I pad 2

    Hi I am trying to download you tube from app store but there is a message shown that this application requires ios6.0or later, you must update to iOS 6.0 in order to download and use this applicatiom

  • Processing multi-part messages in Flex

    Hello, I'm writing an extension for Photoshop using AS3 and Flex. This extension connects to a HTTP server that replies with an HTTP multi-part response containing images. Is Flex able to decode this response? So far I have only been able to see the

  • Re-install of CS2 - Indesign crashes when I try to make a PDF

    I had upgraded to snow leopard & bought CS5. Which wouldn't work on my computer. I had to re-install CS2 & now I can't create any PDFs. The program quits unexpectedly. Any suggestions??? Thanks, Diana DePasquale