JPopupMenu, JTree

Hi,
I am new to JPopupMenu and JTree. Let me explain the scenario first. There is a JTree with two branch nodes(Game tables and New Players). First branch node(game tables) can have multiple branch nodes which are different tables and each of these game tables have leaves i.e. players on each table.
I need a popup menu only for branch node(game tables) and leaves(players). Rite now when i am doing its coming for all branches. How to make my code specific for specific nodes??
Please reply as soon as possible.. Desperatly need help!!

[url http://onesearch.sun.com/search/onesearch/index.jsp?qt=popup+menu+specific+jtree+node&qp_name=null&subCat=siteforumid%3Ajava57&site=dev&dftab=siteforumid%3Ajava57&chooseCat=javaall&col=developer-forums]Search Results

Similar Messages

  • Removing focus from a node

    I have a frame in which a scrollpane hold a jtree.
    I picked up the following code from the forum for making sure that only when the right click is on a node, the popupmenu is displayed.
    public void mouseReleased(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    TreePath closestTreePath = tree.getClosestPathForLocation(e.getPoint(), e.getPoint());
                    if (closestTreePath != null) {
                        tree.setSelectionPath(closestTreePath);
                         // select the row in the tree for the path
                        selectedRow = tree.getRowForPath(closestTreePath);
                        YourNode node = (YourNode) closestTreePath.getLastPathComponent();
                       // assuming your popup menu is already created somewhere else
                       popupMenu.show(deviceTree, pt.x, pt.y);
                        selectedRow = -1;
    }by codecraig
    But now the problem is that whenever i do right click anywhere on the tree a node gets selected and the popupmenu is displyed. i want to display the right click is on the node.
    here is my code
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.event.*;
    public class tree_right_click
         //JPopupMenu popupmenu = new JPopupMenu();
         JTree mytree;
         SysPopupListener s = new SysPopupListener();
         public tree_right_click()
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
              DefaultMutableTreeNode l1 = new DefaultMutableTreeNode("level1");
              DefaultMutableTreeNode l2 = new DefaultMutableTreeNode("level2");
              mytree=new JTree(root);
              mytree.addMouseListener(s);
              root.add(l1);
              l1.add(l2);
              JScrollPane treeview = new JScrollPane(mytree);
              JFrame fr = new JFrame("My Frame");
              fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              fr.getContentPane().add(treeview);
              fr.setSize(300,300);
              fr.setVisible(true);
              public static void main(String args[])
              new tree_right_click();
    class SysPopupListener extends MouseAdapter
         JPopupMenu popupmenu = new JPopupMenu();
         SysPopupListener()
              JMenuItem part = new JMenuItem("Add detail 1");
              JMenuItem part2 = new JMenuItem("Add detail 2");
              part.addMouseListener(this);
              part2.addMouseListener(this);
              popupmenu.add(part);
              popupmenu.add(part2);
         public void mousePressed(MouseEvent e)
              maybeshowpopup(e);
         public void mouseReleased(MouseEvent e)
              maybeshowpopup(e);
         void maybeshowpopup(MouseEvent e)
              if(e.isPopupTrigger())
                   JTree t = (JTree)e.getComponent();
                   TreePath closestTreePath = t.getClosestPathForLocation(e.getX(), e.getY());
                if (closestTreePath != null) {
                    t.setSelectionPath(closestTreePath);
                     // select the row in the tree for the path
                    int selectedRow = t.getRowForPath(closestTreePath);
                    DefaultMutableTreeNode n = (DefaultMutableTreeNode) closestTreePath.getLastPathComponent();
                    System.out.print(n);
                   // assuming your popup menu is already created somewhere else
                    popupmenu.show(e.getComponent(),e.getX(),e.getY());
                    selectedRow = -1;
    }Please help,
    thanks in advance,
    Puneet

    I made some changes to your code and seems to be working like this:
              if(e.isPopupTrigger()) {
                   JTree t = (JTree)e.getComponent();
                   TreePath closestTreePath = t.getClosestPathForLocation(e.getX(), e.getY());
                   if (closestTreePath != null) {
                        t.setSelectionPath(closestTreePath);
                        // select the row in the tree for the path
                        int selectedRow = t.getRowForPath(closestTreePath);
                        DefaultMutableTreeNode n = (DefaultMutableTreeNode) closestTreePath.getLastPathComponent();
                        System.out.print(n);
                        // assuming your popup menu is already created somewhere else
                        popupmenu.show(e.getComponent(),e.getX(),e.getY());
                        selectedRow = -1;
                   JTree t = (JTree)e.getComponent();
                   TreePath path = t.getPathForLocation(e.getX(), e.getY());
                   if (path != null) {
                        popupmenu.show(e.getComponent(),e.getX(),e.getY());
              }

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • JPopupMenu for a JTree, enabling and disabling options

    Hi all.
    I'm trying to activate/deactivate some JMenuItem options for a JPopupMenu launched for a JTree object.
    Let's say, depending on "some state", I want some options in the JPopupMenu (the JMenuItems) should be enabled or disabled, and change whenever that state changes.
    I'm trying to activate this feature with "((JMenuItem) item).setEnabled(true)" but the PopupMenu option is still disabled.
    Can some one help me, please?
    Thanks a lot in advance.
    -- Arturo

    Hi all.
    I'm trying to activate/deactivate some JMenuItem options for a JPopupMenu launched for a JTree object.
    Let's say, depending on "some state", I want some options in the JPopupMenu (the JMenuItems) should be enabled or disabled, and change whenever that state changes.
    I'm trying to activate this feature with "((JMenuItem) item).setEnabled(true)" but the PopupMenu option is still disabled.
    Can some one help me, please?
    Thanks a lot in advance.
    -- Arturo

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

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

  • Select multiple nodes in a JTree a right click

    Hi all,
    I've a JTree and I'd like to allow the user select some nodes (one or more) right click and than show a popupMenu.
    This behavior seems not to be easy, because if I select a single node (right clicking on it) the node does not appear selected ; I need to select it left clicking and than everything works fine.
    I read some posts found in the forum and the solution seems to be :
    - attach a mouseListener to the JTree
    - get the TreePath of the node selected
    - force the selection on the node with setSelectionPath(TreePath)
    This works fine if you need to select only one node, cause if you have to select more, you simply cannot.
    I wonder a so obvious behavior is so hard to achieve.
    I hope somebody out there had made the magic.
    Any help would be appreciated.
    Flavio Palumbo

    Hi Darryl,
    I wrote the test case below.
    Using the methods you suggested it works almost fine.
    The only behavior not desired is when you select a range (shift or control), release the key an than right click ; in this case remains selected the only node you clicked on ; to select the range clicking with the right button, you have to keep pressed the key.
    Any hint would be appreciated.
    Flavio
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    public class TestTree {
        JTree jtr = null;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TestTree();
        public TestTree() {
            JFrame jf = new JFrame();
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            try {
                javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                javax.swing.SwingUtilities.updateComponentTreeUI(jf);
            } catch (Throwable e) {
            jf.setPreferredSize(new java.awt.Dimension(200, 560));
            javax.swing.JScrollPane js = new javax.swing.JScrollPane();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
            jtr = new JTree(root);
            jtr.addMouseListener(new TestTreeML());
            js.setViewportView(jtr);
            jf.getContentPane().add(js);
            for (int i = 0; i < 20; i++) {
                DefaultMutableTreeNode nodoFiglio = new DefaultMutableTreeNode("nodo" + i);
                ((DefaultTreeModel) jtr.getModel()).insertNodeInto(nodoFiglio, root, root.getChildCount());
            jf.pack();
            jf.setVisible(true);
        public class TestTreeML extends MouseAdapter {
            @Override
            public void mousePressed(MouseEvent e) {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    if (!e.getSource().equals(jtr)) {
                        return;
                    TreePath tpSel = jtr.getPathForLocation(e.getX(), e.getY());
                    if (tpSel == null) {
                        return;
                    int i = 0;
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tpSel.getLastPathComponent();
                    TreePath[] tpExisting = null;
                    if (e.isControlDown() || e.isShiftDown()) {
                        System.out.println("control/shift");
                        TreePath[] tpEx = jtr.getSelectionPaths();
                        tpExisting = java.util.Arrays.copyOfRange(tpEx, 0, tpEx.length + 1);
                        i = tpEx.length;
                    } else {
                        tpExisting = new TreePath[1];
                    tpExisting[i] = tpSel;
                    jtr.setSelectionPaths(tpExisting);
                    if (e.getClickCount() == 2) {
                        System.out.println("double click on " + node.getUserObject());
                    if (javax.swing.SwingUtilities.isRightMouseButton(e)) {
                        if (!e.isControlDown()) {
                            jtr.setSelectionPath(tpSel);
                        JPopupMenu menu = new JPopupMenu();
                        JMenuItem it0 = new JMenuItem("Option1");
                        it0.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                System.out.println("Option1 on " + node.getUserObject());
                        menu.add(it0);
                        JMenuItem it1 = new JMenuItem("Option2");
                        it1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                System.out.println("Option2 on " + node.getUserObject());
                        menu.add(it1);
                        menu.show(jtr, e.getX(), e.getY());
                } catch (Throwable t) {
    }

  • JTree with XML Content

    Hi Friends,
    I am trying to create a JTree whose data will come from a XML Document. Whenever the tree is refreshed (There is a JPopupMenu on the tree which allows the user to call refresh), the tree must update itself with the underlying XML document. If there is any change in the xml doc, it must be reflected in the tree. However, the tree must not collapse when the refresh is called. For example if I have a tree like this:-
    + Root
        |
        ------ Child #1
        |            |
        |            -------- A
        |            |
        |            -------- B
        |
        +------ Child #2
        |
        ------- Child #3
                    |
                    -------- AAA
                    |
                    -------- BBBThe XML Document for the above tree structure would be:-
    <?xml version="1.0" encoding="UTF-8"?>
    <Root>Root
          <Child> Child #1
                <SubChild>A</SubChild>
                <SubChild>B</SubChild>
          </Child>
          <Child> Child #2
                <SubChild>AA</SubChild>
                <SubChild>BB</SubChild>
          </Child>
          <Child> Child #3
                <SubChild>AAA</SubChild>
                <SubChild>BBB</SubChild>
          </Child>
    </Root>Now if i add another node (CCC) in Child #3 (by adding another Subchild element in the XML document), and click refresh on the tree, the tree should look like:-
    + Root
        |
        ------ Child #1
        |            |
        |            -------- A
        |            |
        |            -------- B
        |
        +------ Child #2
        |
        ------- Child #3
                    |
                    -------- AAA
                    |
                    -------- BBB
                    |
                    -------- CCCHowever, if i am trying to reload the tree model, after reading the XML file, the whole tree collapses.
    Can anyone please help me out with this problem?
    Thanx a lot in advance,
    ~Debopam

    * XMLNode.java
    * Created on December 18, 2004, 4:25 PM
    package debopam.utils.xml;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.Vector;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreeNode;
    import org.jdom.Element;
    * @author Debopam Ghoshal
    public class XMLNode implements MutableTreeNode
        private Element nodeElement;
        private XMLNode parent;
        /** optional user object */
        transient protected Object     userObject;
        /** true if the node is able to have children */
        protected boolean allowsChildren;
        /** array of children, may be null if this node has no children */
        protected Vector children;
         * An enumeration that is always empty. This is used when an enumeration
         * of a leaf node's children is requested.
        static public final Enumeration<TreeNode> EMPTY_ENUMERATION
                = new Enumeration<TreeNode>()
            public boolean hasMoreElements()
            { return false; }
            public TreeNode nextElement()
                throw new NoSuchElementException("No more elements");
        /** Creates a new instance of XMLNode */
        public XMLNode(Element nodeElement, boolean allowsChildren)
            this.nodeElement = nodeElement;
            this.allowsChildren = allowsChildren;
        public XMLNode(String nodeName, boolean allowsChildren)
            nodeElement = new Element(nodeName);
            this.allowsChildren = allowsChildren;
         * Creates and returns a forward-order enumeration of this node's
         * children.  Modifying this node's child array invalidates any child
         * enumerations created before the modification.
         * @return     an Enumeration of this node's children
        public java.util.Enumeration children()
            if(children == null)
                return EMPTY_ENUMERATION;
            else
                return children.elements();
         * Returns true if this node is allowed to have children.
         * @return     true if this node allows children, else false
        public boolean getAllowsChildren()
            return allowsChildren;
         * Determines whether or not this node is allowed to have children.
         * If <code>allows</code> is false, all of this node's children are
         * removed.
         * <p>
         * Note: By default, a node allows children.
         * @param     allows     true if this node is allowed to have children
        public void setAllowsChildren(boolean allows)
            if (allows != allowsChildren)
                allowsChildren = allows;
                if (!allowsChildren)
                    removeAllChildren();
         * Returns the child at the specified index in this node's child array.
         * @param     index     an index into this node's child array
         * @exception     ArrayIndexOutOfBoundsException     if <code>index</code>
         *                              is out of bounds
         * @return     the TreeNode in this node's child array at  the specified index
        public javax.swing.tree.TreeNode getChildAt(int index)
            if (children == null)
                throw new ArrayIndexOutOfBoundsException("node has no children");
            return (TreeNode)children.elementAt(index);
         * Returns the number of children of this node.
         * @return     an int giving the number of children of this node
        public int getChildCount()
            if (children == null)
                return 0;
            else
                return children.size();
         * Returns the index of the specified child in this node's child array.
         * If the specified node is not a child of this node, returns
         * <code>-1</code>.  This method performs a linear search and is O(n)
         * where n is the number of children.
         * @param     aChild     the TreeNode to search for among this node's children
         * @exception     IllegalArgumentException     if <code>aChild</code>
         *                                   is null
         * @return     an int giving the index of the node in this node's child
         *          array, or <code>-1</code> if the specified node is a not
         *          a child of this node
        public int getIndex(TreeNode aChild)
            if (aChild == null)
                throw new IllegalArgumentException("argument is null");
            if (!isNodeChild(aChild))
                return -1;
            return children.indexOf(aChild);     // linear search
         * Returns this node's parent or null if this node has no parent.
         * @return     this node's parent TreeNode, or null if this node has no parent
        public TreeNode getParent()
            return parent;
         * Removes <code>newChild</code> from its present parent (if it has a
         * parent), sets the child's parent to this node, and then adds the child
         * to this node's child array at index <code>childIndex</code>.
         * <code>newChild</code> must not be null and must not be an ancestor of
         * this node.
         * @param     newChild     the MutableTreeNode to insert under this node
         * @param     childIndex     the index in this node's child array
         *                    where this node is to be inserted
         * @exception     ArrayIndexOutOfBoundsException     if
         *                    <code>childIndex</code> is out of bounds
         * @exception     IllegalArgumentException     if
         *                    <code>newChild</code> is null or is an
         *                    ancestor of this node
         * @exception     IllegalStateException     if this node does not allow
         *                              children
         * @see     #isNodeDescendant
        public void insert(MutableTreeNode newChild, int childIndex)
            if (!allowsChildren)
                throw new IllegalStateException("node does not allow children");
            else if (newChild == null)
                throw new IllegalArgumentException("new child is null");
            else if (isNodeAncestor(newChild))
                throw new IllegalArgumentException("new child is an ancestor");
            MutableTreeNode oldParent = (MutableTreeNode)newChild.getParent();
            if (oldParent != null)
                oldParent.remove(newChild);
            newChild.setParent(this);
            if (children == null)
                children = new Vector();
            children.insertElementAt(newChild, childIndex);
        public boolean isLeaf()
            return !nodeElement.hasChildren();
         * Removes the child at the specified index from this node's children
         * and sets that node's parent to null. The child node to remove
         * must be a <code>MutableTreeNode</code>.
         * @param     childIndex     the index in this node's child array
         *                    of the child to remove
         * @exception     ArrayIndexOutOfBoundsException     if
         *                    <code>childIndex</code> is out of bounds
        public void remove(int childIndex)
            MutableTreeNode child = (MutableTreeNode)getChildAt(childIndex);
            children.removeElementAt(childIndex);
            child.setParent(null);
         * Removes <code>aChild</code> from this node's child array, giving it a
         * null parent.
         * @param     aChild     a child of this node to remove
         * @exception     IllegalArgumentException     if <code>aChild</code>
         *                         is null or is not a child of this node
        public void remove(MutableTreeNode aChild)
            if (aChild == null)
                throw new IllegalArgumentException("argument is null");
            if (!isNodeChild(aChild))
                throw new IllegalArgumentException("argument is not a child");
            remove(getIndex(aChild));     // linear search
         * Removes the subtree rooted at this node from the tree, giving this
         * node a null parent.  Does nothing if this node is the root of its
         * tree.
        public void removeFromParent()
            MutableTreeNode parent = (MutableTreeNode)getParent();
            if (parent != null)
                parent.remove(this);
         * Sets this node's parent to <code>newParent</code> but does not
         * change the parent's child array.  This method is called from
         * <code>insert()</code> and <code>remove()</code> to
         * reassign a child's parent, it should not be messaged from anywhere
         * else.
         * @param     newParent     this node's new parent
        public void setParent(MutableTreeNode mutableTreeNode)
            this.parent = parent;
        public void setUserObject(Object obj)
            this.userObject = obj;
        public Element getXMLElement()
            return this.nodeElement;
        public String toString()
            return this.nodeElement.getTextTrim();
         * Returns true if <code>anotherNode</code> is an ancestor of this node
         * -- if it is this node, this node's parent, or an ancestor of this
         * node's parent.  (Note that a node is considered an ancestor of itself.)
         * If <code>anotherNode</code> is null, this method returns false.  This
         * operation is at worst O(h) where h is the distance from the root to
         * this node.
         * @see          #isNodeDescendant
         * @see          #getSharedAncestor
         * @param     anotherNode     node to test as an ancestor of this node
         * @return     true if this node is a descendant of <code>anotherNode</code>
        public boolean isNodeAncestor(TreeNode anotherNode)
            if (anotherNode == null)
                return false;
            TreeNode ancestor = this;
            do
                if (ancestor == anotherNode)
                    return true;
            } while((ancestor = ancestor.getParent()) != null);
            return false;
         * Returns true if <code>aNode</code> is a child of this node.  If
         * <code>aNode</code> is null, this method returns false.
         * @return     true if <code>aNode</code> is a child of this node; false if
         *            <code>aNode</code> is null
        public boolean isNodeChild(TreeNode aNode)
            boolean retval;
            if (aNode == null)
                retval = false;
            else
                if (getChildCount() == 0)
                    retval = false;
                else
                    retval = (aNode.getParent() == this);
            return retval;
         * Removes all of this node's children, setting their parents to null.
         * If this node has no children, this method does nothing.
        public void removeAllChildren()
            for (int i = getChildCount()-1; i >= 0; i--)
                remove(i);
         * Removes <code>newChild</code> from its parent and makes it a child of
         * this node by adding it to the end of this node's child array.
         * @see          #insert
         * @param     newChild     node to add as a child of this node
         * @exception     IllegalArgumentException    if <code>newChild</code>
         *                              is null
         * @exception     IllegalStateException     if this node does not allow
         *                              children
        public void add(MutableTreeNode newChild)
            if(newChild != null && newChild.getParent() == this)
                insert(newChild, getChildCount() - 1);
            else
                insert(newChild, getChildCount());
         * Indicates whether some other object is "equal to" this one.
         * @param   obj   the reference object with which to compare.
         * @return  <code>true</code> if this object is the same as the obj
         *          argument; <code>false</code> otherwise.
        public boolean equals(XMLNode node)
            boolean retValue;
            retValue = (this.getXMLElement().getTextTrim().equals(node.getXMLElement().getTextTrim())) &&
                    (this.getXMLElement().getParent().getTextTrim().equals(node.getXMLElement().getParent().getTextTrim()));
            return retValue;
    * XMLTreeModel.java
    * Created on December 20, 2004, 11:29 AM
    package debopam.utils.xml;
    import java.io.File;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.EventListener;
    import java.util.List;
    import java.util.Vector;
    import javax.swing.event.EventListenerList;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    * @author Debopam Ghoshal
    public class XMLTreeModel implements TreeModel
        private XMLNode rootNode;
        private String xmlFileName;
        private Document xmlDocument;
        /** Listeners. */
        protected EventListenerList listenerList = new EventListenerList();
         * Determines how the <code>isLeaf</code> method figures
         * out if a node is a leaf node. If true, a node is a leaf
         * node if it does not allow children. (If it allows
         * children, it is not a leaf node, even if no children
         * are present.) That lets you distinguish between <i>folder</i>
         * nodes and <i>file</i> nodes in a file system, for example.
         * <p>
         * If this value is false, then any node which has no
         * children is a leaf node, and any node may acquire
         * children.
         * @see TreeNode#getAllowsChildren
         * @see TreeModel#isLeaf
         * @see #setAsksAllowsChildren
        protected boolean asksAllowsChildren;
        /** Creates a new instance of XMLTreeModel */
        public XMLTreeModel(String xmlFileName, boolean asksAllowsChildren)
            this.xmlFileName = xmlFileName;
            this.asksAllowsChildren = asksAllowsChildren;
            loadXMLDocument();
            rootNode = makeRootNode();
        public XMLTreeModel(String xmlFileName)
            this(xmlFileName, false);
        private void loadXMLDocument()
            System.out.println("loading xml document...");
            try
                this.xmlDocument = null;
                this.xmlDocument = new SAXBuilder().build(new File(xmlFileName));
            catch(Exception x)
                System.out.println("Error while loading XML Document.");
                x.printStackTrace();
        private XMLNode makeRootNode()
            XMLNode root = new XMLNode(xmlDocument.getRootElement(), true);
            addChildren(root, xmlDocument.getRootElement());
            return root;
        private void addChildren(XMLNode parentXMLNode, Element element)
            List children = element.getChildren();
            for(int i = 0; i < children.size(); i++)
                Element childElement = (Element)children.get(i);
                XMLNode childNode = new XMLNode(childElement, true);
                parentXMLNode.add(childNode);
                addChildren(childNode, childElement);
         * Sets whether or not to test leafness by asking getAllowsChildren()
         * or isLeaf() to the TreeNodes.  If newvalue is true, getAllowsChildren()
         * is messaged, otherwise isLeaf() is messaged.
        public void setAsksAllowsChildren(boolean newValue)
            asksAllowsChildren = newValue;
         * Tells how leaf nodes are determined.
         * @return true if only nodes which do not allow children are
         *         leaf nodes, false if nodes which have no children
         *         (even if allowed) are leaf nodes
         * @see #asksAllowsChildren
        public boolean asksAllowsChildren()
            return asksAllowsChildren;
         * Returns the child of <I>parent</I> at index <I>index</I> in the parent's
         * child array.  <I>parent</I> must be a node previously obtained from
         * this data source. This should not return null if <i>index</i>
         * is a valid index for <i>parent</i> (that is <i>index</i> >= 0 &&
         * <i>index</i> < getChildCount(<i>parent</i>)).
         * @param   parent  a node in the tree, obtained from this data source
         * @return  the child of <I>parent</I> at index <I>index</I>
        public Object getChild(Object parent, int index)
            return ((XMLNode)parent).getChildAt(index);
         * Returns the number of children of <I>parent</I>.  Returns 0 if the node
         * is a leaf or if it has no children.  <I>parent</I> must be a node
         * previously obtained from this data source.
         * @param   parent  a node in the tree, obtained from this data source
         * @return  the number of children of the node <I>parent</I>
        public int getChildCount(Object parent)
            return ((XMLNode)parent).getChildCount();
         * Returns the index of child in parent.
         * If either the parent or child is <code>null</code>, returns -1.
         * @param parent a note in the tree, obtained from this data source
         * @param child the node we are interested in
         * @return the index of the child in the parent, or -1
         *    if either the parent or the child is <code>null</code>
        public int getIndexOfChild(Object parent, Object child)
            if(parent == null || child == null)
                return -1;
            return ((XMLNode)parent).getIndex((XMLNode)child);
         * Sets the root to <code>root</code>. A null <code>root</code> implies
         * the tree is to display nothing, and is legal.
        public void setRoot(XMLNode rootNode)
            Object oldRoot = this.rootNode;
            this.rootNode = rootNode;
            if (rootNode == null && oldRoot != null)
                fireTreeStructureChanged(this, null);
            else
                nodeStructureChanged(rootNode);
         * Returns the root of the tree.  Returns null only if the tree has
         * no nodes.
         * @return  the root of the tree
        public Object getRoot()
            return rootNode;
         * Returns whether the specified node is a leaf node.
         * The way the test is performed depends on the
         * <code>askAllowsChildren</code> setting.
         * @param node the node to check
         * @return true if the node is a leaf node
         * @see #asksAllowsChildren
         * @see TreeModel#isLeaf
        public boolean isLeaf(Object node)
            if(asksAllowsChildren)
                return !((XMLNode)node).getAllowsChildren();
            return ((XMLNode)node).isLeaf();
         * This sets the user object of the TreeNode identified by path
         * and posts a node changed.  If you use custom user objects in
         * the TreeModel you're going to need to subclass this and
         * set the user object of the changed node to something meaningful.
        public void valueForPathChanged(TreePath path, Object newValue)
            XMLNode aNode = (XMLNode)path.getLastPathComponent();
            aNode.setUserObject(newValue);
            nodeChanged(aNode);
         * Invoked this to insert newChild at location index in parents children.
         * This will then message nodesWereInserted to create the appropriate
         * event. This is the preferred way to add children as it will create
         * the appropriate event.
        public void insertNodeInto(XMLNode newChild, XMLNode parent, int index)
            parent.insert(newChild, index);
            int[] newIndexs = new int[1];
            newIndexs[0] = index;
            nodesWereInserted(parent, newIndexs);
         * Message this to remove node from its parent. This will message
         * nodesWereRemoved to create the appropriate event. This is the
         * preferred way to remove a node as it handles the event creation
         * for you.
        public void removeNodeFromParent(XMLNode node)
            XMLNode parent = (XMLNode)node.getParent();
            if(parent == null)
                throw new IllegalArgumentException("node does not have a parent.");
            int[] childIndex = new int[1];
            Object[] removedArray = new Object[1];
            childIndex[0] = parent.getIndex(node);
            parent.remove(childIndex[0]);
            removedArray[0] = node;
            nodesWereRemoved(parent, childIndex, removedArray);
         * Invoke this method after you've changed how node is to be
         * represented in the tree.
        public void nodeChanged(XMLNode node)
            if(listenerList != null && node != null)
                XMLNode parent = (XMLNode)node.getParent();
                if(parent != null)
                    int        anIndex = parent.getIndex(node);
                    if(anIndex != -1)
                        int[] cIndexs = new int[1];
                        cIndexs[0] = anIndex;
                        nodesChanged(parent, cIndexs);
                else if (node == getRoot())
                    nodesChanged(node, null);
         * Invoke this method if you've modified the TreeNodes upon which this
         * model depends.  The model will notify all of its listeners that the
         * model has changed.
        public void reload()
            loadXMLDocument();
            XMLNode tempRootNode = makeRootNode();
            if(!tempRootNode.equals(rootNode))
                // Means that the root node itself has changed.
                System.out.println("Root node changed");
                reload(rootNode);
            //else
                checkForNodesChanged(tempRootNode, rootNode);
         * Invoke this method if you've modified the TreeNodes upon which this
         * model depends.  The model will notify all of its listeners that the
         * model has changed below the node <code>node</code> (PENDING).
        public void reload(XMLNode node)
            if(node != null)
                fireTreeStructureChanged(this, getPathToRoot(node), null, null);
         * Invoke this method after you've inserted some TreeNodes into
         * node.  childIndices should be the index of the new elements and
         * must be sorted in ascending order.
        public void nodesWereInserted(XMLNode node, int[] childIndices)
            if(listenerList != null && node != null && childIndices != null
                    && childIndices.length > 0)
                int               cCount = childIndices.length;
                Object[]          newChildren = new Object[cCount];
                for(int counter = 0; counter < cCount; counter++)
                    newChildren[counter] = node.getChildAt(childIndices[counter]);
                fireTreeNodesInserted(this, getPathToRoot(node), childIndices,
                        newChildren);
         * Invoke this method after you've removed some TreeNodes from
         * node.  childIndices should be the index of the removed elements and
         * must be sorted in ascending order. And removedChildren should be
         * the array of the children objects that were removed.
        public void nodesWereRemoved(XMLNode node, int[] childIndices,
                Object[] removedChildren)
            if(node != null && childIndices != null)
                fireTreeNodesRemoved(this, getPathToRoot(node), childIndices,
                        removedChildren);
         * Invoke this method after you've changed how the children identified by
         * childIndicies are to be represented in the tree.
        public void nodesChanged(XMLNode node, int[] childIndices)
            if(node != null)
                if (childIndices != null)
                    int cCount = childIndices.length;
                    if(cCount > 0)
                        Object[] cChildren = new Object[cCount];
                        for(int counter = 0; counter < cCount; counter++)
                            cChildren[counter] = node.getChildAt
                                    (childIndices[counter]);
                        fireTreeNodesChanged(this, getPathToRoot(node),
                                childIndices, cChildren);
                else if (node == getRoot())
                    fireTreeNodesChanged(this, getPathToRoot(node), null, null);
         * Invoke this method if you've totally changed the children of
         * node and its childrens children...  This will post a
         * treeStructureChanged event.
        public void nodeStructureChanged(XMLNode node)
            if(node != null)
                fireTreeStructureChanged(this, getPathToRoot(node), null, null);
         * Builds the parents of node up to and including the root node,
         * where the original node is the last element in the returned array.
         * The length of the returned array gives the node's depth in the
         * tree.
         * @param aNode the TreeNode to get the path for
        public XMLNode[] getPathToRoot(XMLNode aNode)
            return getPathToRoot(aNode, 0);
         * Builds the parents of node up to and including the root node,
         * where the original node is the last element in the returned array.
         * The length of the returned array gives the node's depth in the
         * tree.
         * @param aNode  the TreeNode to get the path for
         * @param depth  an int giving the number of steps already taken towards
         *        the root (on recursive calls), used to size the returned array
         * @return an array of TreeNodes giving the path from the root to the
         *         specified node
        protected XMLNode[] getPathToRoot(XMLNode aNode, int depth)
            XMLNode[] retNodes;
            // This method recurses, traversing towards the root in order
            // size the array. On the way back, it fills in the nodes,
            // starting from the root and working back to the original node.
            /* Check for null, in case someone passed in a null node, or
               they passed in an element that isn't rooted at root. */
            if(aNode == null)
                if(depth == 0)
                    return null;
                else
                    retNodes = new XMLNode[depth];
            else
                depth++;
                if(aNode == rootNode)
                    retNodes = new XMLNode[depth];
                else
                    retNodes = getPathToRoot((XMLNode)aNode.getParent(), depth);
                retNodes[retNodes.length - depth] = aNode;
            return retNodes;
        //  Events
         * Adds a listener for the TreeModelEvent posted after the tree changes.
         * @see     #removeTreeModelListener
         * @param   l       the listener to add
        public void addTreeModelListener(TreeModelListener l)
            listenerList.add(TreeModelListener.class, l);
         * Removes a listener previously added with <B>addTreeModelListener()</B>.
         * @see     #addTreeModelListener
         * @param   l       the listener to remove
        public void removeTreeModelListener(TreeModelListener l)
            listenerList.remove(TreeModelListener.class, l);
         * Returns an array of all the tree model listeners
         * registered on this model.
         * @return all of this model's <code>TreeModelListener</code>s
         *         or an empty
         *         array if no tree model listeners are currently registered
         * @see #addTreeModelListener
         * @see #removeTreeModelListener
         * @since 1.4
        public TreeModelListener[] getTreeModelListeners()
            return (TreeModelListener[])listenerList.getListeners(
                    TreeModelListener.class);
         * Notifies all listeners that have registered interest for
         * notification on this event type.  The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @param source the node being changed
         * @param path the path to the root node
         * @param childIndices the indices of the changed elements
         * @param children the changed elements
         * @see EventListenerList
        protected void fireTreeNodesChanged(Object source, Object[] path,
                int[] childIndices,
                Object[] children)
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            TreeModelEvent e = null;
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2)
                if (listeners==TreeModelListener.class)
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
    * Notifies all listeners that have registered interest for
    * notification on this event type. The event instance

  • PopupMenu on Jtree nodes Please [b]Help me][/b]

    how can I set my JpopupMenu to work on Jtree nodes and not on the tree?

    how can I set my JpopupMenu to work on Jtree nodes
    and not on the tree?Could you elaborate? Are you asking that popup events are ignored if the mouse click is not actually on the rendered area of a node or are you asking something else?

  • Allow right-click selection in a JTree

    Hi everybody! How are today? Fine? I hope so.
    I've got a little question about JTrees: i want to put a right-click popup menu on my JTree, which may not be the same depending on which node of the tree is selected.
    My problem is that i must do a left click selection of the node before doing the right click in order that this one may be effective and correct (i.e the correct popup menu appears).
    So, i want to allow the right click selection in my JTree to select the node and to perform the action linked to the Popup menu.
    I will be very thankfull if someone could help me :)

    Sorry to post twice, but just thought i'd post the code to show you what I mean (forgive me not making this entirely generic):
    ///// Some "global" variables:
         private JPopupMenu               stPopupMenu;
         private TreePath               stPath;
         private String                    stPathComponent;
         private int                         stCount;
         private Object                    selectedNode;
    ///// Attaching the listeners:
    symbolTreeDisplay.addTreeSelectionListener(stHandler);
    symbolTreeDisplay.addMouseListener(stHandler);
    //// The event listener class:
         private class SymbolTreeHandler extends MouseAdapter implements
                   TreeSelectionListener
              public void mouseClicked(java.awt.event.MouseEvent event)
                   try
                        if (event.getModifiers() == event.BUTTON3_MASK)
                        {//right button click on mouse
                             stPopupMenu = new JPopupMenu();
                             // add your logic here, based on selectedNode to add items to the menu
                             stPopupMenu.show(symbolTreeDisplay, event.getX(), event
                                       .getY());
                   catch (Exception e)
              public void valueChanged(TreeSelectionEvent aTreeEvent)
                   try
                        stPath = aTreeEvent.getPath();
                        stCount = stPath.getPathCount();
                        selectedNode = stPath.getPathComponent(stCount - 1);
                   catch (Exception e)
         }

  • JTree expand programatically is not working

    jTree1.fireTreeExpanded(curTreePath);
    expandAll(jTree1, curTreePath, true);
    jTree1.expandPath(curTreePath);
    jTree1.scrollPathToVisible(curTreePath);
    jTree1.updateUI();
    jTree1.setExpandsSelectedPaths(true);
    jTree1.expandPath(curTreePath);
    expandAll(jTree1, curTreePath, true);
    for (int i = 0; i < jTree1.getRowCount(); i++)
    jTree1.expandRow(i);
    jTree1.validate();
    jTree1.repaint();
    Any help ?

    package so;
    ToDo list
    * Log timestamp and line number of at every exception.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    import java.util.Enumeration;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    public class SCM extends javax.swing.JFrame implements javax.swing.event.TreeExpansionListener, javax.swing.event.TreeModelListener, javax.swing.event.TreeWillExpandListener
        Connection con = null;
        java.sql.Statement stmt = null;
        ResultSet rs = null;
        PrintStream log = null;// File creation at local system, to record events, actions, errors and traces
        javax.swing.tree.TreePath curTreePath = null;
        /** Creates new form SCM */
        public SCM()
            //---------------------- Native LookandFeel Windows is expected.-------------------//
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception e)
                System.out.println("Error setting native LAF: " + e);
            //******************** Native LookandFeel Windows is expected.*******************//
            // initialising GUI containers and controls
            initComponents();
            TableCellRenderer defaultRenderer;
            defaultRenderer = jTable1.getDefaultRenderer(JLabel.class);
            jTable1.setDefaultRenderer(JLabel.class, new Label_cell(defaultRenderer));
            setState(javax.swing.JFrame.HIDE_ON_CLOSE);
            jfc.setEnabled(false);
            this.setSize(1024, 740);
            jTree1.setSize(400, this.getWidth() / 4);
            jTree1.setRootVisible(false);
            jTree1.addTreeWillExpandListener(this); // Registering jTree1 to Expand listener.
            jTree1.setCellRenderer(new TreeIconRenderer());
            try
                //-------Preparing Logger----------------//
                FileOutputStream fos = new FileOutputStream(new File(System.getProperties().getProperty("user.home") + System.getProperties().getProperty("file.separator") + "SCM-Log_" + System.currentTimeMillis()));
                log = new PrintStream(fos);
                log.println("Started Time\t\t:" + new java.util.Date().getTime());
                //*******Preparing Logger****************//
                // Initialising jTree1 with the userid and preparing the xml and loading jTree1 with xml content,
                // and expected to repeat the same while refreshing.
                //----- Rendering images for the folders and files i.e. nodes and leaves of this tree
                jTree1 = new XMLTree("215");
                //******** Rendering images for the folders and files i.e. nodes and leaves of this tree
                //Selection can only contain one path at a time, i.e. user is confined to reffere to only one node
                //or leaf at a time
                //jTree1.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION);
                this.setTitle("ZIIC-ITG SCM");// Title can be changed at any time.
            catch (IOException ioe)
                ioe.printStackTrace(log);   //logging Exception.
                //This is first level action and to be decided to go further or not by exit(0);.
        public boolean prepareCon() throws ClassNotFoundException
            try
                if (con != null && !con.isClosed())
                    return true;
                else
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    java.sql.DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                    con = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@172.16.1.31:1521:soadb", "dms", "dms");
                    if (con != null && !con.isClosed())
                        return true;
            catch (java.lang.ClassNotFoundException cnfe)
                cnfe.printStackTrace(log);
            catch (SQLException se)
                se.printStackTrace(log);
            if (con != null)
                return true;
            else
                return true;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents()
            jPopupMenu1 = new javax.swing.JPopupMenu();
            jSplitPane1 = new javax.swing.JSplitPane();
            jScrollPane1 = new javax.swing.JScrollPane();
            try
                jTree1 = new XMLTree("215");
                jScrollPane2 = new javax.swing.JScrollPane();
                jTable1 = new javax.swing.JTable();
                menuBar = new javax.swing.JMenuBar();
                fileMenu = new javax.swing.JMenu();
                openMenuItem = new javax.swing.JMenuItem();
                saveMenuItem = new javax.swing.JMenuItem();
                saveAsMenuItem = new javax.swing.JMenuItem();
                exitMenuItem = new javax.swing.JMenuItem();
                editMenu = new javax.swing.JMenu();
                cutMenuItem = new javax.swing.JMenuItem();
                copyMenuItem = new javax.swing.JMenuItem();
                pasteMenuItem = new javax.swing.JMenuItem();
                deleteMenuItem = new javax.swing.JMenuItem();
                helpMenu = new javax.swing.JMenu();
                contentsMenuItem = new javax.swing.JMenuItem();
                aboutMenuItem = new javax.swing.JMenuItem();
                //setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            }catch(Exception e){}
            jTree1.setDoubleBuffered(true);
            jTree1.setDragEnabled(true);
            jTree1.setEditable(true);
            jTree1.setFocusTraversalPolicyProvider(true);
            jTree1.setInheritsPopupMenu(true);
            jTree1.setInvokesStopCellEditing(true);
            jTree1.setLargeModel(true);
            jTree1.setMaximumSize(new java.awt.Dimension(250, 64));
            jTree1.setPreferredSize(new java.awt.Dimension(200, 64));
            jTree1.setVerifyInputWhenFocusTarget(false);
            jTree1.addMouseListener(new java.awt.event.MouseAdapter()
                public void mouseClicked(java.awt.event.MouseEvent evt)
                    jTree1MouseClicked(evt);
            jTree1.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener()
                public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt)
                    jTree1TreeCollapsed(evt);
                public void treeExpanded(javax.swing.event.TreeExpansionEvent evt)
                    jTree1TreeExpanded(evt);
            jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener()
                public void valueChanged(javax.swing.event.TreeSelectionEvent evt)
                    jTree1ValueChanged(evt);
            jScrollPane1.setViewportView(jTree1);
            jSplitPane1.setLeftComponent(jScrollPane1);
            jScrollPane2.setAutoscrolls(true);
            jScrollPane2.setDoubleBuffered(true);
            jScrollPane2.setFocusCycleRoot(true);
            jScrollPane2.setFocusTraversalPolicyProvider(true);
            jScrollPane2.setInheritsPopupMenu(true);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String []
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jTable1.addMouseListener(new java.awt.event.MouseAdapter()
                public void mouseClicked(java.awt.event.MouseEvent evt)
                    jTable1MouseClicked(evt);
            jScrollPane2.setViewportView(jTable1);
            jSplitPane1.setRightComponent(jScrollPane2);
            fileMenu.setText("File");
            openMenuItem.setText("Open");
            fileMenu.add(openMenuItem);
            saveMenuItem.setText("Save");
            fileMenu.add(saveMenuItem);
            saveAsMenuItem.setText("Save As ...");
            fileMenu.add(saveAsMenuItem);
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    exitMenuItemActionPerformed(evt);
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            editMenu.setText("Edit");
            cutMenuItem.setText("Cut");
            editMenu.add(cutMenuItem);
            copyMenuItem.setText("Copy");
            editMenu.add(copyMenuItem);
            pasteMenuItem.setText("Paste");
            editMenu.add(pasteMenuItem);
            deleteMenuItem.setText("Delete");
            editMenu.add(deleteMenuItem);
            menuBar.add(editMenu);
            helpMenu.setText("Help");
            contentsMenuItem.setText("Contents");
            helpMenu.add(contentsMenuItem);
            aboutMenuItem.setText("About");
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt)
        try
            curTreePath = evt.getPath();
            //curTreePath.getPathCount();
            //selectedNode = stPath.getPathComponent(stCount - 1);
            //TODO add your handling code here:
            if (prepareCon())
                javax.swing.tree.TreePath path = evt.getPath();
                DMETreeNode node = (DMETreeNode) path.getLastPathComponent();
                try
                    if (node != null && (node.getSerial() + "").length() > 0)
                        //stmt = con.createStatement();
                        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                        rs = stmt.executeQuery("select serial, description, file_location, status, sheet,  part, approvedby, locked, location, created_by from dms_files where owner=" + node.getSerial());
                        SCM_Tbl_model model = new SCM_Tbl_model();
                        model.setRs(rs);
                        //jTable1.setColumnModel(columnModel);
                        jTable1.setModel(model);
                        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
                        jTable1.setRowSorter(sorter);
                catch (Exception e)
                    e.printStackTrace();
            catch (ClassNotFoundException ex)
                ex.printStackTrace(log);
                Logger.getLogger(SCM.class.getName()).log(Level.SEVERE, null, ex);
        private void jTree1MouseClicked(java.awt.event.MouseEvent evt)
        // TODO add your handling code here:   
        if (evt.getButton() == evt.BUTTON3)
            jPopupMenu1.removeAll();
            javax.swing.JMenuItem expandMI = new javax.swing.JMenuItem("Expand");
            javax.swing.JMenuItem expandAllMI = new javax.swing.JMenuItem("Expand All");
            javax.swing.JMenuItem find_folderMI = new javax.swing.JMenuItem("Find Folder");
            final javax.swing.JMenuItem new_folderMI = new javax.swing.JMenuItem("New Folder");
            javax.swing.JSeparator separator1 = new javax.swing.JSeparator();
            jPopupMenu1.setSize(100, 200);
            jPopupMenu1.add(expandMI);
            jPopupMenu1.add(expandAllMI);
            jPopupMenu1.add(separator1);
            jPopupMenu1.add(find_folderMI);
            jPopupMenu1.add(new_folderMI);
            jPopupMenu1.setVisible(true);
            jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
            //expandToLast(jTree1);
            //jTree1.scrollPathToVisible(curTreePath);
            //jTree1.fireTreeExpanded(curTreePath);       
            ActionListener menuOnTree = new ActionListener()
                        public void actionPerformed(ActionEvent e)
                            if (e.getSource().equals(new_folderMI))
                                    DMETreeNode ch=new DMETreeNode("Child of "+((DMETreeNode)curTreePath.getLastPathComponent()).toString());   
                                    ((DMETreeNode) curTreePath.getLastPathComponent()).add(ch);
                                    jTree1.fireTreeExpanded(curTreePath);
                                    expandAll(jTree1, curTreePath, true);
                                    jTree1.expandPath(curTreePath);
                                    jTree1.scrollPathToVisible(curTreePath);
                                    jTree1.updateUI();
                            if (e.getActionCommand().trim().equalsIgnoreCase("Expand"))
                                jTree1.setExpandsSelectedPaths(true);
                                jTree1.expandPath(curTreePath);
                                expandAll(jTree1, curTreePath, true);
                                for (int i = 0; i < jTree1.getRowCount(); i++)
                                    jTree1.expandRow(i);
                                jTree1.validate();
                                jTree1.repaint();
                                System.out.println(((DMETreeNode) curTreePath.getLastPathComponent()).getSerial());
                                expandToLast(jTree1);
                                System.out.println(jTree1.getModel().getRoot().toString());
                                ((XMLTree)jTree1).expandAll(true);
                                expandToLast(jTree1);
            expandMI.addActionListener(menuOnTree);
            expandAllMI.addActionListener(menuOnTree);
            find_folderMI.addActionListener(menuOnTree);
            new_folderMI.addActionListener(menuOnTree);
    public void expandAll(JTree tree, boolean expand)
            TreeNode root = (TreeNode) tree.getModel().getRoot();
            // Traverse tree from root
            expandAll(tree, new TreePath(root), expand);
        private void expandAll(JTree tree, TreePath parent, boolean expand)
            // Traverse children
            TreeNode node = (TreeNode) parent.getLastPathComponent();
            if (node.getChildCount() >= 0)
                for (Enumeration e = node.children(); e.hasMoreElements();)
                    TreeNode n = (TreeNode) e.nextElement();
                    TreePath path = parent.pathByAddingChild(n);
                    //System.out.println(path.toString());
                    expandAll(tree, path, expand);
            // Expansion or collapse must be done bottom-up
            if (expand)
                tree.expandPath(parent);
            else
                tree.collapsePath(parent);
    public void expandToLast(JTree tree)
            // expand to the last leaf from the root
            DefaultMutableTreeNode root;
            root = (DefaultMutableTreeNode) tree.getModel().getRoot();
            tree.scrollPathToVisible(new TreePath(root.getLastLeaf().getPath()));
            //System.out.println(""+root.getLastLeaf().getPath().toString());
        public void expandToLast(JTree tree)
            TreeModel data = tree.getModel();
            Object node = data.getRoot();
            if (node == null)
                return;
            TreePath p = new TreePath(node);
            while (true)
                int count = data.getChildCount(node);
                if (count == 0)
                    break;
                node = data.getChild(node, count - 1);
                p = p.pathByAddingChild(node);
            tree.scrollPathToVisible(p);
        private void jTree1TreeExpanded(javax.swing.event.TreeExpansionEvent evt)
        // TODO add your handling code here:
            System.out.println("@447");
        private void jTree1TreeCollapsed(javax.swing.event.TreeExpansionEvent evt) {                                    
        // TODO add your handling code here:
        private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
            System.exit(0);
        @SuppressWarnings("static-access")
        private void jTable1MouseClicked(java.awt.event.MouseEvent evt)                                    
            // TODO add your handling code here:
            jPopupMenu1.removeAll();
            jPopupMenu1.setVisible(true);
            //Prepare Menu items based the event and the user, and the item clicked on i.e.
            javax.swing.JMenuItem menuItem = new javax.swing.JMenuItem("Add A doc", KeyEvent.VK_T);
            jPopupMenu1.add(menuItem);
            ActionListener al = new ActionListener()
                        public void actionPerformed(ActionEvent e)
                            jfc.updateUI();
                            jfc.showOpenDialog(jTable1);
                            jTable1.setValueAt(jfc.getSelectedFile().getAbsolutePath(), jTable1.getSelectedRow(), jTable1.getSelectedColumn());
                            jfc.setDialogTitle("Choose only fmx files");
                            try
                                if (jfc.getSelectedFile().getAbsolutePath() != null)
                                    java.io.File f = new java.io.File(jfc.getSelectedFile().getAbsolutePath());
                                    if (f.exists())
                                        // Start FTP process.
                                        SCM_FTP ftp = new SCM_FTP();
                                        ftp.connect("ziicsrv11", 21, "z11902", "ziicit");
                                        ftp.bin();
                                        // Change to a new working directory on the FTP server.
                                        ftp.cwd("bin");
                                        // Upload some files.
                                        log.println("FTP Start: " + System.currentTimeMillis());
                                        ftp.stor(f);
                                        ftp.disconnect();
                                        log.println("FTP Done: " + System.currentTimeMillis());
                            catch (java.io.IOException ioe)
                                log.println("File is not Found");
                                ioe.printStackTrace(log);
            menuItem.addActionListener(al);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
            jPopupMenu1.setSize(100, 200);
            if (evt.getButton() == evt.BUTTON3)//evt.isPopupTrigger()
                jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
         * @param args the command line arguments
        public static void main(String args[])
            java.awt.EventQueue.invokeLater(new Runnable()
                        public void run()
                            SCM s = new SCM();
                            s.setVisible(true);
                            //s.setState(s.HIDE_ON_CLOSE);
                            s.setAlwaysOnTop(true);
                            SystemTrayTest st = new SystemTrayTest();
                            st.setControl(s);
                            st.showFrame();
        // Variables declaration - do not modify                    
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JMenuItem contentsMenuItem;
        private javax.swing.JMenuItem copyMenuItem;
        private javax.swing.JMenuItem cutMenuItem;
        private javax.swing.JMenuItem deleteMenuItem;
        private javax.swing.JMenu editMenu;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JPopupMenu jPopupMenu1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JSplitPane jSplitPane1;
        private javax.swing.JTable jTable1;
        private javax.swing.JTree jTree1;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenuItem openMenuItem;
        private javax.swing.JMenuItem pasteMenuItem;
        private javax.swing.JMenuItem saveAsMenuItem;
        private javax.swing.JMenuItem saveMenuItem;
        // End of variables declaration                  
        private javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
        public void treeExpanded(TreeExpansionEvent event)
        public void treeCollapsed(TreeExpansionEvent event)
        public void treeNodesChanged(TreeModelEvent e)
        public void treeNodesInserted(TreeModelEvent e)
        public void treeNodesRemoved(TreeModelEvent e)
        public void treeStructureChanged(TreeModelEvent e)
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException
    }

  • Cannot add popup to JTree

    Have implemented JTree treePanel using DefaultTreeModel.
    Created popupMenu.
    Created JTextArea output.
    In the end of createPopupMenu() method add following:
    treePanel.addMouseListener(popupListener);
    output.addMouseListener(popupListener);
    Result: Popup added to JTextArea and didn't add to JTree.
    (When I right mouse click on JTextArea, popup appears and when on JTree -- not)
    What is the problem? What is difference between JTextArea and JTree?

    Ok, the problem is following:
    class PopupListener extends MouseAdapter {
    JPopupMenu popup;
    PopupListener (JPopupMenu popupMenu) {
    popup = popupMenu;
    public void mousePressed(MouseEvent e) {
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
    maybeShowPopup(e);
    public void maybeShowPopup(MouseEvent e) {
    if (e.isPopupTregger()) {
    popup.show(e.getComponent(), e.getX(), e.getY());
    In GUImain class:
    public Container createContentPane() {
    tree = new MyTree();
    contentPane.add(tree, BorderLayout.PAGE_START);
    output = new JTextArea(5, 30);
    contentPane.add(output, BorderLayout.PAGE_END);
    public void createPopupMenu() {
    JPopupMenu popup = new JPopupMenu();
    // Create menu items
    MouseListener popupListener = new PopupListener(popup);
    output.addMouseListener(popupListener);
    tree.addMouseListener(popupListener);
    Popup menu appear on right click on output.
    tree doesn't react on right click.
    How to bind popup menu to JTree?

  • Need a popupmenu for a JTree

    hi folks,
    i need ur urgent help for this particular Java Code.
    I hav a JTree in my code. On clicking the root,its sub nodes expand.. When i right click on any of its Node, a PopupMenu shud appear.
    Can someone pla give me the entire code for this procedure.
    I hav tried lots of permutations and combinations, but its futile.
    Please post ur answer as soon as possible...
    Thanks a lot...
    divya

    Here you go :import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.tree.*;
    public class TreePanel extends JPanel {
         public JTree theTree;
         public JPopupMenu thePopupMenu;
         private class ActionEnabledTreeNode extends DefaultMutableTreeNode {
              private Action[] theActions;
              public ActionEnabledTreeNode(String aNodeName, Action[] someActions) {
                   super(aNodeName);
                   theActions = someActions;
              public Action[] getActions() {
                   return theActions;
         private class TreeMouseListener extends MouseAdapter {
              public boolean handledInPressed;
              public TreeMouseListener() {
                   handledInPressed = false;
              public void mousePressed(MouseEvent e) {
                   Point ptInTree = e.getPoint();
                   TreePath path = theTree.getPathForLocation(ptInTree.x, ptInTree.y);
                   if (path == null) {
                        handledInPressed = false;
                        return;
                   Rectangle rect = theTree.getPathBounds(path);
                   if (!rect.contains(ptInTree)) {
                        handledInPressed = false;
                        return;
                   if (SwingUtilities.isRightMouseButton(e)) {
                        theTree.setSelectionPath(path);
                   if (e.isPopupTrigger()) {
                        TreeNode node = (TreeNode)path.getLastPathComponent();
                        if (node instanceof ActionEnabledTreeNode) {
                             Action[] actions = ((ActionEnabledTreeNode)node).getActions();
                             Point ptInPanel = SwingUtilities.convertPoint(theTree, ptInTree, TreePanel.this);
                             thePopupMenu.removeAll();
                             for (int i = 0; i < actions.length; i++) {
                                  thePopupMenu.add(actions);
                             thePopupMenu.show(TreePanel.this, ptInPanel.x, ptInPanel.y);
                             handledInPressed = true;
                   } else {
                        handledInPressed = false;
              public void mouseReleased(MouseEvent e) {
                   Point ptInTree = e.getPoint();
                   TreePath path = theTree.getPathForLocation(ptInTree.x, ptInTree.y);
                   if (path == null) {
                        handledInPressed = false;
                        return;
                   Rectangle rect = theTree.getPathBounds(path);
                   if (!rect.contains(ptInTree)) {
                        handledInPressed = false;
                        return;
                   if (e.isPopupTrigger() && !handledInPressed) {
                        TreeNode node = (TreeNode)path.getLastPathComponent();
                        if (node instanceof ActionEnabledTreeNode) {
                             Action[] actions = ((ActionEnabledTreeNode)node).getActions();
                             Point ptInPanel = SwingUtilities.convertPoint(theTree, ptInTree, TreePanel.this);
                             thePopupMenu.removeAll();
                             for (int i = 0; i < actions.length; i++) {
                                  thePopupMenu.add(actions[i]);
                             thePopupMenu.show(TreePanel.this, ptInPanel.x, ptInPanel.y);
                             handledInPressed = true;
                   handledInPressed = false;
         public TreePanel() {
              super(new BorderLayout());
              thePopupMenu = new JPopupMenu("Tree node actions");
              theTree = new JTree(createTreeStructure());
              theTree.addMouseListener(new TreeMouseListener());
              add(new JScrollPane(theTree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS), BorderLayout.CENTER);
         public TreeNode createTreeStructure() {
              Action[] connectionActions = new Action[2];
              connectionActions[0] = new AbstractAction("connection action 1") {
                   public void actionPerformed(ActionEvent e) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)theTree.getSelectionPath().getLastPathComponent();
                        System.out.println("connection action 1 performed on " + node.getUserObject().toString());
              connectionActions[1] = new AbstractAction("connection action 2") {
                   public void actionPerformed(ActionEvent e) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)theTree.getSelectionPath().getLastPathComponent();
                        System.out.println("connection action 2 performed on " + node.getUserObject().toString());
              Action[] mappingActions = new Action[2];
              mappingActions[0] = new AbstractAction("mapping action 1") {
                   public void actionPerformed(ActionEvent e) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)theTree.getSelectionPath().getLastPathComponent();
                        System.out.println("mapping action 1 performed on " + node.getUserObject().toString());
              mappingActions[1] = new AbstractAction("mapping action 2") {
                   public void actionPerformed(ActionEvent e) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)theTree.getSelectionPath().getLastPathComponent();
                        System.out.println("mapping action 2 performed on " + node.getUserObject().toString());
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("-----");
              DefaultMutableTreeNode connection = new DefaultMutableTreeNode("Connection");
              DefaultMutableTreeNode childconn = new ActionEnabledTreeNode("Connection 1", connectionActions);
              DefaultMutableTreeNode childconn1 = new ActionEnabledTreeNode("Connection 2", connectionActions);
              DefaultMutableTreeNode mapping = new DefaultMutableTreeNode("Mapping");
              DefaultMutableTreeNode childmapping = new ActionEnabledTreeNode("Mapping 1", mappingActions);
              DefaultMutableTreeNode childmapping1 = new ActionEnabledTreeNode("Mapping 2", mappingActions);
              connection.add(childconn);
              connection.add(childconn1);
              mapping.add(childmapping);
              mapping.add(childmapping1);
              root.add(connection);
              root.add(mapping);
              return root;
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Test TreePanel");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new TreePanel());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(800, 600);
                        frame.setVisible(true);

  • Problem dismissing a JPopupMenu

    I have a DropDownCalendar class that extends JButton. I am inserting a calendar(JPanel) into a JPopupMenu. The JPopupMenu is then invoked by the user when they click on the DropDownCalendar button. When a user clicks on a date in the calendar, the dateChanged() action is called which sets the selected date and then hides the JPopupMenu. After I hide the JPopupMenu, I then have to click TWICE on the DropDownCalendar button before the mouse event is fired again to redisplay the popup. The button never receives the first mouse click, but then receives the second. I think the popup is grabbing the first mouse click. Is popup.setVisible(false) the right way to dismiss the popup?
    Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
    public class DropDownCalendar extends JButton {
         JLabel          dateLabel, arrowLabel;
         JPopupMenu jpm;
         SimpleCalendar scal;
         SimpleDateFormat dateFormatter;
         Dimension origin = new Dimension(0, 0);
         class MouseHandler extends MouseAdapter {
              public void mousePressed(MouseEvent me) {
                   jpm.show(me.getComponent(), 0, me.getComponent().getHeight());
    * DropDownCalendar constructor comment.
    public DropDownCalendar() {
         super();
         // Set display format to "Mon, Dec 31, 2001"
         dateFormatter = new SimpleDateFormat ("EEE, MMM d, yyyy");
         // Button contains two JLabels. One for the date string and another
         // for the up/down arrow.
         dateLabel = new JLabel("", JLabel.LEFT);
         arrowLabel = new JLabel(" \u25BC", JLabel.RIGHT);
         setMargin(new Insets(0,0,0,0));
         setLayout(new BorderLayout());
         add(dateLabel, BorderLayout.WEST);
         add(arrowLabel, BorderLayout.EAST);
         addMouseListener(new MouseHandler());
         scal = new SimpleCalendar();
         scal.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
         dateChanged();
         jpm = new JPopupMenu();
         jpm.setBorderPainted(false);
         jpm.add(scal);
         dateChanged();     // Trigger this to initialize the date string in the button
    private void dateChanged()
         // Set the date string the in the button
         dateLabel.setText(dateFormatter.format(scal.getSelection()));
         jpm.setVisible(false);

    I am having the same problem. If the JPopupMenu is visible and the user clicks somewhere else on the JPanel to select something else, the JPopupMenu goes away but the MouseEvent doesn't get called on the JPanel. The only MouseEvent I get is mouseEntered. I put a PopupMenuListener on the JPopupMenu and tried requesting focus and transfer focus to my JPanel but that doesn't work. I have noticed that it does work if the same code it applied to a JTable or JTree?? On a JTable after the popupMenuWillBecomeInVisible a mouseReleased event is fired on the JTable and it looks like it is coming from java.awt.LightweightDispatcher.retargetMouseEvent. How do I get this to work just using a JPanel?

Maybe you are looking for

  • Problem in Converting string to float

    Hi, I am reading from textField and trying to convert that string value to float. Compiler is giving error cannot find symbol toFloat even though I have included java.lang in my program. Please help me with this one. Thanks.

  • Get read-only error when trying to create via CI

    I have created a component interface of the VCHR_EXPRESS component (along with the proper component fix for an initialization issue). I had VS generate a create_ex XML schema to be used by BizTalk (PS adapter) to create a new voucher. When I try to e

  • Java Mail throws Connect failed error in Oracle 11g Enterprise  Edition

    Hi, I am using Oracle 11g Enterprise edition.I have a java class which is used for reading outlook 2010 inbox and download attachments from mails .For Connecting to OutLook from oracle i am using "POP3S" protocol in my java class. Which is working fi

  • I am having trouble opening a particular web page.

    I am a new mac user and have an imac. I am able to use Safari for every website, except for this one. http://www.milwaukeemoms.com/ Do I have to download something to be able to open/view the page? There is nothing wierd about this website (free, loc

  • Mail suddenly stopped working and also cannot access mail through Settings iphone 4

    The mail partially opens for a second and then crashes. I see some suggestions for deleting the mail program but when I go to Settings the Mail, Calendar and Contact button won't open.