Sorting contents of a JTREE

Hi all..
I have a Jtree that needs to be sorted. How can it do it fast and efficiently as the size of the tree can be huge. I have the tree contents that has depth of max 4 or 5. Your help on this is greatly appreciated.
Thanks
Srivarun

Hi there ..
You can sort the tree by again recreating the tree nodes.
  DefaultMutableTreeNode oldNodes = (DefaultMutableTreeNode)tree.getModel().getRoot();
  DefaultMutableTreeNode newNodes = new DefaultMutableTreeNode(oldNodes.getUserObject());
  void visitNodes(DefaultMutableTreeNode oldNodes,DefaultMutableTreeNode newNodes ){
    Vector sorted = sort(oldNodes.children());
    for (int i = 0; i < sorted.size(); i++)
      DefaultMutableTreeNode chNode = new DefaultMutableTreeNode(sorted.get(i));
      newNodes.add(chNode);
      visitNodes((DefaultMutableTreeNode)sorted.get(i),chNode);
  tree = new Tree(newNodes);hope this would help!
or you can also checkout the thread .. http://forum.java.sun.com/thread.jsp?forum=57&thread=189640
Regards,
Asim

Similar Messages

  • Sorting the raws of JTree

    How do i sort the raws which are there in one JTree. But here we have added JTree in JTable. And i want to sort the values of JTree depending on the click of the column of the JTable.

    There is already a topic on this subject
    http://forum.java.sun.com/thread.jsp?forum=57&thread=563889&tstart=45&trange=15
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • Sorting Content with PersonalizationAdvisor session bean

    Hi,
    I am working on content selection through the PersonalizationAdvisor session
    bean not the jsp tags. Content selection is going on fine with my meta tags,
    but whenever I try to sort on any of the fields of the WLCS_DOCUMENT it does
    nothing. No errors are returned but the result set is not sorted.
    I tried sorting on different fields but no hope. I suspect that the names I
    am using my be incorrect.
    For sorting on the MODIFIED_DATE column of the table I use the string
    "modifiedDate ASC" in my ContentQueryAdviceRequest. Similarly
    "createionDate", "author", "size"
    I tied sorting by any of my meta tags but again it didn't work. I was
    wondering if these are the correct names, and if they are any idea why the
    sorting is not working.
    I am using
    Weblogic Server 5.1 with sp1
    WLCS 2.0.1 with sp1
    Any help is greatly appreciated.
    May

    Got it thanks
    "May AbdelRazik" <[email protected]> wrote in message
    news:[email protected]..
    Hi,
    I am working on content selection through the PersonalizationAdvisorsession
    bean not the jsp tags. Content selection is going on fine with my metatags,
    but whenever I try to sort on any of the fields of the WLCS_DOCUMENT itdoes
    nothing. No errors are returned but the result set is not sorted.
    I tried sorting on different fields but no hope. I suspect that the namesI
    am using my be incorrect.
    For sorting on the MODIFIED_DATE column of the table I use the string
    "modifiedDate ASC" in my ContentQueryAdviceRequest. Similarly
    "createionDate", "author", "size"
    I tied sorting by any of my meta tags but again it didn't work. I was
    wondering if these are the correct names, and if they are any idea why the
    sorting is not working.
    I am using
    Weblogic Server 5.1 with sp1
    WLCS 2.0.1 with sp1
    Any help is greatly appreciated.
    May

  • Query and sort content from two lists using search API

    Hi,
    I have a custom web part which I would like to query two different lists and sort the results by Created Date. One is a list of news articles and the other contains blogs. So basically the result set will be an intermix of news and blog items sorted by date.
    I would also like to do this by query through the search API. Does anybody have any sample code to do this?
    thanks,
    Sherazad.
    Sherazad

    Hi Sherazad:
    To use the JOIN operator in CAML, your lists must have a
    defined relation(Lookup column). You can refer to sample code that I list as follow.
    Create your query from one of your lists.
    SPList Projects= SPContext.Current.Site.RootWeb.Lists["Projects"];
    SPQuery query = new SPQuery();
    To do the join, setquery.Joins
     <Join Type="INNER" ListAlias="Contacts">
        <Eq>
            <FieldRef Name="ProjectManager" RefType="ID" /> ///
    ProjectManager is a Lookup Column.
            <FieldRef List="Contacts" Name="ID" />
        </Eq>
     </Join>
    And query.ProjectedFields (To tell SharePoint how to project the lookup columns into the result)
    <Field Name="Project Name" Type="Lookup" List="Projects" ShowField="Title">
    /// My Project Name is a Display Name in Memory so you can give a name by yourself But ShowField must be Internal Name of the Column(Project Name)
    You can add a lot of columns that you want to display.
    Everything comes from memory.
    To choose the fields to display set query.ViewFields
    <FieldRef Name="Your Internal Name of Column Or
    ProjectedFields - Field Name">
    <FieldRef Name="Your Internal Name of Column Or
    ProjectedFields - Field Name">
    <FieldRef Name="Your Internal Name of Column Or
    ProjectedFields - Field Name"> 
    Then
    SPListItemCollection result = ListA.GetItems(query);

  • How can I sort content into a-z of album titles

    Hi Everyone
    Hope someone out there can help.  I run two libraries on one pc at home, in library one I have the album icon view and I click on "Album" at the top and my albums are organised a to z by album title.  However in library two, I cannot get itunes to do this, I have the same album icon view i click on "Album" on the top bar and it organises my albums a-z by artists name.  I cannot see what I am doing wrong in library two.  Any advise will be most welcome.
    regards
    Anniemaca

    You're welcome, and you too.
    tt2

  • JTree - changed content, refresh

    Hello,
    I have a problem in my program I can`t solve...
    basically I am using drop-down menu with different drives (c:, d:, etc.). Don`t ask me why I don`t use the JTree to display all the drives, I simply need to display each drive separately.
    when I select the drive, JTree pops up with the content of the drive.
    Problem comes in, when the JTree is already displayed and I go into my drop-down menu to select a different drive.... Everything seems to work fine in background.... The tree gets build up, I just somehow cannot update (or refresh) the screen....
    did anyone experienced similar problem?
    thank you
    Otakar

    No, I am not using TreeModel.. Let me post the code... I am using 3 different files:
    MainModule.java
    DetectDrives.java
    FileSystem.java
    I think You might wanna see the ChoiceListener in MainModule
    thank you for you time
    MainModule.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.*;
    import java.awt.event.*;
    public class MainModule{
         private JFrame aFrame;         // BASE frame
         private JPanel driveListPane;
         private JList  driveList;
         // MENU Bar Components
         private JMenuBar aMenuBar;
         private JMenu fileMenu, editMenu, viewMenu, settingsMenu, helpMenu;
         private JMenuItem newMenuItem, openMenuItem, saveMenuItem,                // FILE menu Items
                                           saveAsMenuItem, exitMenuItem,                     //
                                           selectDriveMenuItem, selectOutputMenuItem;        // SETTINGS menu Items
          // ComboBox
         private JComboBox aComboBox;
          // Buttons
         private JButton selectDriveButton, printButton;
         // Listeners
         private PrintButtonListener prtListener;
         private ChoiceListener choiceListener;
         // Labels
         private JLabel sourceLabel, label1, label2;
         private int listRows;
         public static String drive;
         private DetectDrives dd;
         private FileSystem fs;
         private int ct;
         /*============ CONSTRUCTOR ===========================================================\
         |
         public MainModule(){
             ct = 0;
              // create a MAIN WINDOW (Frame)
              drive = new String("C:\\");
              aFrame = new JFrame("Otax Drive Printer 0.99b");
              aFrame.setSize(800, 600);
              aFrame.setLocation(100, 50);
              aFrame.getContentPane().setLayout(null);
              aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // create the categories in a menu bar
              aMenuBar = new JMenuBar();
              fileMenu = new JMenu("File");
              editMenu = new JMenu("Edit");
              viewMenu = new JMenu("View");
              settingsMenu = new JMenu("Settings");
              helpMenu = new JMenu("Help");
              // create menu items for FILE menu
              newMenuItem = new JMenuItem("New", 'N');
              openMenuItem = new JMenuItem( "Open", 'O');
              saveMenuItem = new JMenuItem( "Save", 'S' );
                     saveAsMenuItem = new JMenuItem( "Save As", 'A');
                     exitMenuItem = new JMenuItem("Exit", 'E');
              // create menu items for SETTINGS menu
                     selectDriveMenuItem = new JMenuItem("Select Drive", 'D');
                     selectOutputMenuItem = new JMenuItem("Select Output", 'O');
              // detect drives mounted to system and put them into JComboBox
              dd = new DetectDrives();
              aComboBox = new JComboBox(dd.detectCdDrives());
              aComboBox.setBounds(100, 5, 180, 20);
              //create labels
              sourceLabel = new JLabel("Select Source:");
              sourceLabel.setBounds(6, 4, 90, 20);
                     label1 = new JLabel("Current Drive: ");
              label1.setBounds(2, 500, 90, 20);
              label2 = new JLabel();
              label2.setBounds(85, 500, 50, 20);
              //create buttons
              printButton = new JButton("Print");
              printButton.setBounds(2, 50, 101, 16);
                     //create Accelerators for FILE MenuItems
                     newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_N, InputEvent.CTRL_MASK, false));
              saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_S, InputEvent.CTRL_MASK, false));
              //create the action listeners (listener definitions bellow)
              prtListener = new PrintButtonListener();
              choiceListener = new ChoiceListener();
              //connect the action listeners with menu items
              printButton.addActionListener(prtListener);
              aComboBox.addActionListener(choiceListener);
         // LISTENERS Definitions start HERE ====================================
         public class PrintButtonListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   System.out.println("print action performed: " + drive);
         public class ChoiceListener implements ActionListener{
             public void actionPerformed( ActionEvent e)
                  ct++;
                  System.out.println(ct + " event started");
               String drive = new String(aComboBox.getSelectedItem().toString().substring(0,2));
               label2.setText(drive);
               fs = new FileSystem(drive + "//");
               fs.sortFiles();
               fs.addNodes(drive);
               DefaultMutableTreeNode top = fs.getNodes();
               JTree tree = new JTree(top);
               tree.setBounds(10, 30, 500, 450);
                  aFrame.getContentPane().add(tree);
               aFrame.repaint();
         public void addComponents(){
              aMenuBar.add(fileMenu);        // create menu
              aMenuBar.add(editMenu);
              aMenuBar.add(settingsMenu);
              aMenuBar.add(helpMenu);
              fileMenu.add(newMenuItem);     //add items to the FILE menu
              fileMenu.add(openMenuItem);
              fileMenu.addSeparator();
              fileMenu.add(saveMenuItem);
                     fileMenu.add(saveAsMenuItem);
                     fileMenu.addSeparator();
                     fileMenu.add(exitMenuItem);
              settingsMenu.add(selectDriveMenuItem);
              settingsMenu.add(selectOutputMenuItem);
              aFrame.setJMenuBar(aMenuBar);
              aFrame.getContentPane().add(aComboBox);
              aFrame.getContentPane().add(sourceLabel);
              aFrame.getContentPane().add(label1);
              aFrame.getContentPane().add(label2);
              aFrame.setVisible(true);
         public static void main(String [] args){
              MainModule m1 = new MainModule();
              m1.addComponents();
    DetectDrives.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.filechooser.*;
    public class DetectDrives{
         private FileSystemView fsv;
         private File[] roots;
         private Vector drives;
         /*======== CONSTRUCTOR =====================================================================\
         |Purpose: To INITIALIZE the object                                                          |
         |Variables: (FileSystemView) fsv - creates the Object containing info about current system  |
         |           (File[]) roots - array used to store all drives currently mounted to system     |
         |           (Vector) drives - vector used for storage of selected info about drives         |
           \==========================================================================================*/
         public DetectDrives(){
              drives = new Vector(0,1); // *Create empty Vector(0) with expansion capacity (1)
              //--- Get a FileSystemView object for the current system
             fsv = FileSystemView.getFileSystemView();
            //--- Get an array of File objects describing the 'roots' attached to the system
              roots = File.listRoots();
         /*SD1)==== Method detectCdDrives() ========================================================\
         |Purpose: To SCAN the system for any drives mounted and add DRIVE LETTER and DRIVE NAME    |
         |         to a Vector. It Also CHECKS if drive CONTAINS any DATA or if it`s EMPTY.         |
         |Variables: (int) i - a loop iterator                                                      |
         |           (String) cdInfo - temporary storage for drive information during drive check   |
         |           (Vector) drives - storage for driveletter and drive name for all drives        |
         |                             This Vector is returned upon function call                   |
         public Vector detectCdDrives(){
              String cdInfo;
              //SCAN system and RETRIEVE drives
              for(int i = 0; i < roots.length; i++){
                   if((fsv.getSystemDisplayName(roots)).equals("")) //--FIND OUT if any DATA on DRIVE
                        cdInfo = fsv.getSystemTypeDescription(roots[i]) + " ";
                   else
                   cdInfo = fsv.getSystemDisplayName(roots[i]);
                   drives.addElement(roots[i].getPath() + " " + cdInfo.substring(0, cdInfo.length()-5));
              return drives;
    FileSystem.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.io.File;
    import java.io.*;
    import java.util.Vector;
    public class FileSystem{
         private String driveLetter;
         private Vector root;
         private Vector dirs;
         private Vector files;
         private File dir;
         private File [] allFiles;
         private DefaultMutableTreeNode top;
         /*================= File System Constructor ================================\
         |Purpose: To initialize the conject and to accept drive letter selected in  |
         |         main module                                                       |
         public FileSystem(String dl){
              driveLetter = dl;
        /*================= Method: sortFiles() ====================================\
         |Purpose: To sort content of selected drive, directories (alphabetically),  |
         |         followed by files (alphabeticaly)                                 |
         public void sortFiles(){
              dir = new File (driveLetter);
              allFiles = dir.listFiles();
              root  = new Vector(2,1);
              dirs  = new Vector(0,1);
             files = new Vector(0,1);
             //---- Separate Directories and Files into 2 different vectors
             for(int i = 0; i < allFiles.length; i++){
                   if(allFiles.isDirectory())
                   dirs.add(allFiles[i]);
                   else
                   files.add(allFiles[i]);
              //---- Add elements from dirs and files Vectors into root vector
              for(int i = 0; i < dirs.size(); i++){
                   root.add(dirs.elementAt(i));
              for(int i = 0; i < files.size(); i++){
                   root.add(files.elementAt(i));
    /*================= Method: addNodes() =====================================\
         |Purpose: to build the file structure which will be used to create the tree |
         |Variables: drive = used to accept the drive letter representing the root |
         | top = primary (root) node in the structure) |
    | root = vector of all files in the drive |
         public void addNodes(String drive){
              top = new DefaultMutableTreeNode(drive);
              DefaultMutableTreeNode node = null;
              for(int i = 0; i < root.size(); i++){
                   node = new DefaultMutableTreeNode(root.elementAt(i));
                   top.add(node);
    /*================= Method: getNodes() =====================================\
         |Purpose: To return variable top, which holds the files structure and will |
         | be used to build the tree |
    public DefaultMutableTreeNode getNodes(){
              return top;

  • SORT statement is not working!

    Hi frdz,
    Below SORT statement is not working. Can any one explain me why this is happening.
    SORT i_bseg ASCENDING BY belnr bukrs
                        DESCENDING kunnr.
    I have table content as below.
    BELNR      BUKRS KUNNR   
    0016000000|CROP |         
    0016000000|CROP |0008910168
    Before and after the sort content order is same.
    I want to sort the content like below.
    0016000000|CROP |0008910168
    0016000000|CROP |       
    Is there any thing wrong with the sort statement???
    i_bseg is defined as TYPE STANDARD TABLE OF
    Sort criteria must not change i. e ascending by belnr and bukrs and descending by kunnr.
    Thanks,
    Vinod.

    hi vinod,
    this is because on your statement, you are sorting BUKRS in descending order and KUNNR in ASCENDING order.
    please take note that the sort order should come after the sorted field. if no order is given, the default which is ASCENDING will be used.
    do your sorting like this
    SORT i_bseg BY belnr bukrs kunnr DESCENDING.
    regards,
    Peter

  • Dynamically Updating Content Server Portlets

    [urlHi, I am currently having difficulty dynamically updating content server portlets.  I have a portlet of the following form:[/url]
    ArticleName Author Title Date mystory author1 title1 04/05/01
    story2 author2 title2 06/07/04
    story author3 title3 01/02/03
    So I have this table where each one of the line items is an article in the content server. So, for example the first line item is an article "mystory" by "author1", with title "title1" and date "04/05/01" additionally there is an article text field, but this isn't displayed unless I click on the article name.
    I can set up the basics of this portlet, but when I try to add any real functionality I run into one of two problems.
    First Problem: Passing Information
    I cannot find a way to pass information between content portlets. For instance, if the user would like to "re-sort" this table based on "date", I would like to have the user click on the "date" column heading and then reload the page. To do so, I would have to pass the section name back to the page so that it could resort based on this data. I have not found anyway to effectively pass information to a content server portlet. I am building these pages through use of the presentation template framework (so I can have access to the content items) but that seems to change the way portlets are handled.
    I got around this limitation with a regular portlet by creating an intermediary page which captures passed information and stores it to the session state. Once the information was in the session state, it is accessible to the portlet on the first page. However, this only works because remote portlets do not change their session id once loaded. Content Server portlets, on the other hand, change their session id after every reload of the browser or page change. I can send information from a content server portlet to an intermediary page, but I cannot send it back to the portlet because the session id has changed so I have no idea of knowing where to send the information. I can write it to a session state, but by the time I return to the portal page, the content server has changed its session id so it does not know where to look any longer.
    I suppose it would be possible to create an application state variable and append it with some static token (if there is some static variable per portal session) but I would rather not have to deal with application variables if at all possible.
    Second Problem: Dynamically Updating PCS Tags
    Even if I were able to the pass information back to my content server portlet, I run into another issue. The easiest way to sort content server items is using the filter command in the pcs:foreach tag. So, if I wanted to sort by author name, I could do something like the following <pcs:foreach var="item" expr="filter(folderByName('content'), filtered.name == '"name")" or something like that (the syntax may be incorrect, I just wrote this off the top of my head). However, it appears that the way the presentation templates are compiled goes in the order of PCS tags THEN JSP. So I would have no way of dynamically changing the variable on which I sort. For example, if I clicked on "Date" above in my table, I would like to be able to dynamically change my code so that I sort on date, and not name. I cannot find a solution to this problem.
    My workaround is to use the pcs tags to write out all the possible sortings to java array objects. This gives me access to the data on a JSP level and based on whatever the user will chose, I could then display that array. While this works, it is extremely ghetto and inefficient. Any help or suggestions would be fantastic.
    Thanks a lot,
    Jason Grauel

    You can use just about any javascript you want in any Content Server presentation template including ones that are used for portlets.
    However, you should be careful to name javascript functions and global variables uniquely so that they do not conflict with any other javascript on the page. To do this, you can append the item id to function and variable names, for example,
    function doSomething<pcs:value expr="pcs_id"></pcs:value>() {
    return true;
    Randy

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • My friend wanted me to help him sort his bookmarks. I put them in alphebetical order. He decided he wanted them put back in "date added" order...

    I've found a workaround and now his bookmarks are back in order by date added, but they are reversed, i.e., the last bookmark is at the top.
    For those wanting the workaround (as I see this question was never properly answered) I opened "Show all Bookmarks", clicked on Bookmarks Menu, and View, Sort, and Sort by Added.
    Then highlighted all his bookmarks, and copied.
    Then created a new folder in the Bookmarks Menu, and pasted to that new folder.
    I then created another folder and did it again as a backup, and deleted all his bookmarks in alphabetical order, then opened one of the folders I just made, copied the bookmarks and pasted them into the Bookmarks Menu.
    (I made that extra folder just in case things didn't go as planned. He would have understandably freaked out had I deleted all his bookmarks without making another backup of them! After I saw that everything was cool, I deleted the extra folder.)
    But still the order is reversed.
    How do I reverse the reversed order?

    I am trying to think how your friends bookmarks came to be in a different order permanently and how you may be able to reverse that.
    I note you have been copying bookmark folders. You have already discovered that the sort orders used to display may be varied and that second clicks toggle the order to be ascending or descending. If you copy a bookmark folder contents they retain the order that they were sorted on in the display when copied.
    So if you have a folder. The bookmarks are in the order in which they were added. You may however display them in Alphabetical or reverse alphabetical order or reverse of the order added etc.
    '''Try this I hope it will work'''
    #Obviously back up the bookmarks first.
    # In the bookmarks library re-sort the folder book marks menu.
    # Create a new folder.
    # Copy that the resorted bookmarks to the new folder.
    # Delete the mis-sorted content and copy the new content over it

  • Customizing JTree Nodes ImageIcons???

    I have a JTree. Iam trying to customize the icons of it instead of the defaulticons available for leaf and branch nodes.I successfully set a new icon for leaf nodes by calling setLeafIcon.Also i can use setOpenIcon and setClosedIcon for the expanded and closed branches.
    But in my application when my GUI is launched i actually set the JTree in its fully expansion form.
    so there is no difference between setOpenICon and setClosedIcon as all of them are expanded.so how do i differentiate between the two and set different icons for both of them.
    exmaple:Cricket club is my root node..I have for ex:ABC , BCD, and CDE club underneath that(branch nodes).Under each club i have player1,player2, player3. .etc..so i want to set 3 different icons,,one for cricket club, 2nd for ABC,BCD andCDE clubs and 3rd one for players.since my JTree is expanded the same icon is set for CricketClub(root Node) and ABC,BCD and CDE club(branch nodes)..How can iset different icons to these. can anyone help me on this..I am sort of new to JTree.So code snippet will be a welcome..
    Thanks Much in advance

    To fully expand the tree, use the method scrollPathToVisible(TreePath path). The path is the path for your tree's last node. The DefaultMutableTreeNode class should have some methods to find the path for a particular node.
    To set the icons for a particular node, depending on their opened or closed state, Make a subclass of TreeCellRenderer. If you look at the API for TreeCellRenderer, you will see that it will tell you if the current node is expanded, selected, leaf, hasfocus, etc...
    If you want to set an open icon for an expanded node, just check if it is expanded. Cast the Object value to a DefaultMutableTreeNode and set the Icon for it, unless you have your own class for your nodes. Lastly, set your renderer for your JTree with setCellRenderer(TreeCellRenderer ren). I hope this helps.

  • How to replace original JTree node with + and - sign or icon??

    Dear friends:
    I have following code for JTree:
    import java.awt.BorderLayout;
    import java.awt.Container;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    public class TreeSample {
      public static void main(String args[]) {
        JFrame f = new JFrame("JTree Sample");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = f.getContentPane();
        JTree tree = new JTree();
        JScrollPane scrollPane = new JScrollPane(tree);
        content.add(scrollPane, BorderLayout.CENTER);
        f.setSize(300, 200);
        f.setVisible(true);
    }Here, when I click any node to explore its children, right handle pointer become down handle Pointer, but if I hope to change this right handle pointer to + sign or icon; and to change this down handle pointer to - sign or icon; how to do it, ??
    Is there any simplest way instead of using ImageIcon ????
    Thanks
    sunny

    You have to use Windows look and feel instead of Java look and feel.
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

  • Thunar: incorrect sort order

    Hello, everyone.
    Guys, maybe any of you encountered with that problem in Thunar... especially if you use cyrillic letters in file or folder names.
    I have the latest version of Thunar (1.4.0) installed, and it turns out it incorrectly sorts contents of folders.
    I can not even understand the way Thunar sorts contents of any folder.
    Here is the contents of one folder "sorted" by name (ascending).
    Looking from top to bottom I see file names starting with...
    cyrillic upper letters
    digits
    cyrillic lower letters
    again digits
    again cyrillic lower letters
    english lower letters
    and again cyrillic lower letters
    Concrete example of another folder "sorted" by name:
    голубь.txt
    иволга.txt
    аист.txt
    орёл.txt
    сова.txt
    Absoluletly wrong order. The file with name that starts with 'A' is in the middle.
    Cyrillic alpabet is:
    Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ ЬЬ Ыы ЪЪ Ээ Юю Яя
    Meanwhile
    ls -1
    gives right order
    аист.txt
    голубь.txt
    иволга.txt
    орёл.txt
    сова.txt
    PCManFM and other filemanagers give right sort order.
    So, Thunar DOES NOT sort with 'ls'. Also, sort order of Thunar CAN NOT be changed using LC_COLLATE.
    Thunar uses its own "mega-wise" algorithm.
    P.S.
    By the way, before version 1.4.0, everything was OK in Thunar. So one day their devs decided to make some "improvements".
    Last edited by BrainWorker (2012-08-14 02:28:35)

    BrainWorker wrote:
    AaronBP wrote:They notice because they are in the CC list. Whenever a new comment comes in they get an email. You should not open a new bug if there's already one open about it.
    I don't really care if they are going to complain about it or not. My goal is to make them pay attention to this bug, because I think it is nicely forgotten.
    This is open source, bro. You can't make anybody do anything, but you might encourage some admin to ban you if you willfully break rules. If you can't break open the source and fix the problem yourself (which is surely the most speedy solution!), you're better off following community procedures and being as helpful as possible. Otherwise you'll just be excluded and ignored.

  • JTree: Problems updating the nodes size

    Hi,
    I'm trying to update the content of a JTree and I wonder how it
    really works, since the paint() method doesn't seem to call the
    renderer.
    My situation: Imagine a JPanel splited in two by a JSplitPane. In
    the left is the tree. Each node in the tree shows two panels, one
    aligned to the left, and another to the right. I need that the panel
    containing the two use all the available space in the left part of the
    Split panel.
    My solution: I pass the left JPanel to the tree renderer, so that
    it can get the width from it (inside the
    getTreeCellRendererComponent()) to build the return JPanel with the
    correct size. My logic is that since each time you move the JSplitPane
    the JTree paint() method is invoked the renderer can return the
    correct JPanel with the correct size that will be painted then in the
    screen.
    My problem: Doens't work. When I render the tree, the renderer is
    invoked, but it doesn't change its size (I can change the color based on the width, but not the node size). Only when I collapse & expand a node, it correctly takes into account the .setPreferredSize() and returns the JPanel with the correct size.
    The only way I found to update the tree involves to catch the
    JSplitPane event and call updateUI() in the tree, something that, I
    think, it's certainly not the correct way to do it.
    Any explanation of why this doesn't work would be really great. Any
    pointer to a web resource explaining in deep how Swing components work (specially the JTree) would be a godsend.
    Thanks,
    - Juancho

    My situation: Imagine a JPanel splited in two by a JSplitPane. Got it.
    In the left is the tree. In the left side of the JSplitPane is a JTree.
    Each node in the tree shows two panels,Maybe... on the right side of the JSplitPane are two Panels in which the data depends on which node is selected in the JTree???
    Maybe... you have a custom TreeCellRenderer which displays a pair of panels in place of the standard JLabel???
    one aligned to the left, and another to the right. To the left of what??? To the right of what???
    I need that the panel containing the two use all the available
    space in the left part of the Split panel.Panel containing the two what??? I thought the left part of the SplitPanel contained a JTree???

  • Unable to refresh JTree

    Hi!
    I am using a TreeModel to manage the content of a JTree.
    I provide buttons to add/remove items in the tree. The content is correctly modified (when I do some System.out.println(...)), but I don't see the new items on my displayed tree.
    I tried to use
    JTree.revalidate();
    JTree.repaint();
    And the same on the panel containing the JTree, nothing works!
    What should I do?
    Thanks a lot
    Choub

    Hi,
    you can try with this sample code:
    * <p>Adds a new objects in the JTree. </p>
    * @param parent - the DefaultMutableTreeNode parent
    * @param child - the object to add
    * @param shouldBeVisible - if it is true, all the path components in path
    * are expanded and scrolls so that the
    * node identified by the path is displayed.
    * @return a DefaultMutableTreeNode object
    * @see javax.swing.tree.DefaultMutableTreeNode
    public DefaultMutableTreeNode addObject( DefaultMutableTreeNode parent,
    Object child,
    boolean shouldBeVisible) {
    DefaultMutableTreeNode childNode = null;
    switch ( this.levelSelected ) {
    case 0: childNode = new DefaultMutableTreeNode(
    new IconData( rm.getIcon("db/Computer.gif"), child ) );
    break;
    case 1: childNode = new DefaultMutableTreeNode(
    new IconData( rm.getIcon("db/BCard.gif"), child ) );
    break;
    case 2: childNode = new DefaultMutableTreeNode(
    new IconData( rm.getIcon("db/Thread.gif"), child ) );
    break;
    if ( null == childNode )
    return null;
    if ( null == parent ) {
    parent = root;
    model.insertNodeInto( childNode, parent, parent.getChildCount() );
    model.reload();
    if ( shouldBeVisible ) {
    logicTree.scrollPathToVisible( new TreePath( childNode.getPath() ) );
    return childNode;
    Regards.

Maybe you are looking for