How to get the path when i select a directory or a file in a JTree

How to get the path when i select a directory or a file in a JTree

import java.lang.*;
import java.io.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.HeadlessException;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Iterator;
* @author Frederic FOURGEOT
* @version 1.0
public class JTreeFolder extends JPanel {
protected DefaultMutableTreeNode racine;
JTree tree;
protected JScrollPane scrollpane;
final static int MAX_LEVEL = 1; // niveau max de descente "direct" dans l'arborescence
* Sous-classe FSNode
* @author Frederic FOURGEOT
* @version 1.0
private class FSNode extends DefaultMutableTreeNode {
File file; // contient le fichier li� au noeud
* Constructeur non visible
private FSNode() {
super();
* Constructeur par initialisation
* @param userObject Object
FSNode(Object userObject) {
super(userObject);
* Constructeur par initialisation
* @param userObject Object
* @param newFile File
FSNode(Object userObject, File newFile) {
super(userObject);
file = newFile;
* Definit le fichier lie au noeud
* @param newFile File
public void setFile(File newFile) {
file = newFile;
* Renvoi le fichier lie au noeud
* @return File
public File getFile() {
return file;
public JTree getJTree(){
     return tree ;
* Constructeur
* @throws HeadlessException
public JTreeFolder() throws HeadlessException {
File[] drive;
tree = new JTree();
// cr�ation du noeud sup�rieur
racine = new DefaultMutableTreeNode("Poste de travail");
// cr�ation d'un noeud pour chaque lecteur
drive = File.listRoots();
for (int i = 0 ; i < drive.length ; i++) {
FSNode node = new FSNode(drive, drive[i]);
addFolder(drive[i], node); // on descend dans l'arborescence du lecteur jusqu'� MAX_LEVEL
racine.add(node);
// Gestion d'evenement sur JTree (on �coute les evenements TreeExpansion)
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeExpanded(TreeExpansionEvent e) {
// lorsqu'un noeud est ouvert
// on descend dans l'arborescence du noeud jusqu'� MAX_LEVEL
TreePath path = e.getPath();
FSNode node = (FSNode)path.getLastPathComponent();
addFolder(node);
((DefaultTreeModel)tree.getModel()).reload(node); // on recharche uniquement le noeud
public void treeCollapsed(TreeExpansionEvent e) {
// lorsqu'un noeud est referm�
//RIEN
// alimentation du JTree
DefaultTreeModel model = new DefaultTreeModel(racine);
tree.setModel(model);
     setLayout(null);
// ajout du JTree au formulaire
tree.setBounds(0, 0, 240, 290);
scrollpane = new JScrollPane(tree);
     add(scrollpane);
     scrollpane.setBounds(0, 0, 240, 290);
* Recuperation des sous-elements d'un repertoire
* @param driveOrDir
* @param node
public void addFolder(File driveOrDir, DefaultMutableTreeNode node) {
setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
addFolder(driveOrDir, node, 0);
setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
* Recuperation des sous-elements d'un repertoire
* (avec niveau pour r�cursivit� et arr�t sur MAX_LEVEL)
* @param driveOrDir File
* @param node DefaultMutableTreeNode
* @param level int
private void addFolder(File driveOrDir, DefaultMutableTreeNode node, int level) {
File[] fileList;
fileList = driveOrDir.listFiles();
if (fileList != null) {
sortFiles(fileList); // on tri les elements
// on ne cherche pas plus loin que le niveau maximal d�finit
if (level > MAX_LEVEL - 1) {return;}
// pour chaque �l�ment
try {
for (int i = 0; i < fileList.length; i++) {
// en fonction du type d'�l�ment
if (fileList[i].isDirectory()) {
// si c'est un r�pertoire on cr�� un nouveau noeud
FSNode dir = new FSNode(fileList[i].getName(), fileList[i]);
node.add(dir);
// on recherche les �l�ments (r�cursivit�)
addFolder(fileList[i], dir, ++level);
if (fileList[i].isFile()) {
// si c'est un fichier on ajoute l'�l�ment au noeud
node.add(new FSNode(fileList[i].getName(), fileList[i]));
catch (NullPointerException e) {
// rien
* Recuperation des sous-elements d'un noeud
* @param node
public void addFolder(FSNode node) {
setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
for (int i = 0 ; i < node.getChildCount() ; i++) {
addFolder(((FSNode)node.getChildAt(i)).getFile(), (FSNode)node.getChildAt(i));
setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
* Tri une liste de fichier
* @param listFile
public void sortFiles(File[] listFile) {
triRapide(listFile, 0, listFile.length - 1);
* QuickSort : Partition
* @param listFile
* @param deb
* @param fin
* @return
private int partition(File[] listFile, int deb, int fin) {
int compt = deb;
File pivot = listFile[deb];
int i = deb - 1;
int j = fin + 1;
while (true) {
do {
j--;
} while (listFile[j].getName().compareToIgnoreCase(pivot.getName()) > 0);
do {
i++;
} while (listFile[i].getName().compareToIgnoreCase(pivot.getName()) < 0);
if (i < j) {
echanger(listFile, i, j);
} else {
return j;
* Tri rapide : quick sort
* @param listFile
* @param deb
* @param fin
private void triRapide(File[] listFile, int deb, int fin) {
if (deb < fin) {
int positionPivot = partition(listFile, deb, fin);
triRapide(listFile, deb, positionPivot);
triRapide(listFile, positionPivot + 1, fin);
* QuickSort : echanger
* @param listFile
* @param posa
* @param posb
private void echanger(File[] listFile, int posa, int posb) {
File tmpFile = listFile[posa];
listFile[posa] = listFile[posb];
listFile[posb] = tmpFile;

Similar Messages

  • I use iPhoto and want to know how to get the 'key photo' i select on my MacBook Pro to be the one that gets used on my iPhone when i sync them. Any ideas? also, i want the events to appear in the order i choose on my MacBook too

    I use iPhoto and want to know how to get the 'key photo' i select on my McBook Pro to be the same one that gets used on my iPhone 5s when i sync. i also want the events to appear on the iPhone in the same order i have them on my macbook. any ideas there too?

    Killerfinch wrote:
    My new yahoo account nestles comfortably in iCloud on the mine iPad.
    No, your Yahoo account is not in iCloud (which only handles iCloud mail), it is in Yahoo, and the Yahoo mail account is on your iPad.
    But the MacBook Pro will have none of it! I write this question now as I fear that I will be totally demented very soon and unable to formulate my thoughts clearly!
    Get the correct settings for your account from Yahoo and set it up manually.
    By the way, I also find the "password" issue problematical. It seems Apple want my Apple password rather than my eMail password. All very confusing.
    That would depend on what you are trying to do.

  • How to get the values from html:select? tag..?

    i tried with this, but its not working...
    <html:select styleClass="text" name="querydefs" property="shortcut"
                 onchange="retrieveOptions()" styleId="firstBox" indexed="true">
    <html:options collection="advanced.choices" property="shortcut" labelProperty="label" />
    </html:select>
                        <td align="left" class="rowcolor1">
                        <script language="javascript" type="text/javascript">
                              function retrieveOptions(){
                             var sel = document.querydefs.options;
                             var selectedOption = sel[sel.selectedIndex].value;
                             document.write(selectedOption);
                           </script>

    <td align="left" class="rowcolor1">
                        <script language="javascript" type="text/javascript">
                              function retrieveOptions(){
                             var sel = document.querydefs.options;
                             var selectedOption = sel[sel.selectedIndex].value;
                             document.write(selectedOption);
                           </script>This java script is not working at all..its not printing anything in document.write();
    This is code..
    <td class="rowcolor1" width="20%">
    <html:select styleClass="text" name="querydefs" property="shortcut"
                             onchange="retrieveSecondOptions()" styleId="firstBox"
                             indexed="true">
                             <html:options collection="advanced.choices" property="shortcut"
                                  labelProperty="label"  />
                        </html:select>i tried with this also. but no use..i'm not the getting the seleced option...
    function retrieveOptions(){
    firstBox = document.getElementById('firstBox');
                             if(firstBox.selectedIndex==0){
          return;
        selectedOption = firstBox.options[firstBox.selectedIndex].value;
    }actually , how to get the values from <html:select> ...?
    my idea is to know which value is selected from the combo box(<html:select> ) if that value is equal some string i have enable a hyperlink to open a popup window

  • How to get the Path of the WebDynpro page

    Hi All,
    Can any one say how to get the path of the JSPDynPage ina Portlet in Portal Application.
    Becoz i have to display that Page in another JSPDynPagee
    Thanks in Advance....

    Hi,
    You can call your JSPDynPage component by calling the URL as:
    http://localhost:50000/irj/servlet/prt/portal/prtroot/YourApplicationName.YourComponentName
    Check this:
    Calling portal component
    Greetings,
    Praveen Gudapati
    [Points are welcome for helpful answers]

  • How to get the path of the image stored in sap??

    Hi All
    The problem is
    While making an entry in standard there is a field called documents through which we attach our images in sap.
    How to get the path of the image stored with the corresponding order so that the image can be displayed while we are creating a report.
    I know how to upload the image while creating a report using docking control.
    I am not able to get the path of the image stored...
    Please Help
    Thanks in advance..
    Pooja

    I am not aware of exactly which tables are used for storing the attached doc. details, but we have worked in the similar requiremnent.
    What you can do is .... before uploading the image to any order, try swich on the SQL trace ST05 and after upload switch off.
    The log will display what are the tables involved while storing the image. And you can easily find out the image location.

  • How 2 get the path of a file

    how 2 get the path of a file Using jsp
    i have tried getPath...but i'm geting the error
    The method getPath(String) is undefined for the type HttpServletRequest
    any idea how 2 get the path of a file

    You need ServletContext#getRealPath().
    API documentation: http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

  • How 2 get the path of a file Using jsp

    how 2 get the path of a file Using jsp
    i have tried getPath...but i'm geting the error
    The method getPath(String) is undefined for the type HttpServletRequest
    any idea how 2 get the path of a file

    You need ServletContext#getRealPath().
    API documentation: http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

  • How to get the tab when is it pressed?

    I have the following situation:
    I have an array of JTextField inside a scroollpane. The size of my array is nine or ten depends on some rules. But my window show just four JTextField. So I would like to know how to get the event when I press "tab", just to show the others JTextField while I'm pressing "tab". Because I need this event to scrooll down or scrooll up.
    I tried the keylistener, but when I press "tab" any method(keypressed, keyreleased, keytyped) is called.
    I also tried the focuslistener. If this event I could scrooll down or scrooll up, but I couldn't do both!!
    Can somebody help me??
    Thanks anyway!!
    Gin

    JTextField implements Scrollable interface, which provides information to the enclosing container such as JScrollPane.
    Hence when the tab event is fired, you can compute the Rectangle area that should be visible and then call the 'scrollRectToVisible()' method in JTextField. This will inform the JScrollPane to scroll to the rectangle that you mention.
    HTH

  • How to get the source code of an HTML page in Text file Through J2EE

    How to get the source code of an HTML page in Text file Through J2EE?

    Huh? If you want something like your browser's "view source" command, simply use a URLConnection and read in the data from the URL in question. If the HTML page is instead locally on your machine, use a FileInputStream. There's no magic invovled either way.
    - Saish

  • How to get the source code of an HTML page in Text file Through java?

    How to get the source code of an HTML page in Text file Through java?
    I am coding an application.one module of that application is given below:
    The first part of the application is to connect our application to the existing HTML form.
    This module would make a connection with the HTML page. The HTML page contains the coding for the Form with various elements. The form may be a simple form with one or two fields or a complex one like the form for registering for a new Bank Account or new email account.
    The module will first connect through the HTML page and will fetch the HTML code into a Text File so that the code can be further processed.
    Could any body provide coding hint for that

    You're welcome. How about awarding them duke stars?
    edit: cheers!

  • How to get the path of the selected Jtree node for deletion purpose

    I had one Jtree which show the file structure of the system now i want to get the functionality like when i right click on the node , it should be delete and the file also deleted from my system, for that how can i get the path of that component
    i had used
    TreePath path = tree.getPathForLocation(loc.x, loc.y);
    but it gives the array of objects as (from sop)=> [My Computer, C:\, C:\ANT_HOME, C:\ANT_HOME\lib, C:\ANT_HOME\lib\ant-1.7.0.pom.md5]
    i want its last path element how can i get it ?

    Call getLastSelectedPathComponent() on the tree.

  • How to get the path of the folder?

    hello everybody,
    I want to retrive the path of folder. how can i do? i used File I/O > Adv file fun > File dialog and set the file dialog property to "Folder". but I cannot get the path included with folder name. Can somebody help me? thanks in advance..

    Did you select "File or Folder" for the file dialog?
    and
    Did you click on the Current Folder button when selecting the folder?
    R
    Message Edited by JoeLabView on 09-03-2008 07:56 AM
    Attachments:
    fileFolder.PNG ‏11 KB
    currentFolder.PNG ‏6 KB

  • How to get the Path of the Current File using Import & Export File -Reg.

    Dear all,
    I have a mega (big) doubt. I have manually inserted the Figures from the figure folders. Now i need, fully automated. So How can I get the Figure path
    Example :
    PMString path = "E://development/Figures/";
    now i checked, How many subFolders is there in "path", get the All Subfolders and check to the Article Name.
    Example
    Article Name == subFolder name then get the Files from the SubFolders(E://development/Figures/ChapterF/*.eps files").
    now I paste the Document using to For Loop.
    Please any one can suggest me, How can We get the Path in SDK.
    Note:
    Should I have to create the relative path by myself?
    No method supplied in SDK to do this directly?
    Please I need a help of this Query as soon as posible.
    Thanks & Regards
    T.R.Harihara SudhaN

    http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/input_file.asp?frame=true
    When a file is uploaded, the file name is also submitted. The path of the file is available only to the machine within the Local Machine security zone. The value property returns only the file name to machines outside the Local Machine security zone. See About URL Security Zones for more information on security zones.
    i need to know on how to get the compelete path /directory of the filename
    using <input type="file"> tag You can't. Its a security thing.
    is there any other way to get an input file from a local host aside from <input type="file"> tag?No. Not using just html.
    You could always go into activex components, but thats different again.
    Cheers,
    evnafets

  • How to get the path of input type="file" tag

    -- im using <input type="file"> tag to get an input file from a local host, it returns only the filename but not the complete path of the filename,,,
    -- i need to know on how to get the compelete path /directory of the filename using <input type="file"> tag , or is there any other way to get an input file from a local host aside from <input type="file"> tag?
    thanks

    http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/input_file.asp?frame=true
    When a file is uploaded, the file name is also submitted. The path of the file is available only to the machine within the Local Machine security zone. The value property returns only the file name to machines outside the Local Machine security zone. See About URL Security Zones for more information on security zones.
    i need to know on how to get the compelete path /directory of the filename
    using <input type="file"> tag You can't. Its a security thing.
    is there any other way to get an input file from a local host aside from <input type="file"> tag?No. Not using just html.
    You could always go into activex components, but thats different again.
    Cheers,
    evnafets

  • How to get the folder name of selected subitem in tree structure?

    Hi All,
               I created a tree structure like below.
             ->Folder1-- 1
                              2
                              3
            ->Folder2-----1
                               2
                               3
                    i.e i have two folders & each folder having the values like above.Now i want to perform some action by clicking on the any of the values.Suppose if i click value 2,i want to do some action.the actions need to perform is varies from floder to to folder.
            So How can i get the folder name of clicked Value?
    Regards,
    Ravi

    Hi Kumar ,
    the below code should help you.
    Register the below action for the leaf node for which u need the subfolder's name above it.
    Worked fine in my system ...hope it does in ur scenario too
    method ONACTIONGET_PATH .
      data : lr_element TYPE REF TO if_wd_context_element,
             lr_node TYPE REF TO if_wd_context_node,
             ls_path type string,
             ls_path_node TYPE string,
             lt_string type TABLE OF string,
             l_lines type i,
             l_lines_1 TYPE i.
      lr_element = wdevent->get_context_element( 'CONTEXT_ELEMENT' ).
    **-> getting the path of the node/leaf
    *which  u had clicked and from that getting the node above it
      ls_path = lr_element->get_path( ).
      SPLIT ls_path at '.' into table lt_string.
    -> remove the first 2 entries as they will contain the view name
      DELETE lt_string FROM 1 to 2.
      l_lines = LINES( lt_String ).
      l_lines_1 = l_lines - 1.
    -> remove the last 2 entries as they will contain the element in the path
      DELETE lt_string  from l_lines_1 to l_lines.
      LOOP AT lt_string into ls_path.
        CONCATENATE LINES OF LT_STRING into ls_path_node SEPARATED BY '.'.
      ENDLOOP.
    **-> getting access to the node above the leaf element
    LR_NODE = WD_CONTEXT->PATH_GET_NODE( path = ls_path_node ).
    lr_element = lr_node->get_element( ).
    **-> Getting the name of the folder...
    *here path is the attribute in my context which stores the name of the folder
    lr_element->get_attribute( EXPORTING name = 'PATH' IMPORTING value = ls_path ).
    endmethod.

Maybe you are looking for

  • Problem with Checkbox and Button components....(Simple one)

    Hi all,           As I am new to flash and ActionScript 3.0,I have the following issue regarding Flash.           I have 2 swf files whose contents are as follows: First.swf file contains a check-box (instance name:my_checkbox).    Second.swf file co

  • Downloaded PDF file on front end is not opening

    Hi, We have a requirement to open the Master Data Governance documents (which are stored as RAWSTRING in a DB table) from an ALV on double click. We are downloading the binary content(converting XSTRING to BINARY) as a file with appropriate extension

  • Mat****a DVD-RAM-841S - Failure and disappeared icon - Code 19

    Hi. I am hoping some one can help asap as its a massive problem. I turned my A series dual core laptop on to find no DVD drive present, no icons, and nothing working. So i checked the device drivers to find this problem: *Windows cannot start this ha

  • Determining audio files and corresponding slide # in Presenter

    It is a big challenge to edit audio files.  Presenter does not sequentially number audio files, they appear to be random.  Which means you have to hunt and peck to find the correct audio file to edit for the appropriate slide.  Any fix for this?

  • 24 bit audio not playing in Quicktime

    I have captured some video through an a Matrox MXO2 in Adobe Premiere CS6 and end up with 24 bit PCM audio in my .mov files that can't be played back in Quicktime player or any other Quicktime based application.  This happens regardless of the codec