TreeSelectionListener

A question about the TreeSelectionListener. I was having trouble adding the interface to my app, and after reading one of the examples under the JTree tutorials, I tried adding an import statement for TreeSelectionListener, along with TreeSelectionEvent, which fixed the problem. My question is, why is that necessary? I've never had to import a listener interface or event class before today, with ActionListener or MouseListener or any of the other commonly used interfaces. Thx.

That is probably just a fluke that you have never had to do this. Listener classes and interfaces are usually in different packages so you always will have to import those packages.
Bryan

Similar Messages

  • Problem about TreeSelectionListener

    hi there...
    i m programming some kind of editor...
    i added Jtree to JTabbedPane...
    and added JTabbedPane to Frame.
    when user select jtree.. i wanna know which Node is selected..
    so, i added TreeSelectionListener object to each of the Jtable...
    source code as follow...
    DefaultMutableTreeNode xmltree_t = new DefaultMutableTreeNode("None of Document loaded");
    m_model = new DefaultTreeModel(xmltree_t);
    xmltree = new JTree(m_model);
    // xmltree = new JTree(xmltree_t);
    xmltree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    xmltree.setShowsRootHandles(true);
    xmltree.setEditable(false);
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
    Color m_draggingBackground = new Color(0, 0, 128);
         Color m_draggingForeground = Color.white;
         Color m_standardBackground = getBackgroundNonSelectionColor();
         Color m_standardForeground = getTextNonSelectionColor();
         public Component getTreeCellRendererComponent(JTree tree,
    Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                   if (value.equals(m_draggingOverNode)) {
                        setBackgroundNonSelectionColor(m_draggingBackground);
                        setTextNonSelectionColor(m_draggingForeground);
                        sel = false;
                   }else {
                        setBackgroundNonSelectionColor(m_standardBackground);
                        setTextNonSelectionColor(m_standardForeground);
                   Component res = super.getTreeCellRendererComponent(tree,
                   value, sel, expanded, leaf, row, hasFocus);
                   if (value instanceof XmlViewerNode) {
    System.out.println("instanceof XmlViewNode-----------------");
                        Node node = ((XmlViewerNode)value).getXmlNode();
                        if (node instanceof Element)
                             setIcon(expanded ? openIcon : closedIcon);
                        else
                             setIcon(leafIcon);
                        return res;
              xmltree.setCellRenderer(renderer);
              m_treeEditor = new DefaultTreeCellEditor(xmltree, renderer) {
                   public boolean isCellEditable(EventObject event) {
                        Node node = getSelectedNode();
                        if (node != null && node.getNodeType() == Node.TEXT_NODE)
                             return super.isCellEditable(event);
                        else
                             return false;
                   public Component getTreeCellEditorComponent(JTree tree, Object value,
                        boolean isSelected, boolean expanded, boolean leaf, int row) {
                        if (value instanceof XmlViewerNode)
    System.out.println("instanceof XmlViewNode-----------------");
                             m_editingNode = ((XmlViewerNode)value).getXmlNode();
                        return super.getTreeCellEditorComponent(tree,
                             value, isSelected, expanded, leaf, row);
    m_treeEditor.addCellEditorListener(new XmlEditorListener());
    xmltree.setCellEditor(m_treeEditor);
    xmltree.setEditable(true);
    xmltree.setInvokesStopCellEditing(true);
    m_tableModel = new AttrTableModel();
    jtable = new JTable(m_tableModel);
    xtree = new JScrollPane(xmltree);
    xtree_e = new JScrollPane(jtable);
    // xtree_e.add(jtable);
    xtree_e.getViewport().setBackground(jtable.getBackground());
    // jsp_x = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, xtree, xtree_e);
    jsp_x = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, xtree, xtree_e);
    jsp_x.setDividerLocation(350);
    jsp_x.setDividerSize(5);
    xmltext = new JTextArea();
    linenumborder = new LineNumberBorder(Color.blue);
    xmltext.setBorder(linenumborder);
    xmltext.addFocusListener(new TextAreaFocusEvent());
    //xmltext.addCaretListener(new TextAreaChanged());
    xmltext.addCaretListener(statuscret);
    xmltext.setText(xmltextString);
    xmlsource = new JScrollPane(xmltext);
    se_xtree = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jsp_x, xmlsource);
    se_xtree.setDividerLocation(350);
    se_xtree.setDividerSize(10);
    se_xtree.setOneTouchExpandable(true);
    //----------------------------------end------------------------------------------
    TreeSelectionListener lSel = new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {
              Node node = null;
    if(whichdoc==0) {
    node = getSelectedNode();
    }else {
    node = getSelectedNode2();
    //System.out.println("xmltree selected Node" + node.toString());
              setNodeToTable(node);     // null is OK
              //enableNodeButtons();
              //enableAttrButtons();
    xmltree.addTreeSelectionListener(lSel);
    jtable.getSelectionModel().addListSelectionListener(new listselectionEvent());
    //enableNodeButtons();
    //enableAttrButtons();
    //-----------------------------------s t a r t----------------------------------------
    DefaultMutableTreeNode xsltree_t = new DefaultMutableTreeNode("None of Document loaded");
    xsl_model = new DefaultTreeModel(xsltree_t);
    xsl_tree = new JTree(xsl_model);
    xsl_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    xsl_tree.setShowsRootHandles(true);
    xsl_tree.setEditable(false);
    DefaultTreeCellRenderer renderer2 = new DefaultTreeCellRenderer() {
    Color m_draggingBackground = new Color(0, 0, 128);
         Color m_draggingForeground = Color.white;
         Color m_standardBackground = getBackgroundNonSelectionColor();
         Color m_standardForeground = getTextNonSelectionColor();
         public Component getTreeCellRendererComponent(JTree tree,
                   Object value, boolean sel, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
                   if (value.equals(m_draggingOverNode2)) {
                        setBackgroundNonSelectionColor(m_draggingBackground);
                        setTextNonSelectionColor(m_draggingForeground);
                        sel = false;
                   }else {
                        setBackgroundNonSelectionColor(m_standardBackground);
                        setTextNonSelectionColor(m_standardForeground);
                   Component res = super.getTreeCellRendererComponent(tree,
                   value, sel, expanded, leaf, row, hasFocus);
                   if (value instanceof XmlViewerNode2) {
    System.out.println("instanceof XmlViewNode2-----------------");
                        Node node = ((XmlViewerNode2)value).getXmlNode();
                        if (node instanceof Element)
                             setIcon(expanded ? openIcon : closedIcon);
                        else
                             setIcon(leafIcon);
                        return res;
    xsl_tree.setCellRenderer(renderer2);
    m_treeEditor2 = new DefaultTreeCellEditor(xsl_tree, renderer2) {
                   public boolean isCellEditable(EventObject event) {
                        Node node = getSelectedNode2();
                        if (node != null && node.getNodeType() == Node.TEXT_NODE)
                             return super.isCellEditable(event);
                        else
                             return false;
                   public Component getTreeCellEditorComponent(JTree tree, Object value,
                        boolean isSelected, boolean expanded, boolean leaf, int row) {
                        if (value instanceof XmlViewerNode2)
                             m_editingNode2 = ((XmlViewerNode2)value).getXmlNode();
                        return super.getTreeCellEditorComponent(tree,
                             value, isSelected, expanded, leaf, row);
    m_treeEditor2.addCellEditorListener(new XmlEditorListener2());
    xsl_tree.setCellEditor(m_treeEditor2);
    xsl_tree.setEditable(true);
    xsl_tree.setInvokesStopCellEditing(true);
    xsl_pane = new JScrollPane(xsl_tree);
    xsl_tree.addTreeSelectionListener(lSel);
    xsl_tableModel = new AttrTableModel2();
    xsl_table = new JTable(xsl_tableModel);
    xsl_pane2 = new JScrollPane(xsl_table);
    xsl_pane2.getViewport().setBackground(xsl_table.getBackground());
    xsl_table.getSelectionModel().addListSelectionListener(new listselectionEvent());
    xsl_split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, xsl_pane, xsl_pane2);
    //------------------------------------e n d-------------------------------------------
    xsltext = new JTextArea();
    xsltext.addFocusListener(new TextAreaFocusEvent());
    //xsltext.addCaretListener(new TextAreaChanged());
    xsltext.addCaretListener(statuscret);
    xsltext.setText(xsltextString);
    xslsource = new JScrollPane(xsltext);
    se_xstree = new JSplitPane(JSplitPane.VERTICAL_SPLIT, xsl_split, xslsource);
    se_xstree.setDividerLocation(350);
    se_xstree.setDividerSize(10);
    se_xstree.setOneTouchExpandable(true);
    //----------------------------------end------------------------------------------
    Method<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<public Node getSelectedNode() {
    XmlViewerNode treeNode = getSelectedTreeNode();
    System.out.println("-------------getSelectedNode method---------------------------");
    System.out.println(treeNode.toString());
    System.out.println("----------------------------------------");
    if (treeNode == null)
    return null;
    return treeNode.getXmlNode();
    public XmlViewerNode getSelectedTreeNode() {
    TreePath path = xmltree.getSelectionPath();
         if (path == null)
         return null;
         Object obj = path.getLastPathComponent();
         if (!(obj instanceof XmlViewerNode))
         return null;
         return (XmlViewerNode)obj;
    Method<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<lSel(TreeSelectionListener object) catch Event from User....
    but i can not get Event...
    error message is as follow...
    java.lang.NullPointerException
         at admintool.getSelectedNode2(admintool.java:579)
    how can if fix it...???
    i need your help....
    i will appreciate for your advice...
    thanz.. in advance...

    It works now.
    I have updated web.xml to below:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
          version="2.4">
      <servlet>
        <servlet-name>controller</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    </web-app>

  • Repaint in TreeSelectionListener Event

    Hi all,
    I am new to write a swing application which extends JFrame. I am displaying a JSplitPane object. On the top of the splitpane, I am displaying a JTree. My application is to display a table at the bottom of the splitpane according to what node user chooses in the JTree object (which invokes the TreeSelectionListener). It seems that the JFrame doesn't get update as I tried to do the following
    private class ResultFrame extends JFrame {
    JTree tree;
    JScrollPane treeScrollPane;
    JScrollPane tablePane;
    JSplitPane splitPane;
    public ResultFrame() {
    super("Results");
    init();
    setSize(800,400);
    centerWindow();
    show();
    private void init() {
    /* make the tree here */
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.addTreeSelectionListener(new TreeHandler());
    treeScrollPane = new JScrollPane(tree);
    tablePane = new JScrollPane();
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setTopComponent(treeScrollPane);
    splitPane.setBottomComponent(tablePane);
    getContentPane().add(splitPane);
    private class TreeHandler implements TreeSelectionListener {
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)((JTree)e.getSource()).getLastSelectedPathComponent();
    /* method makeTable() will make the table */
    JTable resultTable = makeTable();
    tablePane.removeAll();
    tablePane.add(resultTable);
    tablePane.setVisible(true);
    tablePane.doLayout();
    tablePane.revalidate();
    tablePane.repaint();
    this.doLayout();
    this.revalidate();
    this.repaint();
    Thanks for the help!!!

    Hello!
    Are you able to compile the code? Probably, you can't because
    this.doLayout();
    this.revalidate();
    this.repaint();and the compiler treats the this keyword as the instance of the the inner class & will throw few errors instead replace the code with the following, hope this helps you,
    ResultFrame.this.doLayout();
    ResultFrame.this.revalidate();
    ResultFrame.this.repaint();I'm no expert though, hope this helps you.
    regards,
    Afroze

  • TreeSelectionListener with JPanel is not reacting

    Hi all!
    I have class which extends JPanel, and is later docked in a side menu. The effect should be like the Tools menu in VisualStudio.
    Inside the JPanel I have a JTree. And the TreeSelectionListener isn't working. I tried the JTree code in a plain project and it works. So I figure it's something to do with the JPanel.
    Here my code with the JTree
    package de.lmu.ifi.pst.swep.rid.gui;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.Map;
    import java.util.TreeMap;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import com.vlsolutions.swing.docking.DockKey;
    import com.vlsolutions.swing.docking.Dockable;
    import de.lmu.ifi.pst.swep.rid.cartridgeInterface.AbstractCartridgeElement;
    import de.lmu.ifi.pst.swep.rid.cartridgeInterface.AbstractModelElement;
    import de.lmu.ifi.pst.swep.rid.cartridgeInterface.ICartridge;
    import de.lmu.ifi.pst.swep.rid.cartridgeloader.CartridgeLoader;
    import de.lmu.ifi.pst.swep.rid.cartridgeloader.ComponentLoader;
    import de.lmu.ifi.pst.swep.rid.interfaces.ICartridgeBay;
    import de.lmu.ifi.pst.swep.rid.utils.IconProvider;
    import de.lmu.ifi.pst.swep.rid.utils.Settings;
    import de.lmu.ifi.pst.swep.rid.utils.IconProvider.Identifier;
    * The toolbar for selecting canvas tools, such as select and new Cartridge
    * Element creation.
    public class CartridgeToolbar extends JPanel implements Dockable, ICartridgeBay {
         static {
              Settings.register("cartridge.selection.none", false);
              Settings.register("cartridge.selection.default", true);
              Settings.register("cartridge.selection.user", false);
              Settings.register("cartridge.selection.xul", true);
              Settings.register("cartridge.selection.uml", true);
         private static final long serialVersionUID = 8926943523499013449L;
         private DockKey dockKey = new DockKey("cartridgeToolbar", "Tools", null, IconProvider
                   .getSmallImage(Identifier.VIEW_TOOLS));
         private Map<String, ArrayList<AbstractCartridgeElement>> cartridgeGroups = new TreeMap<String, ArrayList<AbstractCartridgeElement>>();
         private JTree cartridgeTree;
         public CartridgeToolbar(ComponentLoader componentLoader) {
              super();
              dockKey.setFloatEnabled(true);
              dockKey.setMaximizeEnabled(false);
              dockKey.setResizeWeight(0.1f);          
              this.setLayout(new BorderLayout());          
              setPreferredSize(new Dimension(200, 600));
              cartridgeTree = new JTree(new DefaultMutableTreeNode("Unpainted tree"));
              DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                 renderer.setOpenIcon(null);
                 renderer.setClosedIcon(null);
                 renderer.setLeafIcon(null);
                 cartridgeTree.setCellRenderer(renderer);
              cartridgeTree.putClientProperty("JTree.lineStyle", "None");
              DefaultTreeSelectionModel selectionModel = new DefaultTreeSelectionModel();
                 selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              cartridgeTree.setSelectionModel(selectionModel);
              fillTreeWith("cartridgexul.xml");
              fillTreeWith("cartridgeuml.xml");
              cartridgeTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {//FIXME: listener not working
                   @Override
                   public synchronized void valueChanged(TreeSelectionEvent e) {
                      DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                      System.out.println("You selected " + node);
              cartridgeTree.putClientProperty("JTree.lineStyle", "None");
              cartridgeTree.setSelectionModel(null);
              JScrollPane scrollPane = new JScrollPane(cartridgeTree);
              this.add(scrollPane, BorderLayout.CENTER);
          * Method returns the name of the currently selected Cartridge Element that is to be drawn on the canvas
          * @return
          *           Name of the selected cartridge element.
         public String getSelectedElement()
            //TODO: if inner node
              return cartridgeTree.getLastSelectedPathComponent().toString();          
         private void fillTreeWith(String cartrigdeFileName)
              File dir = new File(".");
              String rootPath;
              try {
                   rootPath = dir.getCanonicalPath() + File.separator + "resources";
                   addCartridge(rootPath, cartrigdeFileName);
              } catch (IOException e) {
                   e.printStackTrace();
         public void addCartridge(String rootPath, String cartrigdeFileName) {
              CartridgeLoader catridgeLoader = new CartridgeLoader(rootPath, cartrigdeFileName);
              ICartridge cartridgeInterface = catridgeLoader.loadCartridge();
              final String nameCartridge = cartridgeInterface.getCartridgeName();
              ArrayList<AbstractCartridgeElement> catridgeGroupElements = generateFactories(cartridgeInterface);
              DefaultMutableTreeNode root = (DefaultMutableTreeNode) cartridgeTree.getModel().getRoot();
              DefaultMutableTreeNode cartridgeGroupNode= new DefaultMutableTreeNode(nameCartridge);
              DefaultMutableTreeNode elementNode ;
              DefaultMutableTreeNode subElementNode;
              for (AbstractCartridgeElement element : catridgeGroupElements) {
                   elementNode = new DefaultMutableTreeNode(element.getElementName());//TODO: add icon
                   subElementNode = new DefaultMutableTreeNode(element.getElementName() + "1");
                   elementNode.add(subElementNode);
                   subElementNode = new DefaultMutableTreeNode(element.getElementName() + "2");
                   elementNode.add(subElementNode);
                      cartridgeGroupNode.add(elementNode);//TODO: add subType          
              root.add(cartridgeGroupNode);
              cartridgeGroups.put(cartridgeInterface.getCartridgeName(), catridgeGroupElements);
          * With getting a new cartridge interface the method will be able to create
          * all factories of the cartridge interface. Element factories are used to
          * add new elements to the canvas.
          * @return List of factories belonging to a cartridge interface
         private ArrayList<AbstractCartridgeElement> generateFactories(ICartridge cartridgeInterface) {
              ArrayList<AbstractCartridgeElement> cartridgeGroupElements = new ArrayList<AbstractCartridgeElement>();
              for (Enumeration<Integer> el = cartridgeInterface.getElementIDs(); el.hasMoreElements();) {
                   cartridgeGroupElements.add(cartridgeInterface.getElementFactoryByID((Integer) el.nextElement()));
              return cartridgeGroupElements;
         @Override
         public DockKey getDockKey() {
              return dockKey;
         @Override
         public AbstractModelElement createCartridgeElement(String id) {
              // getElementFactoryByID
              return null;
         @Override
         public Component getComponent() {
              // TODO Auto-generated method stub
              return null;
         @Override
         public JComponent getComponent(String path, String cartridgeName) {
              // TODO Auto-generated method stub
              return null;
         @Override
         public void setButtonGroup(ButtonGroup buttongroup) {
              // TODO Auto-generated method stub
    }The most important is ofcourse the constructor. Any suggestions and help would be greatly apprieciated.
    best of all,
    Szymon

    cartridgeTree.setSelectionModel(null);You creating a new selection model, add it to the tree and add a listener to it. Then you throw it away.

  • GetSelectionPaths() in a separate TreeSelectionListener-Method

    I've define a JTree-Class with the Attribute "JTree jtree".
    like this:
    public class XY implements ActionListener{
         JTree tree=null;     
    Furthermore in a method addSelectionListener() in this class I add a TreeSelectionListener.
    If now a SelectionEvent occurs the code branch in the valuChanged-Method of
    the SelectionListener. There I try to get the selected items by "tree.getSelectionPaths()".
    And olthough I had selected some items the result I got is null.
    But if I define the addSelectonListener() in this way: addSelectonListener(jtree) it works.
    Why this ??
    Any ideas?
    incs

    Hi Josh,
    I've tryed to separate my problem. Following the extract. Now the problem seems to be reduced to the effect to assign the selection listener to only one tree-instance, videlicet for the tree that was instantiated at last.
    public class JTreeSel
    extends JFrame
    DefaultTreeModel treeModel=null;
    DefaultMutableTreeNode root=null;
    DefaultMutableTreeNode treeNode=null;
    JTree tree,vinTree,proNotree=null;
    public JTreeSel(){
    public void generateTree(){
    JTabbedPane tp = new JTabbedPane();
    root = new DefaultMutableTreeNode("root");
    root.add(new DefaultMutableTreeNode("one"));
    root.add(new DefaultMutableTreeNode("two"));
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setRootVisible(true);
    this.addSelectionListener();
    tp.add(tree);
    root = new DefaultMutableTreeNode("root2");
    root.add(new DefaultMutableTreeNode("one2"));
    root.add(new DefaultMutableTreeNode("two2"));
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setRootVisible(true);
    this.addSelectionListener();
    tp.add(tree);
    this.getContentPane().add(tp);
    public void addSelectionListener(){
    tree.addTreeSelectionListener(
    new TreeSelectionListener(){
    public void valueChanged(TreeSelectionEvent event){
    TreePath[] selections = tree.getSelectionPaths();
    TreePath tp = event.getNewLeadSelectionPath();
    if (tp!=null && tp.getLastPathComponent().toString()!=null && ((DefaultMutableTreeNode)
    tp.getLastPathComponent()).isLeaf()){
    if (selections != null) {
    for (int i = 0; i < selections.length; i++) {
    TreePath selectedProdSet = selections;
    System.out.println("SelektierterTreePath[]: " + selectedProdSet.toString());
    } else {
    System.out.println(" no leaf element selected");

  • Bad loop in TreeSelectionListener!!!

    I have a tree selection listener like this:
                   Tree.addTreeSelectionListener(new TreeSelectionListener() {
                        public void valueChanged (TreeSelectionEvent e) {                    
                             DefaultMutableTreeNode node = (DefaultMutableTreeNode) Tree.getLastSelectedPathComponent();
                             if (node == null) {
                                  return;
                             if (node.getUserObject() instanceof NodeInfo) {
                                  NodeInfo nodeInfo = (NodeInfo) node.getUserObject();
                                  nodeInfo.select(node);                         
                             } else
                                  return;
    Method select() is called whenever a node is selected and performs some actions. My problem is that whenever I select 2 nodes consecutively, the method select loops 2 times, whenever i select 3 nodes consecutively it loops 3 times, and so on. Can anyone help? A sample of my select method is here:
    public void select(final DefaultMutableTreeNode top) {
      DefaultMutableTreeNode vehicleNodes;
      Counts VehicleInfos = new Counts(frame);               
      frame.VariableTable.setValueAt("Short Name", 0, 0); 
      frame.VariableTable.setValueAt(ProjectShortName, 0, 1); 
    }

    There aren't any "loops" there. The method is naturally being called each time you select a node.

  • JTree RootHandles and TreeSelectionListener

    Hello!
    I have the following problem
    I create a tree using vector( the vector contains other vectors etc).
    I also create a TreeSelectionListener that when I select the leafs of this tree,leafs to become nodes,expand and contain new leafs.
    Unfortunately,when I use it, the listener is triggered only when I click
    on the icons I use. If I click on the roothandle in front of the icon it does nothing and the roothandle disappears.I think this happens because it remains leaf.
    Why the two clicks differ?
    How can I make the roothandle to trigger with the listener?

    Try this:
    jt.addTreeWillExpandListener(new TreeWillExpandListener() {
        public void treeWillCollapse(TreeExpansionEvent e) {
        public void treeWillExpand(TreeExpansionEvent e) {
            // The tree
            JTree tree = (JTree) e.getSource();
            // Get parent of node that will be expanded
            TreePath path = e.getPath();
            TreeNode node = (TreeNode) path.getLastPathComponent();
            TreeNode parent = node.getParent();
            // Get nodes of path
            Object[] pathNodes = path.getPath();
            int lastNode = pathNodes.length - 1;
            // Find currently open node under parent
            Enumeration enum = parent.children();
            while ( enum.hasMoreElements() ) {
                DefaultMutableTreeNode kid = (DefaultMutableTreeNode)
                    enum.nextElement();
                // Get path to kid
                pathNodes[lastNode] = kid;
                TreePath kidPath = new TreePath( pathNodes );
                if ( tree.isExpanded( kidPath ) ) {
                    // Collapse this node
                    tree.collapsePath( kidPath );
                    // Remove its kids
                    kid.removeAllChildren();
                    // Add in dummy node so it still has kids
                    DefaultMutableTreeNode placeholder = new
                        DefaultMutableTreeNode( "placeholder" );
                    kid.add( placeholder );
                    // Let model know it has changed
                    ( (DefaultTreeModel) tree.getModel() ).
                        nodeStructureChanged( kid );
                    // Done here
                    break;
    });

  • ADF swing tree TreeSelectionListener on view object

    hi
    i want to make an action according to the selection on a tree, and i don't know how to reach a view object and perform some event. i have made a method in the VO and put it in the client interface, but how to drag it to a specific node in the tree??
    this is the code:
    class TAction implements TreeSelectionListener
    public void actionPerformed(ActionEvent e)
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
    jTree1.getLastSelectedPathComponent();
    if (node != null){
    CreateDocumentForm gu = null;
    if(node.isLeaf()){
    String userinfo = node.getUserObject().toString();
    String parentinfo = ((DefaultMutableTreeNode)node.getParent())
    .getUserObject().toString();
    if ("All Document".equals(parentinfo)){
    if ("By Number".equals(userinfo)){
    JUControlBinding jucd = panelBinding.findControlBinding("sortByNumber");//the method in the VO is sortByNumber
    jucd.refreshControl();
    if ("By Status".equals(userinfo)){
    if ("By Project".equals(userinfo)){
    if ("By Creation Date".equals(userinfo)){
    }

    hi
    the method is not in the pageDef, how can expose it there if this solves the problem?
    the sortByNumber is working when i attach it to a button from the Data Control panel.
    what about using the setControl in the JUControlBinding, but i have problems using it.
    anyway, i want any solution to the problem as i need to attach the method in the VO programatically to the node in the tree TreeSelectionListener

  • [jclient] TreeSelectionListener question

    Hi,
    I have a tree with a set of JUTreeDiscrAttrTypeBindings so each polymorphic row, based on a discriminator, has it's own icon etc.
    Now, in the valueChanged() method of the TreeSelectionListener I added, I need to know what type of thingee I have clicked. I've tried this:
    public void valueChanged(TreeSelectionEvent e)
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
        if (node != null)
          JUTreeNodeBinding tnb = (JUTreeNodeBinding)(node.getUserObject());
          ViewObject vo = tnb.getParent().getViewObject();
          Row r = vo.getCurrentRow();
          if (r!=null)
            System.out.println("Rowtype: "+r.getAttribute("type"));
      }However, r is always null, but I expected the selected row there. The type attribute is the discriminator of the entities of the view object that I used for the tree.
    What's wrong in this example, or what is the correct way to retrieve this attribute?
    Greetings,
    Ivo

    I believe this is duplicate thread from :
    JUTreeNodeBinding question (nullpointer exception in getAttribute) (JUTreeNodeBinding question (nullpointer exception in getAttribute)
    Ivo, let us know if you're situation is resolved with the discussion in the above thread (started by you)

  • TreeSelectionListener() - one click two events!

    Hi, I am working with a JTree, when I click a leaf node it fires two events and so the code handling the event runs twice (this is not a double click just clicking on the leaf node). Obviously this not what I want and I do not want to have to build a 'memory' into the associated classes as this seems a bit messy. I am still working to resolve this issue for myself and have 'googled it'. If I resolve the issue I will post back but any help gratefully received......
    Trevor
    The associated code I am using is shown below:
    //instantiation of the Tree:
    jTreeSubjects = new javax.swing.JTree(rootNode);
    jTreeSubjects.setEditable(true);
    //setting selection model and attatching the listener:   
    jTreeSubjects.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            jTreeSubjects.setShowsRootHandles(true);
            jTreeSubjects.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent e) {
                    jTreeSubjectsValueChanged(e);
    //Handeling the events
    private void jTreeSubjectsValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                          
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTreeSubjects.getLastSelectedPathComponent();
            if (node == null){
                return;
            RegionTreeNode nodeInfo = (RegionTreeNode) node.getUserObject();
            if (node.isLeaf()){
                RegionTreeNode RegionTreeNodeSelected = nodeInfo;
                System.err.println(RegionTreeNodeSelected.file.getAbsoluteFile());
            } else {
                return;
    }

    Just to explain
    I added the code shown using the post creation code feature in netbeans, Prior to this I had added a handler for event valuechanged (jTreeSubjectsValueChanged). Hence one component two listners.

  • TreeSelectionListener detect if mouse click

    hi,
    i've got a JTree and I'm using a TreeSelectionListener to carry out different actions when the user clicks on nodes. however, sometimes i want to change the selection on the tree programmatically (i know how to do this bit), and for the action associated with clicking on the node not to happen.
    is it possible within the valueChanged method of the TreeSelectionListener to determine if the selection was changed by a mouse click or programmatically? or can anyone think of another way to approach this?
    cheers for any help!

    You can't do that with the event, but if you create a boolean variable named for example
    boolean programSelection = false;
    and when you change the selection programmatically you put the value to true. In the method valueChanged you have to test the value of programSelection like that :
    public void valueChanged(ChangeEvent e) {
       if (programSelection) {
          // the code when the selection come from the program
         programSelection = false;
       else {
          // the code when the selection come from the user
    }

  • TreeSelectionListener  valueChanged() called twice on selecting TreeNode

    Hi All,
    This is a class which extends JTree class forms a Tree displaying employee information.Listener is written which should find the list of selected Employee nodes of tree component.
    The method valueChanged() of treeListener is getting called twice for every node selected. Please find the code.
    Is there any alternative to find the list of selected nodes when they are selected using mouse or shift key.
    Even I am facing this in case of row selection of JTable.The listener method is called twice. Could you please let me know your views and any tutorials or examples codes for handling such cases.
    public class TestingTreeModel extends JTree {
         //public vector myMOType;
         public TestingTreeModel() {
              super();
         public void setData(ArrayList testVOs) {
              // set the option of selecting multiple nodes
              this.getSelectionModel().setSelectionMode(
                   TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
              this.setRootVisible(false);
              setModel(rootTreeNode, testVOs);
              // DefaultTreeModel is used.
              this.setModel(new DefaultTreeModel(rootTreeNode));
              // Listener for selected nodes..
              MyTreeSelectionListener myTreeListener = new MyTreeSelectionListener();
              this.addTreeSelectionListener(myTreeListener);
    // which sets the data.
         public void setModel(DefaultMutableTreeNode rootNode, ArrayList empVOs) {
              if empVOs!= null && empVOs.size() > 0) {
                   Iterator empItr = empVOs.iterator();
                   while (neItr.hasNext()) {
                        Employee empVO = (Employee) empItr.next();
                        DefaultMutableTreeNode node =
                             new DefaultMutableTreeNode(empVO.getName());
                        rootNode.add(node);
    // Listener
         public class MyTreeSelectionListener implements TreeSelectionListener {
              public void valueChanged(TreeSelectionEvent evt) {
                   // Get all nodes whose selection status has changed     
                   System.err.println("Listener is called here check how many times");
                   getSelectedNodes(evt);
         private void getSelectedNodes(TreeSelectionEvent evt) {
              System.err.println("came inside getSelectedNodes");
              TreePath[] paths = evt.getPaths();
              // Iterate through all affected nodes
              System.err.println(" Length is " + paths.length);
              for (int i = 0; i < paths.length; i++) {
                   TreePath tp = paths;
                   Object[] o = tp.getPath();
                   for (int j = 0; j < o.length; j++) {
                        System.out.println(
                             "Class: " + o[j].getClass() + "; value: " + o[j]);
                        if (o[j] instanceof DefaultMutableTreeNode) {
                             Object uo = ((DefaultMutableTreeNode) o[j]).getUserObject();
                             if (uo != null) {
                                  System.out.println(
                                       "\tUser object class: "
                                            + uo.getClass()
                                            + "; value: "
                                            + uo);
         private ArrayList empIDList = new ArrayList();
         private DefaultMutableTreeNode rootTreeNode = null;
    Thanks in advance.

    Hi Arun,
    JDev version is Studio Edition Version 11.1.1.5.0.
    Yes, i do have value change listener on the CompanyName LOV. What is a parameter form? The LOV is defined on the page in the following way:
                                <af:selectOneChoice value="#{bindings.CompanyName.inputValue}"
                                                    required="#{bindings.CompanyName.hints.mandatory}"
                                                    shortDesc="#{bindings.CompanyName.hints.tooltip}"
                                                    id="soc1" autoSubmit="true"
                                                    unselectedLabel="--select--"
                                                    contentStyle="width:17em;"
                                                    binding="#{backingBeanScope.backing_Company.soc1}"
                                                    valueChangeListener="#{backingBeanScope.backing_Company.companyChangeListener}">
                                  <f:selectItems value="#{bindings.CompanyName.items}"
                                                 binding="#{backingBeanScope.backing_Company.si1}"
                                                 id="si1"/>
                                </af:selectOneChoice>

  • Order of Execution for TreeSelectionListener

    Hi,
    I have a JTree on which I have registered 2 separate TreeSelectionListeners A and then B. I thought they would by default execute in a first-in first-out way, such as firstly A, secondly B, but to my surprise when I change a selection, listener B executes first!. As far as I have read, the only way to attain listener A executing first, is to re-register the listeners in the desired order when I register listener B.
    Am I correct? Is this the only way? Looks weird that the API doesn't preview this case.
    Thanks for your help,
    Chal.lo.

    As far as I have read, the only way to attain listener A executing first, is to re-register the listeners in the desired orderWherever you might have read that, it's not correct. From
    [Java AWT: Delegation Event Model|http://java.sun.com/j2se/1.3/docs/guide/awt/designspec/events.html]
    (about a third of the way down the page)
    The API makes no guarantees about the order in which the events are delivered to a set of registered listeners for a given event on a given source.
    In the same paragraph:
    If the order in which events are delivered to listeners is a factor for your program, you should chain the listeners off a single listener which is registered on the source (the fact that the event data is encapsulated in a single object makes propagating the event extremely simple).
    db

  • 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));
    }

  • Problem in getting selected values from multiselect list

    Hi,
    I have two multiselect listboxes in my page. In List1 the data will be retrieved from DB and listed.I will have buttons to move the values from List1 to List2 and viceversa.
    After selecting the needed values,I can rearrange them in List2 using some buttons. I have coded this moving and reordering using javascript.
    What happens is while submitting the page I want the values from list2 which are rearranged. But im getting the order in which I moved from list1 to list2.
    I am using html:selectfor both lists
    List1
    <html:select name="CustForm" property="custName" multiple="true" size="10">
           <html optionsCollection property="CustomerNames" value="custName" label="id"/>
    </html:select>I am having a customer form which has a arraylist CustomerNames. This arraylist has customer bean which has proeprties custName and id. The custForm also has a String custName.
    List2
    <html:select name="CustForm" property="selectedCustName" multiple="true" size="10">
           <html  option value=""/>
    </html:select> The custForm also has a String[] selectedCustNames from where I get the selected values in list2
    Please let me know what am I doing wrong here.

    use a treeSelectionListener, that will give you all the selection changes you need.
    thomas

Maybe you are looking for