JTree properties

Hi all!
I guess this is a simple problem for most of you guys... How to change color of the lines in JTree that connect opened nodes? I guess there must be some property like "JTree.lineColor" because this color changes with changing LookAndFeel. I have read the tutarial and it only says that these properties are in the file <java_install_dir>/lib/swing.properties. But I don't have this file.
If I find the name of this property, should I set it with UIManager.put(property_name, Color.whatever)?
Another question:
is there any way to remove those handles on other nodes not only the root node (with setShowRootHandles)?
Thanx
Petar

For the line use, before creating the tree:
UIManager.put("Tree.line", Color.red); for example.
If you want to see all the properties, use this code :
import java.util.*;
import javax.swing.*;
public class UIProperties {
     public static String windowsUI = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
     public static void main(String[] args) {
          try {
          //     UIManager.setLookAndFeel(windowsUI);
               UIDefaults def = UIManager.getDefaults();
               for (Enumeration e = def.keys(); e.hasMoreElements();) {
                    String key = (String)e.nextElement();
                    System.out.println(key+ "     :     "+def.get(key));
          catch (Exception ex) {
               System.out.println(ex);
}I hope this helps,
Denis

Similar Messages

  • How to dynamically add Nodes to JTree?

    How to add nodes to a Jtree by getting the information into a specific file
    For example, in JList:
    DefaultListModel workgroups;
    workgroups = new DefaultListModel();
    List<String> workgroupsList = new ArrayList<String>();
    workgroupsList = ParserUtils.getWorkgroupList(ParserUtils.getConfigPath() + "\\.workgroup.properties");
    if (!workgroupsList.isEmpty()){
         for (String workgroup : workgroupsList){
              workgroups.addElement(workgroup.toString().trim());
    workgroupList = new JList(workgroups); //adds the list workgroupsThe output of this will be a JList displaying the list of workgroups per line. The list could be found in a file name "workgroup.properties"
    Question is, is it possible to adapt this same method in JTree. The information per line will serve as one node in the tree. For example, I have 3 workgroups in the list, there will also be 3 nodes to be found in the tree.
    Any suggestions?
    THanks.

    There's a huge JTree example in the Swing tutorial. It's a bit of a beast to use.

  • How to expand a JTree depending on a property

    Hi I have a JTree that needs to be expandAll if a property in the ini file is true. Can some tell me how I can do it or give me an example. If needed i can post my code. Here the addtreeDisplays() has to expandAll depending on a string(true ).
    Can some help me out.
    Thanks,
    public class TreeDisplayPanel extends JPanel implements QMRequestListener,
                                                            TopologySelectionListener,
                                                                          PropertyChangeListener
        /** Creates new TreeDisplayPanel */
        //Key to get from property file
        String _treeKey = "tree.display.type";
        //default display
        public final static int TREE_DISPLAY = 0;
        public final static int STAR_DISPLAY = 1;
        public final static int BOTH_DISPLAY =2;
         Properties _displayProp = null;
        //Main panel where everything gets put on to be displayed
        public JPanel _mainDisplayPanel;
        //current default display
        private int treeDisplayPreference = STAR_DISPLAY;
        private MQETabbedPane _treeTabPane;
        private MQETabbedPane _viewTabPane;
        private String treeDisplayTitle;
         static private final String treeviewKey = "tree.view.text";
         static private final String starviewKey = "star.view.text";
         static private final String splitviewKey = "split.view.text";
         static private final String mergeviewKey = "merge.view.text";
         // Default tree displays.
         private HyperbolicTreePanel hyperbolicTreePanel = null;
         private NavigatorTreePanel navigatorTreePanel = null;
         // A store for any queue manager tree displays created
         // by the user. This will enable these trees to be
         // modified whenever the user invokes a expand/collapse
         // all action on a node or whenever the user changes
         // the leaf node expansion preference.
         private Vector<NavigatorTreePanel> qmgrTreeDisplays =
            new Vector<NavigatorTreePanel>();
         //HashMap of indexes correspond to indexes in tabbed paned that are merged, it contains
        //hashtables of components in those merged indexes
        HashMap _qmMergedIndexes = new HashMap();
        //Current listeners to this panel on node selections
        protected Vector<TopologySelectionListener> _tsListeners =
            new Vector<TopologySelectionListener>();
         private TopologyModel m_model = null;
         private TopologyModelNode m_nnode = null;
         private TopologyDisplayPanel tdp = null;
        public TreeDisplayPanel(TopologyModel model, Properties prop, String displayTitle) {
            super(new BorderLayout());
              m_model = model;
              _displayProp = prop;
              treeDisplayTitle = displayTitle;
            initComponent();
            initGui();
        private void initComponent()
              _mainDisplayPanel = ComponentFactory.getInstance().createTitledPanel(treeDisplayTitle);
              _mainDisplayPanel.setLayout(new BorderLayout());
              add(_mainDisplayPanel, BorderLayout.CENTER);
        private void initGui()
            if (_displayProp != null)
                   // Get the current display preference.
                   String defaultDisplay = Integer.toString(STAR_DISPLAY);
                treeDisplayPreference = Integer.parseInt(_displayProp.getProperty(_treeKey, defaultDisplay));
            try
                //Add according to your display property
                _treeTabPane = new MQETabbedPane();
                _viewTabPane = new MQETabbedPane(JTabbedPane.BOTTOM);
                _viewTabPane.addMouseListener(new MouseListener()
                    public void mouseClicked(MouseEvent e)
                        final int tabNum = _viewTabPane.getUI().tabForCoordinate(_viewTabPane,e.getX(),e.getY());
                        //Only if the mouse click is a right mouse and tab number is not on overview pane or doc pane is the popup valid
                        if (SwingUtilities.isRightMouseButton(e) && tabNum > 1)
                            final String tabStr = _viewTabPane.getTitleAt(tabNum);
                            JPopupMenu popup = new JPopupMenu();
                            JMenuItem menuItem1 = new JMenuItem(new AbstractAction("Close " + tabStr)
                                public void actionPerformed(ActionEvent e)
                                    //Remove it from our HashMap of merged panes if it exists
                                    if (_qmMergedIndexes.containsKey(tabStr))
                                        _qmMergedIndexes.remove(tabStr);
                                            // Remove the Qmgr tree display.
                                            NavigatorTreePanel treePanel = (NavigatorTreePanel)_viewTabPane.getComponentAt(tabNum);
                                            ExpandingModelNode model = (ExpandingModelNode)treePanel.getNavigatorTreeModel();
                                            model.getNode().removeTreeModelListener(model);
                                            qmgrTreeDisplays.remove(treePanel);
                                    _viewTabPane.removeTabAt(tabNum);
                                  String mergeview = StringFactory.getString(mergeviewKey);
                            JMenu merge = new JMenu(mergeview);
                            merge.setEnabled(false);
                            int numTabs = _viewTabPane.getTabCount();
                            //System.out.println("Num of tabs " + numTabs);
                            //Only allow merging if you have more then 2 panes (1 - Overview, 2 - Qmgr, 3-Qmgr....
                            //Also if the current pane is not a merge pane already
                            if (numTabs > 3 && !_qmMergedIndexes.containsKey(tabStr))
                                //Do not enable this menu if the number of already merged Indexes - the number of tabs
                                //is greater then two (One Valid pane + Overview pane). The reason is because then there is
                                //no valid pane to merge with
                                if ((numTabs - _qmMergedIndexes.size()) > 3)
                                    merge.setEnabled(true);
                                    for (int i = 2; i<numTabs; i++)
                                        //Add only valid tabs and not already merged tabs
                                        if (i != tabNum && !_qmMergedIndexes.containsKey(_viewTabPane.getTitleAt(i)))
                                            //JMenuItem mergeItem = new JMenuItem(new AbstractAction(_viewTabPane.getTitleAt(i))
                                                      JMenuItem mergeItem = new JMenuItem(new AbstractAction(_viewTabPane.getToolTipTextAt(i))
                                                public void actionPerformed(ActionEvent e)
                                                    try
                                                        //System.out.println("Action Name for " + e.getActionCommand());
                                                        //Work around for java bug in JTabbedPane
                                                        _viewTabPane.setSelectedIndex(0);
                                                        _viewTabPane.validate();
                                                        //End workaround
                                                        //Strip off the fully qualified name to contain only the name of the QM name
                                                                     String mergeTabName = m_model.getQMgrName(e.getActionCommand());
                                                                     JPanel splitPanel = new JPanel(new BorderLayout());
                                                        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
                                                        splitPane.setBorder(null);
                                                        splitPane.setOneTouchExpandable(true);
                                                        int mergeTabIndex =  _viewTabPane.indexOfTab(mergeTabName);
                                                        String mergeTabString = _viewTabPane.getTitleAt(mergeTabIndex);
                                                                     Component mergeComp = _viewTabPane.getComponentAt(mergeTabIndex);
                                                        String mergeCompAddress = _viewTabPane.getToolTipTextAt(mergeTabIndex);
                                                                     splitPane.setLeftComponent(mergeComp);
                                                                     int currentTabIndex =  _viewTabPane.indexOfTab(tabStr);
                                                        Component currentComp = _viewTabPane.getComponentAt(currentTabIndex);
                                                                     String currentCompAddress = _viewTabPane.getToolTipTextAt(currentTabIndex);
                                                        splitPane.setRightComponent(currentComp);
                                                        splitPanel.add(splitPane, BorderLayout.CENTER);
                                                        String mergeName = mergeTabName + "/" + tabStr;
                                                                     String toolTipName = mergeCompAddress + " | " + currentCompAddress;
                                                        //_viewTabPane.addTab(mergeName, splitPanel);
                                                                     addTabToDisplay(mergeName, toolTipName, splitPanel);
                                                        splitPane.setDividerLocation(.5);
                                                        int mergeIndex = _viewTabPane.indexOfTab(mergeName);
                                                                      if (mergeIndex != -1)
                                                            //_viewTabPane.setToolTipTextAt(mergeIndex, mergeName);
                                                                          //_viewTabPane.setSelectedIndex(mergeIndex);
                                                            //Now lets update our ongoing vector/hashmap
                                                            //Create a hash map with the current merged view
                                                            Hashtable mergeViews = new Hashtable();
                                                            mergeViews.put(mergeCompAddress,mergeComp);
                                                            mergeViews.put(currentCompAddress,currentComp);
                                                            _qmMergedIndexes.put(mergeName, mergeViews);
                                                    catch (Exception ex)
                                                        ex.printStackTrace();
                                            merge.add(mergeItem);
                                  String splitKey = StringFactory.getString(splitviewKey);
                            JMenu splitMenu = new JMenu(splitKey);
                            splitMenu.setEnabled(false);
                            //Only allow to split if the current tab has a merged view
                            if (_qmMergedIndexes.containsKey(tabStr))
                                splitMenu.setEnabled(true);
                                Hashtable mergeHash = (Hashtable)_qmMergedIndexes.get(tabStr);
                                Enumeration enumeration = mergeHash.keys();
                                while (enumeration.hasMoreElements())
                                    //Create a new menu item for each QM in View
                                    String node = (String)enumeration.nextElement();
                                    JMenuItem mergeItem = new JMenuItem(new AbstractAction(node)
                                        public void actionPerformed(ActionEvent e)
                                            //Work around for java bug in JTabbedPane
                                            _viewTabPane.setSelectedIndex(0);
                                            _viewTabPane.validate();
                                            //End workaround
                                            String splitTabName = e.getActionCommand();
                                            //Get the merge hash for this tab num
                                            Hashtable splitHash = (Hashtable)_qmMergedIndexes.get(tabStr);
                                            Enumeration enumeration = splitHash.keys();
                                            _viewTabPane.removeTabAt(tabNum);
                                                      int iIndexOfSplit = 0;
                                            while (enumeration.hasMoreElements())
                                                //Add new pane for the views in the hashtable
                                                String nodeAddress = (String)enumeration.nextElement();
                                                           String nodeName = m_model.getQMgrName(nodeAddress);
                                                           NavigatorTreePanel currentComp = (NavigatorTreePanel)splitHash.get(nodeAddress);
                                                addTabToDisplay(nodeName,nodeAddress,currentComp);
                                                           //Now if this tab this we just added is equal to the menu item of the split menu,
                                                           //store this so that we can give focus to it later
                                                           if (splitTabName.equals(nodeAddress))
                                                                iIndexOfSplit = _viewTabPane.getTabCount()-1;
                                            //Also remove it from our vector of merged tabs
                                            _qmMergedIndexes.remove(tabStr);
                                            //int mergeIndex = _viewTabPane.indexOfTab(splitTabName);
                                            //if (mergeIndex != -1)
                                                      if (iIndexOfSplit != -1)
                                                //_viewTabPane.setSelectedIndex(mergeIndex);
                                                           _viewTabPane.setSelectedIndex(iIndexOfSplit);
                                    splitMenu.add(mergeItem);
                            popup.add(menuItem1);
                            popup.add(merge);
                            popup.add(splitMenu);
                            if (popup != null)
                                Point p = e.getPoint();
                                popup.show((Component)e.getSource(), (int)p.getX(), (int)p.getY());
                    public void mouseEntered(MouseEvent e)
                    public void mouseExited(MouseEvent e)
                    public void mousePressed(MouseEvent e)
                    public void mouseReleased(MouseEvent e)
                   //Don't forget to add the tree's
                   addTreeDisplays();
                _viewTabPane.addTab(StringFactory.getString("perspective.display.overview.tab"), _treeTabPane);
                   _viewTabPane.addTab(StringFactory.getString("perspective.display.documentation.tab"), new DocDisplayPanel());
                _mainDisplayPanel.add(_viewTabPane, BorderLayout.CENTER);
            catch(Exception e)
                e.printStackTrace();
         private void addTabToDisplay(String nameStr, String toolStr, JComponent c)
              if (_viewTabPane == null)
                   return;
              _viewTabPane.addTab(nameStr, c);
              int tabNum = _viewTabPane.getTabCount()-1;
              if (toolStr != null)
                   _viewTabPane.setToolTipTextAt(tabNum, toolStr);
              _viewTabPane.setSelectedIndex(tabNum);
         private void addTreeDisplays()
              String starKey = StringFactory.getString(starviewKey);
              String treeKey = StringFactory.getString(treeviewKey);
              //navigatorTreePanel.expandTreePath(this, true);
              String test = MQEPreferencesDialog.getPreferenceValue("expand.leaf.startup");
              System.out.println("test{{{{{{{{{{"+test);
              //System.out.println("test{{{{{{{{{{"+m_nnode.);
              if (treeDisplayPreference == BOTH_DISPLAY)
                   hyperbolicTreePanel = new HyperbolicTreePanel(m_model);
                   hyperbolicTreePanel.addQMRequestListener(this);
                   hyperbolicTreePanel.addTopologySelectionListener(this);
                   //hyperbolicTreePanel.expandTreePath((TopologyModelNode)m_model.getRoot(), true);
                   //hyperbolicTreePanel.expandTreePath(m_nnode, true);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("staricon"), hyperbolicTreePanel, starKey);
                   navigatorTreePanel = new NavigatorTreePanel(m_model);
                   navigatorTreePanel.addQMRequestListener(this);
                   navigatorTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("treeicon"), navigatorTreePanel, treeKey);
              else if (treeDisplayPreference == TREE_DISPLAY)
                   navigatorTreePanel = new NavigatorTreePanel(m_model);
                   navigatorTreePanel.addQMRequestListener(this);
                   navigatorTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("treeicon"), navigatorTreePanel, treeKey);
              else
                   hyperbolicTreePanel = new HyperbolicTreePanel(m_model);
                   hyperbolicTreePanel.addQMRequestListener(this);
                   hyperbolicTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("staricon"), hyperbolicTreePanel, starKey);
        public void addTopologySelectionListener(TopologySelectionListener tsl)
            if (tsl != null)
                _tsListeners.add(tsl);
        public void removeTopologySelectionListener(TopologySelectionListener tsl)
            if (tsl != null)
                _tsListeners.remove(tsl);
        protected void fireTopologySelection(TopologyModelNode node)
            for (TopologySelectionListener tsl : _tsListeners)
                tsl.receiveTopologySelection(node);
       /* TopologySelectionListener methods                                     */
        public void receiveTopologySelection(TopologyModelNode node)
            //Since this panel can have multiple panels in it's current Tabbed display.
            //This class registers to each of the TopologyDisplayPanels as a listener for selections
            //This way no matter who is currently active, they will funnel the event to here and it this
            //panel will send the event on foward
            if (node != null)
                fireTopologySelection(node);
       /* QMRequestListener methods                                             */
        public void receiveQMRequest(TopologyModelNode node)
            //Check to see if this node is already in a Tab already
            System.out.println("Queue Manager request");
              boolean doesExist = false;
            int tabNum =0;
              //Fix for activity 00033248 TAB PANES FOR IDENTICAL QMANAGERS ON DIFF MACHINES
              //The only unique names are in the tooltips so lets just cycle through all the tabs
              //and search for this Queue Manager name.  Using indexOfTab in JTabbedPane will not
              //work here because it will return first location of a matching queue manager name, but
              //we could have multiple tabs open with same queue manager name.
              for (int i = 0; i < _viewTabPane.getTabCount();i++)
                   String toolTipStr = _viewTabPane.getToolTipTextAt(i);
                   //Using the string method for indexOf, covers us when we have a merged tab window
                   if ((toolTipStr != null) && (toolTipStr.indexOf(((ResourceProxy)node).getAddress().trim()) != -1))
                        //We already have existing queue manager tab open
                        doesExist = true;
                        tabNum = i;
                        break;
              if ( !doesExist)
                   //Create the tab
                NavigatorTreePanel treePanel = new NavigatorTreePanel(new ExpandingModelNode(node));
                treePanel.addTopologySelectionListener(this);
                   // Add the tree panel to a container so that it can be accessed
                   // for expand/collapse all and tree refresh actions.
                   qmgrTreeDisplays.add(treePanel);
                   //Fix for activity 00033248 TAB PANES FOR IDENTICAL QMANAGERS ON DIFF MACHINES
                   addTabToDisplay(((ResourceProxy)node).getName().trim(), ((ResourceProxy)node).getAddress().trim(), treePanel);
                node.getModel().expandNode(node);
              else
                   _viewTabPane.setSelectedIndex(tabNum);
       /* PropertyChangeListener methods                                        */
            public void propertyChange(PropertyChangeEvent evt){
              String propertyChanged = evt.getPropertyName();
              if (propertyChanged.equals(MQEDisplayPreferences.treeDisplayProperty)){
                   int newPreference = ((Integer)evt.getNewValue()).intValue();
                   changeTreeDisplays(newPreference);
              else if (propertyChanged.equals(MQEDisplayPreferences.expandLeafProperty)){
                   // The enable leaf node preference has changed so update the MQE
                   // tree displays according to the new preference setting.
                   refreshTreeDisplays();
              else{
                   // Ignore the property change event.
        * Changes the trees displayed by MQE according to
         * the preference set by the current user.
        * @param the new trees display preference.*/
         public void changeTreeDisplays(int preference)
              // Assign the new tree display preference.
              treeDisplayPreference = preference;
              // Recreate the tree display according
              // to the new preference.
              m_model.removeTreeModelListeners();
              _treeTabPane.removeAll();
              addTreeDisplays();
              refreshTreeDisplays();
        * Fully expands the Navigator display trees from the specified node.
        * @param the node from which each tree will be fully expanded.
         public void expandAll(TopologyModelNode node)
              node.expandAll();
              final TopologyModelNode fnode = node;
              Runnable doTask = new Runnable(){
                   public void run(){
                        // Fire a tree structure changed notification for
                        // the StarTree, (1) because it will not display
                        // tree nodes correctly without it and (2) it appears
                        // to be the only tree interested in doing anything
                        // with it!
                        fnode.fireTreeStructureChanged(TopologyModel.STRUCTURE_CHANGE);
                        if (hyperbolicTreePanel != null)
                             hyperbolicTreePanel.expand(fnode);
                        if (navigatorTreePanel != null)
                             navigatorTreePanel.expand(fnode);
                        for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                             navTreePanel.expand(fnode);
              SwingUtilities.invokeLater(doTask);
        * Fully collapses the Navigator display trees from the specified node.
        * @param the node from which each tree will be fully collapsed.
         public void collapseAll(TopologyModelNode node)
              final TopologyModelNode fnode = node;
              Runnable doTask = new Runnable(){
                   public void run(){
                        if (hyperbolicTreePanel != null)
                             hyperbolicTreePanel.collapse(fnode);
                        if (navigatorTreePanel != null)
                             navigatorTreePanel.collapse(fnode);
                        for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                             navTreePanel.collapse(fnode);
              SwingUtilities.invokeLater(doTask);
        * Will ensure that all tree nodes, starting from the root, are correctly displayed.
         public void refreshTreeDisplays()
              if (hyperbolicTreePanel != null){
                   TopologyModel model = hyperbolicTreePanel.getTopologyModel();
                   if (model != null){
                        hyperbolicTreePanel.expandTreePath((TopologyModelNode)model.getRoot(), true);
                        hyperbolicTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
              if (navigatorTreePanel != null){
                   TopologyModel model = navigatorTreePanel.getTopologyModel();
                   if (model != null){
                        navigatorTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
                        navigatorTreePanel.repaint();
              for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                   ExpandingModelNode model = (ExpandingModelNode)navTreePanel.getNavigatorTreeModel();
                   if (model != null){
                        navigatorTreePanel.expand((TopologyModelNode)model.getRoot());
                        navTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
                        navTreePanel.repaint();
    }

    you really don't need to post all that code, few people will read it, or try to compile/run it.
    just a tree in a scrollpane in a frame is all you need, then add the method/problem to the basic,
    and post that so its only 20 to 30 lines long.
    here's your basic tree/scrollpane/frame, with an expandAll()
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JTree tree = new JTree();
        expandAll(tree);
        JFrame f = new JFrame();
        f.getContentPane().add(new JScrollPane(tree));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public void expandAll(JTree tree)
        int row = 0;
        while (row < tree.getRowCount())
          tree.expandRow(row);
          row++;
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }so, is your problem with the expandAll(), or with reading the properties file?

  • Mapping JTree to an Access Database

    First of all, I am very new to using JTree.
    Second, I was able to create a JTree using QueryDataSet from an Access database (using JBuilder).
    The database table has the following structure:
    NodeID, ParentNodeID and Name.
    NodeID is unique.
    the problem I am facing is how to bind or map each node created to the corresponding NodeID, while I am displaying the Name field as the userObject of the node?
    I want to know this in order to retrieve information from the database regarding the selected node, and can only do that with the NodeID since there are duplicate names for the "Name" field.
    If anyone has an answer to this question please do not hesitate to reply or send me an email.
    Regards,
    Charbel
    [email protected]

    Build a class to put all the db values:
    class MyNode{
    int NodeID;
    int parentID;
    int NodeID;
    String Name;
    public MyNode(int NodeID,int parentID,String Name){
    this.NodeID = NodeID;
    this.parentID = parentID;
    this.Name = Name;
    public String toString(){
    return Name; // this is for the three to show the Name variable
    I guess you will previously sort ascending the access table on the parentID field, in order to easily build the tree.
    When you read from the database, create MyNode instances and fill in the values, and set in teh TreeNode the user object like:
    MyTreeNode mtn = new MyTreeNode(new MyNode(20,3,"OneNode"));
    or
    mtn.setUserObject(new MyNode(20,3,"OneNode"));
    From this structure, you will easily build any popups or actions responding to click events on the tree branches, by simply requesting the user object of the node, and reading its properties.
    Hope it helped,
    Carlos.

  • How to handle multiply properties.files in combined applications

    I have some applications bundled into one jar for each application. The applications make all use of a properties.file in it's own /resources/ folder within the jarfile.
    To avoid running each application on the desktop with it's own JVM and as seperate programs, I wrote a menuprogram which can start the applications within a splitted pane. Left pand is a JTree menu, right side is the applicationspace. This way i have only one JVM active and all app's can be accessed from within a single window. This menu applications also has it's own properties.file.
    I noticed that the applications now all use the same properties.file which is actually not correct. The file used is the one which belongs to the menu application.
    So i have : menu.jar, app1.jar, app2.jar, appn.jar
    The menu.jar is started and from within this application i run the other applications (jInternalFrames). All apps seems to see only the properties.file within the menu.jar IMHO because i create the objects from app1, app2 and appn from within the menu.
    QUESTION:
    How can i change the code to force each app.object to use the propsfile delivered in his own jar-file?
    Here's a code snippet used in each application.
    setPropertiesFileName("/resources/application.properties");
    try {
    is_ = getClass().getResourceAsStream(propertiesFileName);
    props.load(is_);
    catch(Exception e){
    // Debug Props
    setDEBUG_LEVEL(props.getProperty("DEBUG_LEVEL"));
    setTRACE_ENABLED(props.getProperty("TRACE_ENABLED"));
    ...

    You can do this, but is it generally a bad idea which can turn into a nightmare to manage.
    Instead each application should use a different properties file. Is there a good reason every application proeprties must have the same name and path?

  • Problem in refreshing JTree inside Jscrollpane on Button click

    hi sir,
    i have problem in refreshing JTree on Button click inside JscrollPane
    Actually I am removing scrollPane from panel and then again creating tree inside scrollpane and adding it to Jpanel but the tree is not shown inside scrollpane. here is the dummy code.
    please help me.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class Test
    public static void main(String[] args)
         JFrame jf=new TestTreeRefresh();
         jf.addWindowListener( new
         WindowAdapter()
         public void windowClosing(WindowEvent e )
         System.exit(0);
         jf.setVisible(true);
    class TestTreeRefresh extends JFrame
         DefaultMutableTreeNode top;
    JTree tree;
         JScrollPane treeView;
         JPanel jp=new JPanel();
         JButton jb= new JButton("Refresh");
    TestTreeRefresh()
    setTitle("TestTree");
    setSize(500,500);
    getContentPane().setLayout(null);
    jp.setBounds(new Rectangle(1,1,490,490));
    jp.setLayout(null);
    top =new DefaultMutableTreeNode("The Java Series");
    createNodes(top);
    tree = new JTree(top);
    treeView = new JScrollPane(tree);
    treeView.setBounds(new Rectangle(50,50,200,200));
    jb.setBounds(new Rectangle(50,300,100,50));
    jb.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
              jp.remove(treeView);
              top =new DefaultMutableTreeNode("The Java ");
    createNodes(top);
              tree = new JTree(top);
                   treeView = new JScrollPane(tree);
                   treeView.setBounds(new Rectangle(50,50,200,200));
                   jp.add(treeView);     
                   jp.repaint();     
    jp.add(jb);     
    jp.add(treeView);
    getContentPane().add(jp);
    private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode book = null;
    category = new DefaultMutableTreeNode("Books for Java Programmers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Tutorial Continued: The Rest of the JDK");
    category.add(book);
    book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs");
    category.add(book);
    book = new DefaultMutableTreeNode("Effective Java Programming Language Guide");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Programming Language");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Developers Almanac");
    category.add(book);
    category = new DefaultMutableTreeNode("Books for Java Implementers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Virtual Machine Specification");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Language Specification");
    category.add(book);
    }

    hi sir ,
    thaks for u'r suggession.Its working fine but the
    properties of the previous tree were not working
    after setModel() property .like action at leaf node
    is not working,I'm sorry but I don't understand. I think you are saying that the problem is solved but I can read it to mean that you still have a problem.
    If you still have a problem then please post some code (using the [code] tags of course).

  • JTree not showing plus/minus signs

    Hi,
    I'm having a strange problem with JTree when implementing my own DefaultTreeCellRenderer: the renderer is shown correctly, but the plus and minus signs are gone!
    My getTreeCellRendererComponent implementation actually creates a new JPanel and returns it instead of the default one. Can that be the problem? How can I make these plus/minus signs come back?
    Thanks, U

    I have seen something a little different on my CustomCellRenderer where the plus minus sign is replaced with some default arrow icon and where it comes from I have no clue. I basically have a 3 level deep tree and its at the B level where this icon appears.
    http://www.matthewscorp.com/images/JTreeError.jpg
    For the life of me I can't figure this one out. I have tried all ideas like set all the renderer icons or the LAF properties icons and still this blue arrow appears. Any ideas would help on both mine and the original poster.

  • JTree node name

    hi,
    i have a jtree with a specific renderer, this renderer returns a jlabel to represent each node in the tree. The text can be either bold or normal, based on custom properties of the node being rendered. Sometimes, during the execution of the program, these properties change and the jtree is refreshed, it all works fine and the nodes changed become bold as i want, the only problem is that if the text changes size, the full name does not appear. For example when i have a node with this name :
    Inbox
    When the property changes, and the nome becomes bold, the name changes to :
    Inb...
    I have tried everything i can but i just can't solve the problem. anyone knows?
    best regards
    Zede

    If you are using a DefaultTreeModel as your model, then when you change the text or the formatting of the node, call the model's nodeChanged(TreeNode) method.

  • JTree Nimbus selection treeNode

    I made a jtree with a custom TreeCellRenderer. The leaf nodes are a jpanel with a checkbox in and JPanel. The problem now is that when you select a tree node, there is a selection color box beside the jpanel.
    Here is a sscce:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class Users {
        private static JFrame frame;
        private static JPanel usersPanel;
        private JTree usersTree;
        public Users(){
            usersPanel = new JPanel();
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Gebruikers");
            DefaultMutableTreeNode willie = new DefaultMutableTreeNode("Willie");
            DefaultMutableTreeNode Anna = new DefaultMutableTreeNode("Anna");
            rootNode.add(willie);
            rootNode.add(Anna);
            usersTree = new JTree(rootNode);
            myTreeWithCheckBoxRenderer renderer = new myTreeWithCheckBoxRenderer();
            usersTree.setCellRenderer(renderer);
            usersTree.setRootVisible(true);
            usersTree.setEditable(false);
            usersTree.setOpaque(false);
            usersPanel.add(usersTree);
        class myTreeWithCheckBoxRenderer extends DefaultTreeCellRenderer {
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            JPanel panel;
            JCheckBox checkBox;
            JLabel label;
            public myTreeWithCheckBoxRenderer() {
                checkBox = new JCheckBox();
                label = new JLabel("Gebruikers");
                panel = new JPanel(new BorderLayout());
                panel.add(checkBox, BorderLayout.WEST);
                panel.add(label, BorderLayout.EAST);
                panel.setBackground(Color.red);
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                Component returnValue;
                if(!leaf){
                    renderer.setBackgroundSelectionColor(null);
                    renderer.setText("Gebruikers");
                    returnValue = renderer;
                else{
                    if(hasFocus){
                        panel.setBackground(Color.blue);
                    returnValue = panel;
                return returnValue;
        private static void createAndShowGUI(){
            new Users();
            frame = new JFrame("Tree");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(usersPanel);
            frame.pack();
            frame.setPreferredSize(new Dimension(800, 600));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
         public static void main (String[] args){
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            javax.swing.SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    createAndShowGUI();
    }I tried using a DefaultTreeCellRenderer and use the setBackgroundSelectionColor() method to null, but it doesn't change anything. Also setting the background of the JPanel to null doesn't make a change when you check with (if(hasFocus)). However I have the impression that nimbus is causing the problem, because if you comment the nimbus part out, you don't have the selection box anymore.
    Does anyone has an idea to solve this?
    Edited by: Kligham on 30-aug-2010 19:25

    Kligham wrote:
    Thank you very much!You're welcome.
    Kligham wrote:
    Problem solved. So since this cell background rendering is a Nimbus "feature", can I assume that the "not displaying of angled lines" also is a Nimbus "feature". Since the JTree tutorial says this should do the trick:
    usersTree.putClientProperty("JTree.lineStyle", "Angled");So I probably have to override it the same way, so I was wondering how you know what UIDefaults there are?Well, "JTree.lineStyle" is actually a client property and not a UIDefaults property. In other words, "JTree.lineStyle" is on the same logical level as "Nimbus.Overrides". Unfortunately, there is no way to determine which client properties a component or a component UI implementation supports except carefully examining its source code. javax.swing.plaf.synth.SynthTreeUI (the Nimbus TreeUI implementation) doesn't seem to support any client properties. It might be handled somewhere else, though.
    As an alternative to using "JTree.lineStyle", you could try to use a backgroundPainter that draws angle lines instead of the "do nothing" painter I suggested.
    To determine which UIDefaults properties are available for a given LaF implementation, you can iterate over the UIDefaults' entrySet (UIDefaults is a subclass of Hashtable). For Nimbus specifically, Jasper Potts already did that. See the [corresponding blog entry|http://www.jasperpotts.com/blog/2008/08/nimbus-uimanager-uidefaults/] and [Nimbus UIDefaults Properties List|http://jasperpotts.com/blogfiles/nimbusdefaults/nimbus.html]

  • Can we use JTable in a JTree?

    Hi Actually this is my first mail to this forum.
    I want to use a tables embedded in a tree . You can see such format in VB's Properties sheet's "Categorized" tab. Has anyone tried doing such format. Or anyone knows if it is possible to do it in Jtrees. If yes then how?
    Anybody knows? Pls mail back.
    Regards,
    Amit.

    Hi,
    Thanks for the reply. This will definately serve my purpose, but i cannot compromise on the GUI. But, Is there a way by which I can have table on the click of a tree node and not JTree as a renderer for the cells in a JTable.
    Pls mail back.
    Regards,
    Amit

  • Help with JTrees

    Hello,
    I have a JTree and I need it's items to display as stylized text. Or in other words, I want the listed leafs on the JTree to sometimes be bold, colored, underlined, superscript, etc. The style of each JTree leaf will be determined by the properties of a SimpleAttributeSet.
    Basically, is there a way to turn the cells that render each node into DefaultStyledDocuments so that I can call insertString( int offs, String str, AttributeSet a) on it?
    Thanks a lot for any help on this,
    - kevin

    Btw, The other arguments in the method (selected, expanded, leaf, row and hasFocus) allow you to further customize a rendered node.
    ie. if a tree's row is selected, the selected flag will be true, you should have something like:
    if(selected)
      // render it as 'selected', ie change the background color or something
    }in your getTreeCellRendererComponent() method.
    The "row" integer tells you what row in the tree you are at, so you can also customize things further using that argument.

  • Display style of JTree

    Can we display JTree in top-down form rather than left-right (explorer) form?

    Hi,
    What web part do you use? Or is it a custom web part?
    If there is no such OOTB feature can modify the style, a workaround is using custom CSS code to implement your own custom style for it. With custom CSS, we will be
    able to achieve more complex styles.
    https://www.nothingbutsharepoint.com/2013/05/02/understanding-sharepoint-csslink-and-how-to-add-your-custom-css-in-sharepoint-2010-aspx/
    More demos about how to create table style with custom CSS:
    http://css-tricks.com/almanac/properties/d/display/
    http://www.creativedev.in/2013/01/table-layout-using-div-tags/
    About how to add custom CSS to SharePoint:
    http://fitandfinish.ironworks.com/2010/01/the-best-way-to-add-custom-css-to-sharepoint.html
    Best regards
    Patrick Liang
    TechNet Community Support

  • Best way to store objects' properties and later remake those objects?

    I want to create a bunch of objects, set their properties and then save that so on restart, the objects can be reconstituted. Is serialization the best way/ Some other way? I want to store them in XML so I can also create a GUI to show the objects stored.

    JoachimSauer wrote:
    6tr6tr wrote:
    I want to create a bunch of objects, set their properties and then save that so on restart, the objects can be reconstituted. Is serialization the best way/ Some other way?Serialization is definitely one way to do that.
    I want to store them in XMLUse JAXB or XMLEncoder/XMLDecoder.
    so I can also create a GUI to show the objects stored.What does a GUI have to do with writing XML? I don't see how that's in any way related.Thanks. What I meant was that I want to have a JTree populated easily with that info and I know there's good support for populating a JTree with XML.

  • How can create a JTree with cellRender is checkbox realized multiple selec

    How can create a JTree with cellRender is checkbox realized multiple selection function.thanks for every
    one's help.

    Hi,
    1. Create a value node in your context name Table and set its cardinality to 0:n
    2. Create 2 value attributes within the Table node name value1 and value2
    3. Goto Outline view> Right click on TransparentUIContainer>Apply Template> Select Table>mark the node Table and it's attributes.
    you have created a table and binded its value to context
    Table UI properties
    4.Set Selection Mode to Multi
    5.Set Visible Row Count to 5
    6.ScrollableColCount to 5
    In your implemetaion, you can add values to table as follow:
    IPrivate<viewname>.ITableElement ele = wdContext.nodeTable().createTableElement();
    ele.setValue1(<value>);
    ele.setValue2(<value>);
    wdContext.nodeTable().addElement(ele);
    The above code will allow you to add elements to your table node.
    Regards,
    Murtuza

  • How can i change the particular node color in Jtree?

    I have constructed the tree.i dont know how to set the color for the particular node then how can i change the particular node icon depends on some conditions like if we will give the input whether it is available in jtree that node icon only changed.Anyone please help me as soon as possible.

    hi,
    i saw that tutorial.from that book i dont get the particular node cell renderer.i got a cell renderer for tree only.i attached my code in this mail.pls see and help me if u will do
    mport pack.Prop;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Font;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Properties;
    import java.util.Set;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.text.Position;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    public class ReadProperty3 extends JFrame{
    String str,key;
    static JTree tree;
    static Vector v;
    StringTokenizer st;
    static DefaultMutableTreeNode root;
    DefaultMutableTreeNode t;     
    public Object[] o;
    public static void main(String[] args) throws IOException {
    ReadProperty3 r = new ReadProperty3();
    Prop p=new Prop();
    JFrame f=new JFrame();
    p.show();
    Object[] o=v.toArray();
    int startRow = 0;
    String prefix =p.s;
    TreePath path = tree.getNextMatch(prefix, startRow, Position.Bias.Forward);
    //if(prefix.equals(root.getChildAt(0).toString()))
    if(prefix.equals("2000"))
         System.out.println("Node 2000 found");
         else if(prefix.equals("3000"))
              System.out.println("Node 3000 found");
         else if(prefix.equals("4000"))
              System.out.println("Node 4000 found");
         else
              System.out.println("Node not found");
         for(int i=0;i<v.size();i++)
              //((DefaultTreeModel)tree.getModel()).reload();
              DefaultTreeCellRenderer ren=(DefaultTreeCellRenderer)tree.getCellRenderer();
              Icon openIcon = new ImageIcon("C:/apache-tomcat-5.5.12/webapps/jsp-examples/images/execute.gif");
              Icon closedIcon = new ImageIcon("C:/apache-tomcat-5.5.12/webapps/jsp-examples/images/execute.gif");
              Icon leafIcon = new ImageIcon("C:/apache-tomcat-5.5.12/webapps/jsp-examples/images/read.gif");
              if(o[0].equals(p.s))
                   ren.setBackgroundSelectionColor(Color.MAGENTA);
                   ren.setBackgroundNonSelectionColor(Color.YELLOW);
                   //ren.setTextSelectionColor(Color.YELLOW);
                   //ren.setTextNonSelectionColor(Color.BLUE);
                   ren.setClosedIcon(closedIcon);
                   ren.setFont(new Font("Impact",Font.ITALIC,14));
              else if(o[1].equals(p.s))
                   ren.setLeafIcon(leafIcon);
                   ren.setFont(new Font("Impact",Font.ITALIC,10));
                   UIManager.put("Tree.leafIcon", leafIcon);
              else if(o[2].equals(p.s))
                   ren.setOpenIcon(openIcon);
                   ren.setFont(new Font("Dialog",Font.BOLD,9));
    public ReadProperty3(){
         super("JTree With Properties");
         try{
    int c = 0;
    while(c == 0){
    c = 1;
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter file name which has properties extension :");
    str = bf.readLine();
    File f = new File(str + ".properties");
    if(f.exists()){
    Properties pro = new Properties();
    FileInputStream in = new FileInputStream(f);
    pro.load(in);
    System.out.println("Key: " + pro.keySet());
    System.out.print("Enter Key : ");
    key = bf.readLine();
    String p = pro.getProperty(key);
    st = new StringTokenizer(p,"=,");
    root=new DefaultMutableTreeNode(key);
    v=new Vector();
    while(st.hasMoreTokens())
         String val=st.nextToken();
         v.add(val);
         o=v.toArray();
         System.out.println(val);
         t=new DefaultMutableTreeNode(val);
         root.add(t);
         tree=new JTree(root);
         tree.setEditable(true);
         JScrollPane jp=new JScrollPane(tree);
         // tree.setCellRenderer(new CellRenderer());
         Container content=getContentPane();
         content.add(jp,BorderLayout.CENTER);
    setSize(250,275);
    setVisible(true);
    addWindowListener(new ExitListener());
    else{
    c = 0;
    System.out.println("File not found!");
    catch(IOException e){
    System.out.println(e.getMessage());
    }

Maybe you are looking for