Creating file browser GUI using java swing tree

Hi all,
I have some questions which i wish to clarify asap. I am working on a file browser project using java swing. I need to create 2 separate buttons. 1 of them will add a 'folder' while the other button will add a 'file' to the tree when the buttons are clicked once. The sample source code known as 'DynamicTreeDemo' which is found in the java website only has 1 add button which is not what i want. Please help if you know how the program should be written. Thx a lot.
Regards,

Sorry, don't know 'DynamicTreeDemo'import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.io.File;
public class Test extends JFrame {
  JTree jt = new JTree();
  DefaultTreeModel dtm = (DefaultTreeModel)jt.getModel();
  JButton newDir = new JButton("new Dir"), newFile = new JButton("new File");
  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    newDir.setEnabled(false);
    newFile.setEnabled(false);
    jt.setShowsRootHandles(true);
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    File c = new File("C:\\temp");
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(c);
    dtm.setRoot(root);
    addChildren(root);
    jt.addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent tse) { select(tse) ; }
    JPanel jp = new JPanel();
    content.add(jp, BorderLayout.SOUTH);
    jp.add(newDir);
    jp.add(newFile);
    newDir.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        TreePath tp = jt.getSelectionPath();
        if (tp!=null) {
          DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
          File newFile = new File((File)dmtn.getUserObject(),"foo");
          if (newFile.mkdir()) {
            dmtn.add(new DefaultMutableTreeNode(newFile));
            dtm.nodeStructureChanged(dmtn);
          } else System.out.println("No Dir");
    newFile.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        TreePath tp = jt.getSelectionPath();
        if (tp!=null) {
          DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
          File newFile = new File((File)dmtn.getUserObject(),"foo.txt");
          try {
            if (newFile.createNewFile()) {
              dmtn.add(new DefaultMutableTreeNode(newFile));
              dtm.nodeStructureChanged(dmtn);
            } else System.out.println("No File");
          catch (java.io.IOException ioe) { ioe.printStackTrace(); }
    setSize(300, 300);
    setVisible(true);
  void select(TreeSelectionEvent tse) {
    TreePath tp = jt.getSelectionPath();
    newDir.setEnabled(false);
    newFile.setEnabled(false);
    if (tp!=null) {
      DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
      File f = (File)dmtn.getUserObject();
      if (f.isDirectory()) {
        newDir.setEnabled(true);
        newFile.setEnabled(true);
  void addChildren(DefaultMutableTreeNode parent) {
    File parentFile = (File)parent.getUserObject();
    File[] children = parentFile.listFiles();
    for (int i=0; i<children.length; i++) {
      DefaultMutableTreeNode child = new DefaultMutableTreeNode(children);
parent.add(child);
if (children[i].isDirectory()) addChildren(child);
public static void main(String[] args) { new Test(); }

Similar Messages

  • How to trace changes in directories and files in windows using java.

    Hi,
    Want to know how to trace changes in directories and files in windows using java.
    I need to create a java procedure that keeps track of any changes done in any directory and its files on a windows System and save this data.
    Edited by: shruti.ggn on Mar 20, 2009 1:56 AM

    chk out the bellow list,get the xml and make the procedure.....     
         Notes          
    1     Some of the similar software’s include HoneyBow, honeytrap, honeyC, captureHPC, honeymole, captureBAT, nepenthes.     
    2     Some of the other hacking software’s include keyloggers. Keyloggers are used for monitoring the keystrokes typed by the user so that we can get the info or passwords one is typing. Some of the keyloggers include remote monitoring capability, it means that we can send the remote file across the network to someone else and then we can monitor the key strokes of that remote pc. Some of the famous keyloggers include win-spy, real-spy, family keylogger and stealth spy.          
    3     Apart from theses tools mentioned above there are some more tools to include that are deepfreeze, Elcomsoft password cracking tools, Online DFS, StegAlyzer, Log analysis tools such as sawmill, etc.

  • Java swing tree view interact with indesign javascript

    i have java swing tree view(program).if i execute my program it will all indesign script folder files in tree view. what is my problem is if i click the script
    i want to execute. is it possible to execute indesign javascrpt from java swing UI. could anyone tell me pls.

    Sorry if I did not make this clear:
    This is not an InDesign issue but a Java issue. Search, or ask in a Java forum for best practice to deal with the mentioned platform specific mechanisms:
    - inter process communication (AppleEvent or TLB/OLE )
    - command line / shell script invokation
    - a way to launch an JSX script - the equivalent mechanism to File.execute() in Extendscript.
    For example, if I ask Google for "Java TLB", the second hit takes me to:
    http://dev.eclipse.org/newslists/news.eclipse.tools/msg09883.html
    Eventually you can reuse the DLL and jar - I haven't read that far.
    Google for Java AppleEvent:
    http://developer.apple.com/samplecode/AppleEvent_Send_and_Receive/listing2.html
    Note the 1999 copyright, this is pre-OSX. Also located in a "legacy documents" area. Apple has the bad habit to deprecate/abandon most of their technology every other year, so I would not be surprised if it does not work any more and you'd have to write you own JNI, JDirect or JNIDirect glue ( I don't even know the current buzzword). Ah, further digging unveiled that they even dropped the successor which was named "CocoaJava".
    If Mac specific, maybe post your questions to this list: http://lists.apple.com/mailman/listinfo/java-dev
    Dirk

  • How do we create self-signed certificate using java packages

    Hi All,
    I require some information on creating self-signed certificate using java packages.
    The java.security.cert.* package allows you to read Certificates from an existing store or a file etc. but there is no way to generate one afresh. See CertificateFactory and Certificate classes. Even after loading a certificate you cannot regenerate some of its fields to embed the new public key &#8211; and hence regenerate the fingerprints etc. &#8211; and mention a new DN. Essentially, I see no way from java to self-sign a certificate that embeds a public key that I have already generated.
    I want to do the equivalent of &#8216;keytool &#8211;selfcert&#8217; from java code. Please note that I am not trying to do this by using the keytool command line option &#8211; it is always a bad choice to execute external process from the java code &#8211; but if no other ways are found then I have to fall back on it.
    Regards,
    Chandra

    I require some information on creating self-signed certificate using java packages. Its not possible because JCE/JCA doesn't have implementation of X509Certificate. For that you have to use any other JCE Provider e.g. BouncyCastle, IAIK, Assembla and etc.
    I'm giving you sample code for producing self-signed certificate using IAIK JCE. Note that IAIK JCE is not free. But you can use BouncyCastle its open source and free.
    **Generating and Initialising the Public and Private Keys*/
      public KeyPair generateKeys() throws Exception
          //1 - Key Pair Generated [Public and Private Key]
          m_objkeypairgen = KeyPairGenerator.getInstance("RSA");
          m_objkeypair = m_objkeypairgen.generateKeyPair();
          System.out.println("Key Pair Generated....");
          //Returns Both Keys [Public and Private]*/
          return m_objkeypair;
    /**Generating and Initialising the Self Signed Certificate*/
      public X509Certificate generateSSCert() throws Exception
        //Creates Instance of X509 Certificate
        m_objX509 = new X509Certificate();
        //Creatting Calender Instance
        GregorianCalendar obj_date = new GregorianCalendar();
        Name obj_issuer = new Name();
        obj_issuer.addRDN(ObjectID.country, "CountryName");
        obj_issuer.addRDN(ObjectID.organization ,"CompanyName");
        obj_issuer.addRDN(ObjectID.organizationalUnit ,"Deptt");
        obj_issuer.addRDN(ObjectID.commonName ,"Valid CA Name");
        //Self Signed Certificate
        m_objX509.setIssuerDN(obj_issuer); // Sets Issuer Info:
        m_objX509.setSubjectDN(obj_issuer); // Sets Subjects Info:
        m_objX509.setSerialNumber(BigInteger.valueOf(0x1234L));
        m_objX509.setPublicKey(m_objkeypair.getPublic());// Sets Public Key
        m_objX509.setValidNotBefore(obj_date.getTime()); //Sets Starting Date
        obj_date.add(Calendar.MONTH, 6); //Extending the Date [Cert Validation Period (6-Months)]
        m_objX509.setValidNotAfter(obj_date.getTime()); //Sets Ending Date [Expiration Date]
        //Signing Certificate With SHA-1 and RSA
        m_objX509.sign(AlgorithmID.sha1WithRSAEncryption, m_objkeypair.getPrivate()); // JCE doesn't have that specific implementation so that why we need any //other provider e.g. BouncyCastle, IAIK and etc.
        System.out.println("Start Certificate....................................");
        System.out.println(m_objX509.toString());
        System.out.println("End Certificate......................................");
        //Returns Self Signed Certificate.
        return m_objX509;
      //****************************************************************

  • Is It Possible to store an entire  file in database using java?

    Hi All,
    I am new to Programming. please help he out Is It Possible to store an entire file in database using java? is possible, can u tell me the way to make this success? Thank you in advance.

    Thanks PhHein
    i got that application. i stored one file in db, and i displayed that in browser. thank u very much.

  • Unable to locate existing  file from unix using java program

    Hi
    I have created a file in unix using java program, file.createNewFile();
    And when i try to search for the same file using file.exists() it is returning false. Paths are correct. Can anybody help me out.
    Thanks & Regards,
    Prasanth

    In Linux FC5 using JDK1.6, this code         File temp = new File(System.getProperty("user.home") + "/abcdefghijklmn");
            System.out.println(temp.createNewFile());prints 'true' and the file is created with length zero.

  • Creating a sample report using JAVA SDK

    Hi,
    I am trying to create a sample report using JAVA SDK.
    I slelect 4 "free cells" and pass 4 different strings to it.
    I even slelect the font colour and size. When i run the class and try to view the report in Infoview, I only seeblank blocks without any data. Now if I edit the report from infoview, and save the changes, I am able to see the data.
    My issue is, Why am I not able to see the data when I run the java code.
    Please find teh code below.
    package com;
    import java.awt.Color;
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import com.businessobjects.rebean.wi.BinaryView;
    import com.businessobjects.rebean.wi.DataProvider;
    import com.businessobjects.rebean.wi.DataProviders;
    import com.businessobjects.rebean.wi.DataSource;
    import com.businessobjects.rebean.wi.DataSourceObject;
    import com.businessobjects.rebean.wi.DocumentInstance;
    import com.businessobjects.rebean.wi.DocumentLocaleType;
    import com.businessobjects.rebean.wi.FontImpl;
    import com.businessobjects.rebean.wi.FreeCell;
    import com.businessobjects.rebean.wi.HTMLView;
    import com.businessobjects.rebean.wi.OutputFormatType;
    import com.businessobjects.rebean.wi.PageHeaderFooter;
    import com.businessobjects.rebean.wi.Query;
    import com.businessobjects.rebean.wi.Recordset;
    import com.businessobjects.rebean.wi.Report;
    import com.businessobjects.rebean.wi.ReportBody;
    import com.businessobjects.rebean.wi.ReportCell;
    import com.businessobjects.rebean.wi.ReportContainer;
    import com.businessobjects.rebean.wi.ReportElement;
    import com.businessobjects.rebean.wi.ReportEngine;
    import com.crystaldecisions.sdk.framework.CrystalEnterprise;
    import com.crystaldecisions.sdk.framework.IEnterpriseSession;
    import com.crystaldecisions.sdk.framework.ISessionMgr;
    import com.crystaldecisions.sdk.occa.infostore.IInfoObject;
    import com.crystaldecisions.sdk.occa.infostore.IInfoObjects;
    import com.crystaldecisions.sdk.occa.infostore.IInfoStore;
    import com.crystaldecisions.sdk.plugin.CeKind;
    public class Aug7th {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              String CMS = "pundl8136:6400";
              String userID = "srivas";
              String password = "morcom123";
              String auth = "secEnterprise";
              List<String> entire =new ArrayList<String>();
              List<String> country =new ArrayList<String>();
              List<String> resort =new ArrayList<String>();
              IEnterpriseSession enterpriseSession;
              try
                   ISessionMgr mySessionMgr = CrystalEnterprise.getSessionMgr();
                   enterpriseSession = mySessionMgr.logon(userID, password, CMS,auth);
                   if (enterpriseSession != null)
                   {//Create and store useful objects for the session.
                        IInfoStore iStore = (IInfoStore)enterpriseSession.getService("InfoStore");
                        ReportEngine reportEngine = (ReportEngine)enterpriseSession.getService("WebiReportEngine");
                        IInfoObject infoView = null;
                        String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS WHERE (SI_KIND = '"+CeKind.WEBI+"' OR SI_KIND='FullClient') " +
                        "AND SI_INSTANCE = 'false' AND SI_NAME='Structure Test_001_Java' ORDER BY SI_NAME ASC ";
                        //String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS ORDER BY SI_NAME ASC ";
                        IInfoObjects objInfoObjectsWIDs = (IInfoObjects) iStore.query(str);
                        System.out.println(objInfoObjectsWIDs.size());
                        IInfoObject objInfoObjectWID = (IInfoObject) objInfoObjectsWIDs.get(0);
                        DocumentInstance doc = reportEngine.openDocument(objInfoObjectWID.getID());
                        DataProviders dps = doc.getDataProviders();
    //                     Retrieve the 1st data provider
                        DataProvider dp = dps.getItem(0);
    //                     Retrieve the universe objects
                        DataSource ds = dp.getDataSource ();
                        Query q = dp.getQuery();
                        Recordset rs = dp.getResult(0);
    //                     0: assume query has one flow
                        rs.first();
    //                     Print the column types. They can be Integer, String,
    //                     or Date.
                        for (int i = 0; i < rs.getColumnCount(); i++) {
                        Class c = rs.getColumnType(i);
                        StringBuffer sbt = new StringBuffer();
                        if ( c.equals(Integer.class) )
                        sbt.append("Integer");
                        if ( c.equals(String.class) )
                        sbt.append("String");
                        if ( c.equals(Date.class) )
                        sbt.append("Date");
                        sbt.append(";");
                        System.out.println(sbt.toString());
                        System.out.println(rs.getColumnCount());
                        while (!rs.isLast()) {
    //                          column names
                             StringBuffer sbn = new StringBuffer();
                             StringBuffer sbd = new StringBuffer();
                             for (int j = 0; j < rs.getColumnCount(); j++) {
                             sbn.append( rs.getColumnName(j).toString() );
                             sbn.append(";");
                             System.out.println("sbn "+sbn.toString());
    //                          data
                             for (int k= 0; k< rs.getColumnCount(); k++) {
                             sbd.append( rs.getCellObject(k).toString() );
                             sbd.append(";");
                             entire.add(rs.getCellObject(k).toString());
                             System.out.println("sbd "+sbd.toString());
                             rs.next();
                        System.out.println(entire.size());
                        for(int i=0;i<entire.size();i++){
                             country.add(entire.get(i));
                             i++;
                             System.out.println("entireList "+entire.get(i));
                             resort.add(entire.get(i));
                        DataSourceObject city = ds.getClasses().getChildByName("Country");
                        DataSourceObject resorts = ds.getClasses().getChildAt(1);
                        dp.runQuery();
                        ReportContainer report = doc.createReport("Resort");
                        PageHeaderFooter header = report.getPageHeader();
                        FreeCell headerCell = header.createFreeCell("Resort Report");
                        PageHeaderFooter footer = report.getPageFooter();
                        FreeCell footerCell = footer.createFreeCell("Report Ends");
                        ReportBody body =  report.createReportBody();
                        for(int k=0;k<resort.size();k++){
                        FreeCell res=body.createFreeCell(resort.get(k));
                        res.getAttachTo();
                        res.setHeight(15d);
                        res.setWidth(30d);
                        Color c = new Color(255,255,255);
                        Color c1 = new Color(255,0,0);
                        FontImpl fnt = (FontImpl)res.getFont();
                        fnt.getDecoration().setTextColor(c1);
                        res.setFont(fnt);
                        //res.deleteAttachment();
                        //res.setAttachTo(body,VAnchorType.BOTTOM,HAnchorType.NONE);
                        doc.applyFormat();
                        doc.refresh();
                        final String l_docToken = doc.getStorageToken();
                        final DocumentInstance l_docToSave = reportEngine.getDocumentFromStorageToken(l_docToken);
                        doc.saveAs("mor31",835,null,null);
                        doc.closeDocument();
                        str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS WHERE (SI_KIND = '"+CeKind.WEBI+"' OR SI_KIND='FullClient') " +
                        "AND SI_INSTANCE = 'false' AND SI_NAME='mor31' ORDER BY SI_NAME ASC ";
                        //String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS ORDER BY SI_NAME ASC ";
                        objInfoObjectsWIDs = (IInfoObjects) iStore.query(str);
                        System.out.println(objInfoObjectsWIDs.size());
                        objInfoObjectWID = (IInfoObject) objInfoObjectsWIDs.get(0);
                        DocumentInstance doc1 = reportEngine.openDocument(objInfoObjectWID.getID());
                        String token = doc1.getStorageToken();
                        DocumentInstance doc2 = reportEngine.getDocumentFromStorageToken(token);
                        doc2.saveAs("123123", 835, null, null);
                   //     doc.refresh();
                        //doc.save();
                   enterpriseSession.logoff();
              catch(Exception e)
                   e.printStackTrace();

    duplicate post:
    Sample report using JAVA SDK

  • Open a PDF file in linux using java

    Hi..
    How can I open a PDF file in linux using java.
    I am able to open PDF in windows and mac using this code
    in Windows
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path_of_PDF);
    in mac
    Runtime.getRuntime().exec("open " + path_of_PDF);
    But nothing is working with linux.
    Please help
    Thanks

    One thread is enough:
    http://forum.java.sun.com/thread.jspa?threadID=5267458

  • Open PDF file in linux using java

    Hi..
    How can I open a PDF file in linux using java.
    I am able to open PDF in windows and mac using this code
    in Windows
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path_of_PDF);
    in mac
    Runtime.getRuntime().exec("open " + path_of_PDF);
    But nothing is working with linux.
    Please help
    Thanks

    appi wrote:
    Hi.. I found the JDIC binary files. There are different binaries for all the plateform. Is there any solution which is independent of plateform.Yes, and we already told you: Use JDK6, which has those libraries built into the standard class library.
    How can I use these binaries in my existing project. does it work, If I place them at same place where other .class files are kept.Read the documentation of the JDIC project. I'm sure they answer this question in their FAQ.

  • How to create a packet by using java?

    Hi, i am currently working on a research and i have some problems here.
    1) how to create a packet by using java programming ?
    2) How can i set the packet's information (e.g: packet's length, size of its header, etc) by using java?
    I am currently in a midst of this now and i hope that someone is willing to correspond to my questions and help me out of it.
    Thank you!

    I wan to create a customize packet where the user can
    define the header size, the packet's length etc. in
    the program......Then you get to write it to the connection yourself. Look at the OutputStream classes to see how to write low level output to a connection.

  • Create PDF Application Form Using Java

    Hi
    can Any one help me regarding how to create PDF Application from using java . That application should be doing the action events also.
    Message was edited by:
    helloshiva

    Check these pdf libraries:
    http://www.java-tips.org/java-libraries/pdf-library/

  • File to JDBC using JAVA Mapping

    Hello,
      Can u explain me about the above scenario of File to JDBC using JAVA Mapping.
       Iam new to XI explain above in detail.
    *Points will be Rewarded*
    Thanks&Regards,
    RavichandKone.

    HI,
    If your mapping is one to one then dont go for java mapping use graphical mapping.
    /people/sap.user72/blog/2005/06/01/file-to-jdbc-adapter-using-sap-xi-30 --> for jdbc receiver: file -JDBC
    Here are the link which will help you in writing the stored procedure:
    Receiver JDBC scenario MS access - /people/sameer.shadab/blog/2005/10/24/connecting-to-ms-access-using-receiver-jdbc-adapter-without-dsn
    Stored Procedures-
    /people/siva.maranani/blog/2005/05/21/jdbc-stored-procedures
    http://www.ics.com/support/docs/dx/1.5/tut6.html
    /people/sriram.vasudevan3/blog/2005/02/14/calling-stored-procs-in-maxdb-using-sap-xi
    http://www.ics.com/support/docs/dx/1.5/tut6.html
    http://java.sun.com/docs/books/tutorial/jdbc/basics/sql.html
    http://www.sqlteam.com/article/stored-procedures-an-overview
    thnx
    Chirag Gohil

  • Convert XML file into DTD using Java

    Hi All,
    I want to do convert the xml file into DTD using Java.
    I read the DOM package but didnt get clear idea.
    Anyone of you have an idea please share the coding with me.
    Any suggestions greatly appreciated.
    Thanks
    Veera

    Hi All,
    I want to do convert the xml file into DTD using Java.
    I read the DOM package but didnt get clear idea.
    Anyone of you have an idea please share the coding with me.
    Any suggestions greatly appreciated.
    Thanks
    Veera

  • How to view file from vss using java Commandline

    Hi To ALL,
    I wanted to view a file from vss through java code.
    By using the folowing code,i could able to get vss file in to local folder.
    Runtime.getRuntime().exec
    ("cmd /c ss Get $/Mywork/Myfile.java -GLC:/New");
    But i wanted to view file from vss using java code.
    any one please help me..
    Thanks in advance.........

    As always, Google is your friend.
    Follow the bouncing link.
    http://www.google.com/search?hl=en&q=VisualSourceSafe+%2B+Java+API
    PS.

  • How to extract .sit files(in MAC)  using java program

    Hi,
    please help me , i want to simple program for
    " how to extract .sit files(in MAC) using java program"
    that sit files same as zip files in windows..[                                                                                                                                                                                                                                                                                                                                   

    Thanks for reply...
    but i search in the google about this topic...there is no results will appear..
    the problem is "i have to run program in the MacOS like extract all the
    .sit(StuffIt) extension files. These sit files same as zip files in the windows... we have one tool called StuffIt Expander but it is 3rd party tool. but here requirement is i have to write my own program to extract all the files same as zip file program...
    please do the needful..i am waiting for ur reply,,,

Maybe you are looking for

  • Getting nested data in the datagrid

    If my xml is in the form of multiple nested "nodes?" then how can i go about serilizing them and retrieving them properly? Example, if my xml looked like this: <data> <value>value1</value> <value>value2</value> <value>value3</value> </data> then disp

  • Can we print header text in a tabular format

    Hi, In the below program i need the text type payment history in a proper format.so plz help me regarding this. this a just a test program,you just execute this program.its running. i am feching the text payment history using the function module READ

  • Same Document type, Different number ranges

    All SAP Gurus, I want to assign  Different number based on movement types, but the problem is that both the number ranges (101 for purchase order and 122 return delivery to vendor) are having the same document type (WE). Is it possible to assign diff

  • Smartforms:Can i call a Tcod from Driver Prg 4 its o/p 2 be appended

    Hello Smartform Gurus I need 2 call 1 tcode from my Driver prog ,which has report o/p that is 2 be appended in my Smartform o/p as a appended page . Is it possible at all ? plz throw some light on this . thnx Moni

  • Keywords and naming photos

    I know this has been asked before but I'm still searching for a solution. My fiancee and I are both photographers and we take thousands of photos for our business and I'm still trying to find the best workflow to minimise work and time wasted. At the