Implementing listener in JTree

Hi,
I am trying to implement a listener for JTree within a class other than the one where is tree is initialized and set. With this listener, I would like to grab the index of the selected child from a tree. Do I only need to implement void ValueChanged() or is there something else that is missing because it is not working. Hope you can help me. Thanks.
Here is what I am doing:
//Declaration of class
public class ServerJobList extends JTree implements TreeSelectionListener
//Listener
public void valueChanged(TreeSelectionEvent e) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode)
          getLastSelectedPathComponent();
if (node == null) return;
if(node.isLeaf()){
     DefaultMutableTreeNode parent=(DefaultMutableTreeNode)node.getParent();
//Get index of selected item from tree.
selectedIndex=parent.getIndex(node);
String sServer=parent.toString();
zServer=Document.getClient().getServerList().getServerByName(sServer);
displayInfoList(selectedIndex);
//Testing....
System.out.println(sServer + "'s index= " + selectedIndex);

May someone please help me with this question. I am getting headaches trying to figure out what could be going wrong? Thanks.

Similar Messages

  • Implement listener and tns

    Hai all,
    How do implement listener in the new oracle home after upgrading the EBS DB to 11gr2.
    DB in the new server now

    user12046873 wrote:
    Hai all,
    How do implement listener in the new oracle home after upgrading the EBS DB to 11gr2.
    DB in the new server nowCopy the listener.ora file from the old ORACLE_HOME to the new ORACLE_HOME and edit the path. Or, you could simply run netca from the new ORACLE_HOME.
    Interoperability Notes Oracle EBS 11i with Oracle Database 11gR2 (11.2.0) [ID 881505.1] -- Start the new database listener (conditional)
    Interoperability Notes EBS 12.0 and 12.1 with Database 11gR2 [ID 1058763.1] -- Start the new database listener (conditional)
    Thanks,
    Hussein

  • Servlet also implementing listener interface

    Hi,
    Can I have a servlet "extends HttpServlet" and "implements HttpSessionListener" at the same time? If I add both a listener and a servlet element in deployment descriptor, how the container will instaniate/initialize the servlet/listener?
    Thanks.

    Hi,
    Can I have a servlet "extends HttpServlet" and
    "implements HttpSessionListener" at the same time? Yes, of course. Plenty of examples of this elsewhere in Java (e.g., java.awt.Canvas).
    If
    I add both a listener and a servlet element in
    deployment descriptor, how the container will
    instaniate/initialize the servlet/listener?Same way it always does: by calling the HttpServlet ctor. The fact that there's a new Listener interface doesn't affect that.
    You're on the hook to implement the interface's methods and make sure they're called appropriately.
    Whether this is a good design or not is another question. (I don't know the answer.)
    Thanks.You're welcome. - %

  • Implementing listener in JcomboBox

    I am trying to create JcomboBox in which its item are
    a)1
    b)2
    so that when a user click on 1. In a JTextField called "add"the content of textfield should be increased by 1 and when 2 is clicked content of textfield should be increased by 2
    thanx

    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
    HTH!

  • Listener Interface implementation questions

    Dear all experts,
    I am getting a bit confused of the "standard" way of implementing listener interfaces.
    I found that there are 3 general methods:
    1) create an extra class implementing the interface.
    2) implement the interface as an inner class
    3) using the existing class to implement the inferface :
    eg:
    public class oneofmyclass implement FocusListener
    public oneofmyclass()
    constructor....
    all my other methods.........
    the interface methods......
    Why there are so many ways to do it?
    what's the differences/benefits of each??
    Thx

    I am getting a bit confused of the "standard" way of implementing listener interfaces.
    I found that there are 3 general methods:
    1) create an extra class implementing the interface.
    2) implement the interface as an inner class
    3) using the existing class to implement the inferfaceThere isn't much difference between 1) and 2). The first alternative creates a named inner class
    (that implements the listener interface) while the second creates an anonymous class using that
    listener interface. Alternative 3) exposes the interface to the outer world, i.e. your class may be
    attached to some listener list (in some observable) it really wasn't meant for.
    I prefer 1) or 2) If the actual code for the listener is small I use 2), otherwise I use 1) but that's
    just for readability reasons. I almost never use 3) because I don't want my class to be hooked
    up to any observable it wasn't designed for.
    kind regards,
    Jos

  • Jtree startEditingAtPath cannot work

    I want my JTree to be always automatically goes into editing mode everytime a node is selected. I have add a treeselectionlistener that will initiate startEditingAtPath everytime the tree selection changed. However, the celleditor just won't show.
    Here is my code:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.util.LinkedList;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class MyTreePane extends JScrollPane implements TreeSelectionListener{
         private JTree tree;
         private DefaultTreeModel treeModel;
         private DefaultMutableTreeNode rootNode;
        public MyTreePane() {
            super();
            setPreferredSize(new Dimension(950,330));
            setMinimumSize(new Dimension(950,330));
            setSize(new Dimension(950,330));
            revalidate();
            rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            tree.setBackground(Color.lightGray);
            MyCellRenderer renderer = new MyCellRenderer();
             tree.setCellRenderer(renderer);
             tree.setCellEditor(new MyCellEditor(tree,renderer));
            tree.setEditable(true);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
            tree.setRootVisible(false);
              tree.setDragEnabled(false);
              setViewportView(tree);
              DefaultMutableTreeNode firstNode = new DefaultMutableTreeNode("Good");
              treeModel.insertNodeInto(firstNode, rootNode, 0);
              tree.scrollPathToVisible(new TreePath(firstNode.getPath()));
              tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              tree.addTreeSelectionListener(this);
              tree.setSelectionPath(new TreePath(firstNode.getPath()));
        public void insertNewRowAfter(int index){
              DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
              treeModel.insertNodeInto(newNode, rootNode, index+1);
              tree.scrollPathToVisible(new TreePath(newNode.getPath()));
              tree.setSelectionPath(new TreePath(newNode.getPath()));
        //listener to selection change event
        public void valueChanged(TreeSelectionEvent e){
             DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                  tree.getLastSelectedPathComponent();
             if (node == null)
                  return;
             tree.startEditingAtPath(new TreePath(node.getPath()));
    class MyCellRenderer extends DefaultTreeCellRenderer{
         public Component getTreeCellRendererComponent(JTree tree, Object value,
                   boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
                // Get background color based on selected state
              JLabel renderer =(JLabel) super.getTreeCellRendererComponent(tree,
                        value,selected,expanded,leaf,row,hasFocus);
              Color background = (selected ? Color.yellow : Color.white);
              renderer.setOpaque(true);
              renderer.setBackground(background);
             renderer.setMinimumSize(new Dimension(950,(int)renderer.getMinimumSize().getHeight()));
             renderer.setPreferredSize(new Dimension(950,(int)renderer.getPreferredSize().getHeight()));
              renderer.setText(value.toString());
             return renderer;
    class MyCellEditor extends DefaultTreeCellEditor{
         public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer){
              super(tree,renderer);
         public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor){
              super(tree,renderer,editor);
         public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected,
                   boolean expanded, boolean leaf, int row){
              Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              Component editor = realEditor.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              SwingUtilities.updateComponentTreeUI(c);
              if (editor instanceof JTextField)
                   //widen the textfield for the editor
                   ((JTextField)editor).setColumns(85);
                   ((JTextField)editor).setText(value.toString());
                   //((JTextField)test).selectAll();
              return c;
       

    Use path from the event.
    public void valueChanged(TreeSelectionEvent e){
             tree.startEditingAtPath(e.getPath());
    }Regards,
    Stas

  • Update JTree when model changes

    Hello!
    I'am doing a webbrowser that stores the history in a JTree that is visible in EAST in the browserFrame.
    The history is updated when a link is clicked or it is typed in the addressbar. Everything works for the moment but it's quite ugly i guess...
    For now i do tree.updateUI(); in the view everytime I have added a node, but I want to remove tree.updateUI() and update the view automaticly whenever the model has changed.
    Is nodesWereInserted() the right function to use?
    I have tried to use this listener in the HistoryModel(after removing tree.updateUI()) but the JTree acts very strange then...
    thanks for any help :)
    Fredrik
    ////////////THE LISTENER THAT I HAVE TRIED TO USE IN THE HistoryModel
        class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                 * If the event lists children, then the changed
                 * node is the child of the node we've already
                 * gotten.  Otherwise, the changed node and the
                 * specified node are the same.
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
                System.out.println("The user has finished editing the node.");
                System.out.println("New value: " + node.getUserObject());
            public void treeNodesInserted(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());           
                int index = treeModel.getIndexOfChild(node.getParent(), node);
                treeModel.nodesWereInserted(node.getParent(), new int[] {index});
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
            }////////////////THIS IS THE VIEW CLASS
    package freebrowser.gui;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Iterator;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeSelectionModel;
    import freebrowser.model.HistoryModel;
    import freebrowser.model.LinkInfo;
    import freebrowser.types.Browser;
    * This class represents a JTree with a domainname as children and url:s in its leafs.
    * @author dalen
    public class HistoryTree implements TreeSelectionListener {
        private JTree tree;
        private Browser browser;
        private ArrayList currentPageLinkInfo;
        private URL browserCurrentUrl;
        private HistoryModel historyModel;
        public HistoryTree(Browser browser, HistoryModel historyModel){
            this.browser = browser;
            this.historyModel = historyModel;
            //Create a tree that allows one selection at a time.
            tree = historyModel.createJtree();
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
         * This function is called when a link has been clicked.
         * @param url - The <code>url</code> that has been clicked
        public void newPageClicked(URL url){
            Iterator it = currentPageLinkInfo.iterator();
            while(it.hasNext()){
                LinkInfo info = (LinkInfo)it.next();
                if(info.getUrl().equals(url)){
                    historyModel.addNode(info, browserCurrentUrl);
                    tree.updateUI(); /// this is what I want to remove!
                    break;
         * Adds a node to the tree if a url has been entered in the addresfield
         * @param url
         * @param title
        public void addressBarPageEntered(URL url, String title) {
            LinkInfo info = new LinkInfo(url, title);
            browserCurrentUrl = url;
            historyModel.addNode(info, browserCurrentUrl);
            tree.updateUI();/// this is what I want to remove!
         * Helps the <code>HistoryBar</code> to be updated with the current url.
         * @param url - The curren <code>url</code> in the browser
        public void setHistoryCurrentPage(URL url){
            LinkInfo info = new LinkInfo(url, null);
            currentPageLinkInfo = info.getLinkInfos();
            browserCurrentUrl = url;
         * Invoked by TreeSelectionListener when a node has been clicked
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if (node == null) return;
            Object nodeInfo = node.getUserObject();
            if (node.isLeaf()) {
                LinkInfo linkInfo = (LinkInfo)nodeInfo;
                System.out.println(linkInfo.getUrl());
                browser.setURL(linkInfo.getUrl());
         * Function to recieve the JTree
         * @return The <code>tree</code>
        public JTree getTree() {
            return this.tree;
    }/////////////THIS IS THE MODEL CLASS
    package freebrowser.model;
    import java.net.URL;
    import java.util.Enumeration;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    * This class holds the infomation of the historytree. It is stored in an array containing <code>Nodes</code>.
    * @author dalen
    public class HistoryModel {
        private DefaultTreeModel treeModel;
        private DefaultMutableTreeNode rootNode;
        public HistoryModel() {
            rootNode =  new DefaultMutableTreeNode("L�nkHistorik");
            treeModel = new DefaultTreeModel(rootNode);
         * Adds a node in the right place in the model
         * @param info - The <code>info</code> to be added.
        public void addNode(LinkInfo info, URL browserCurrentUrl) {
            //l�gg till noden p� r�tt plats i modellen
            Enumeration e = rootNode.children();
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode urlLeaf = null;
            boolean newNodeSet = false;
            while(e.hasMoreElements()) {
                DefaultMutableTreeNode childToCheck = (DefaultMutableTreeNode)e.nextElement();
                //check if the domainname already is in the tree
                if(childToCheck.toString().equals( browserCurrentUrl.getHost()) ){
                    urlLeaf = new DefaultMutableTreeNode(info);
                    treeModel.insertNodeInto(urlLeaf, childToCheck, childToCheck.getChildCount());
                    newNodeSet = true;
                    break;
            if(!newNodeSet) {
                category = new DefaultMutableTreeNode(new LinkInfo(null,browserCurrentUrl.getHost()));
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode)treeModel.getRoot();
                treeModel.insertNodeInto(category, parent, parent.getChildCount());
                urlLeaf = new DefaultMutableTreeNode(info);
                treeModel.insertNodeInto(urlLeaf, category, category.getChildCount());
            ((DefaultMutableTreeNode)treeModel.getRoot()).setUserObject("L�nkhistorik (dom�ner: " + rootNode.getChildCount() + "  l�nkar: " + rootNode.getLeafCount() +")");
         * Creates and returns a JTree built on the model from createJTreeModel()
         * @return The new JTree
        public JTree createJtree() {
            return new JTree(treeModel);
    }

    Nevermind, I solved it by my self :)
    added treeModel.nodeChanged(node); after insertNodeInto()

  • Help needed redrawing a JTree

    Hi,
    I'm writing a simple Swing program to examine the entries in a JAR file as a JTree. It is not meant to be professional grade, it's simply for my own fun.
    I have the program so that it displays a Window with a Menus. When the user chooses a JAR file, the program opens the JAR file, reads the entries in the file, and builds a DefaultTreeModel for the entries in the JAR file. Then, it builds a JTree from the DefaultTreeModel.
    The program works great, except, once the tree is created, I don't know how to force Swing to redraw the JFrame.
    Can someone please tell me what I'm doing wrong?
    The code is as follows:
    <pre>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.io.*;
    import java.util.jar.*;
    import java.util.*;
    * <p>This class is used to display the contents of a JAR file.
    * The entries of the JAR file will be displayed in Swing Tree.
    * @version 1.0
    * @author Kevin Yetman
    public class JarFileTree
    * <p>This method is used to display the GUI.
    public static void main(String[] args)
    {  JFrame frame=new JarTreeFrame();
    frame.show();
    * <p>This class is used to define the javax.swing.JFrame based object that
    * will contain the tree from the JAR file.
    class JarTreeFrame extends JFrame implements ActionListener
    private JTree tree;
    private DefaultTreeModel treeModel;
    private DefaultMutableTreeNode root;
    private JScrollPane scrollPane;
    * <P>This constructor is used create and display the frame.
    public JarTreeFrame()
    {  setTitle("JAR Viewer");
    setSize(800, 600);
    addWindowListener(new WindowAdapter()
    {  public void windowClosing(WindowEvent e)
    {  System.exit(0);
    JMenuBar menuBar=setupMenuBar();
    setJMenuBar(menuBar);
    root = new DefaultMutableTreeNode("No file selected yet.");
    treeModel=new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    scrollPane=new JScrollPane(tree);
    Container contentPane=getContentPane();
    contentPane.add(scrollPane);
    public void processString(String currentEntry, DefaultMutableTreeNode currentNode, DefaultTreeModel treeModel)
    if( currentEntry.length()==0 )
    {  return;
    int slashPos=currentEntry.indexOf('/');
    String currentToken="";
    String remainingPartOfCurrentEntry="";
    if( slashPos!=-1 )
    {  currentToken=currentEntry.substring(0, slashPos);
    remainingPartOfCurrentEntry=currentEntry.substring(slashPos+1, currentEntry.length());
    else
    {  currentToken=currentEntry;
    boolean childFound=false;
    for(Enumeration e=currentNode.children(); e.hasMoreElements(); )
    DefaultMutableTreeNode currentChild=(DefaultMutableTreeNode)e.nextElement();
    if( currentChild.toString().equals(currentToken) )
    processString(remainingPartOfCurrentEntry, currentChild, treeModel);
    childFound=true;
    if( !childFound )
    DefaultMutableTreeNode newChild=new DefaultMutableTreeNode(currentToken);
    treeModel.insertNodeInto(newChild, currentNode, currentNode.getChildCount());
    protected JMenuBar setupMenuBar()
    JMenuBar menuBar=new JMenuBar();
    JMenu helpMenu =new JMenu("Help");
    JMenuItem aboutItem=new JMenuItem("About");
    aboutItem.setActionCommand("HelpAbout");
    aboutItem.addActionListener(this);
    helpMenu.add(aboutItem);
    JMenu fileMenu = new JMenu("File");
    JMenuItem openItem=new JMenuItem("Open");
    openItem.setActionCommand("FileOpen");
    openItem.addActionListener(this);
    JMenuItem exitItem=new JMenuItem("Exit");
    exitItem.addActionListener( new ActionListener()
    {  public void actionPerformed(ActionEvent evt)
    { System.exit(0);
    fileMenu.add(openItem);
    fileMenu.add(exitItem);
    menuBar.add(fileMenu);
    menuBar.add(helpMenu);
    return menuBar;
    public void setupTree(String fileName)
    try
    JarFile jarFile=new JarFile(new File(fileName));
    for(Enumeration e=jarFile.entries(); e.hasMoreElements(); )
    String currentEntry=(e.nextElement().toString()).trim();
    processString(currentEntry, root, treeModel);
    DefaultMutableTreeNode lastLeaf=root.getLastLeaf();
    TreePath path=new TreePath(treeModel.getPathToRoot(lastLeaf));
    tree.makeVisible(path);
    catch(IOException e)
    {  JOptionPane.showMessageDialog(this, "ERROR: " + e.toString());
    public void actionPerformed(ActionEvent evt)
    if(evt.getActionCommand().equals("FileOpen"))
    FileOpenSaveAs fosa=new FileOpenSaveAs(this, true);
    if(fosa.approveOptionClicked())
    String fileName=fosa.getSelectedFile();
    fileName+=".jar";
    setupTree(fileName);
    Container contentPane=getContentPane();
    contentPane.removeAll();
    contentPane.add(new JScrollPane(tree));
    contentPane.repaint();
    if(evt.getActionCommand().equals("HelpAbout"))
    {  JOptionPane.showMessageDialog(this, "JAR Viewer Version 1.0\nKevin Yetman");
    // FileOpenSaveAs.java
    // Author: Kevin Yetman
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    // this class handles the display of the
    // File Open or File Save As box.
    public class FileOpenSaveAs {
    // the constructor takes one argument, a
    // boolean which if true opens the File Open
    // box. If false it opens the save as box.
    public FileOpenSaveAs(JFrame baseWindow, boolean fileOpenBox) {
    // initailze the result varialbe
    result=-1;
    // store the value of the fileOpenBox.
    openBox=fileOpenBox;
    // initialize the fileNameSelected string.
    fileNameSelected=new String();
    // first build a JFileChooser.
    JFileChooser fc=new JFileChooser();
    // next tell the file chooser to look in the
    // current directory.
    fc.setCurrentDirectory(new File(CURRENT_DIRECTORY));
    // if the file open box is true, display the file open box.
    // otherwise, display the file save as box.
    if( fileOpenBox ) {
    fc.setDialogTitle(OPEN_TITLE);
    displayBox(baseWindow, fc);
    else {
    fc.setDialogTitle(SAVE_AS_TITLE);
    displayBox(baseWindow, fc);
    // the constructor takes one argument, a
    // boolean which if true opens the File Open
    // box. If false it opens the save as box.
    public FileOpenSaveAs(JDialog baseWindow, boolean fileOpenBox) {
    // initailze the result varialbe
    result=-1;
    // store the value of the fileOpenBox.
    openBox=fileOpenBox;
    // initialize the fileNameSelected string.
    fileNameSelected=new String();
    // first build a JFileChooser.
    JFileChooser fc=new JFileChooser();
    // next tell the file chooser to look in the
    // current directory.
    fc.setCurrentDirectory(new File(CURRENT_DIRECTORY));
    // if the file open box is true, display the file open box.
    // otherwise, display the file save as box.
    if( fileOpenBox ) {
    fc.setDialogTitle(OPEN_TITLE);
    displayBox(baseWindow, fc);
    else {
    fc.setDialogTitle(SAVE_AS_TITLE);
    displayBox(baseWindow, fc);
    // this method displays the File Open box on the base window.
    public void displayBox(JFrame baseWindow, JFileChooser fc) {
    // display the file open box and get the result.
    result=-1;
    if( openBox==true ) {
    result=fc.showOpenDialog(baseWindow);
    else {
    result=fc.showSaveDialog(baseWindow);
    // get the file name.
    if( approveOptionClicked() ) {
    fileNameSelected=fc.getName(fc.getSelectedFile());
    else {
    fileNameSelected="";
    // this method displays the File Open box on the base window.
    public void displayBox(JDialog baseWindow, JFileChooser fc) {
    // display the file open box and get the result.
    result=-1;
    if( openBox==true ) {
    result=fc.showOpenDialog(baseWindow);
    else {
    result=fc.showSaveDialog(baseWindow);
    // get the file name.
    if( approveOptionClicked() ) {
    fileNameSelected=fc.getName(fc.getSelectedFile());
    else {
    fileNameSelected="";
    // check to see if the result is APPROVE_OPTION. If so, we
    // will return true.
    public boolean approveOptionClicked() {
    return (result == JFileChooser.APPROVE_OPTION );
    // get the file name chosen by the user.
    public String getSelectedFile() {
    return fileNameSelected;
    // private attributes for this class.
    private boolean openBox;
    private static final String CURRENT_DIRECTORY=".";
    private static final String SAVE_AS_TITLE="Save As";
    private static final String OPEN_TITLE="Open";
    private int result;
    private String fileNameSelected;
    </pre>
    Thanks!
    Kevin Yetman

    Without looking at all your code, I would suggest that you only redraw the part of the tree that changes (addition or deletion of nodes). To do this, you can call a method of DefaultTreeModel, nodeStructureChanged(TreeNode nodeThatChanged). This fires the appropriate event which in turn causes the node and only its descendents to be redrawn. Good luck.
    -Matt

  • Cut, Copy & Paste Nodes in a JTree

    Hi everyone!
    I would just like to ask you if anyone knows how cut, copy and paste can be implemented on a JTree.
    I have seen some postings with similar questions, but none of them got any answer.
    Thanks in advance

    See the Article
    Cut and Paste
    http://www.javaworld.com/javaworld/javatips/jw-javatip61.html
    drag and Drop in JTree
    http://www.javaworld.com/javaworld/javatips/jw-javatip97.html
    Thank you very much, vinothkumar!
    These tutorials were indeed very helpful!
    And imagine that I had found the cut-paste tutorial, but since it didn't mention anything about JTrees, I ignored it... :P
    Anyway, since I had this problem for some days now, I think you deserve the duke dollars!!!! :)))

  • Making a Directory Structure with JTree.

    Hello,
    Can anyone boss here help me to code to make a
    File System Directory structure through JTree?
    The outlook should be like the Windows Explorer...
    From : [email protected]

    * HarishTree.java
    * Created on September 7, 2004, 2:56 PM
    * @author 120002314
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.io.File;
    import java.awt.event.ActionListener;
    import javax.swing.JToolBar;
    import java.lang.System;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import javax.swing.filechooser.FileSystemView;
    public class HarishTree {
    public static void createAndShowGUI() {
    //creating a tree with drives in the toolbar
    TreeBar bar = new TreeBar();
    JScrollPane scrollpane = new JScrollPane(bar.tree);
    JToolBar toolbar = bar.CreatingTreeBar();
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(toolbar);
    // Display it all in a window and make the window appear
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("FileExplorer");
    frame.getContentPane().add(scrollpane, "Center");
    frame.getContentPane().add(panel,BorderLayout.NORTH);
    frame.setSize(400,600);
    frame.setVisible(true);
    frame.setResizable(false);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    java.lang.System.gc();
    * The methods in this class allow the JTree component to traverse
    * the file system tree and display the files and directories.
    class FileTreeModel implements TreeModel {
    // We specify the root directory when we create the model.
    protected JFile root;
    public FileTreeModel(){}
    public FileTreeModel(JFile root) { this.root = root; }
    // The model knows how to return the root object of the tree
    public Object getRoot() { return root; }
    // Tell JTree whether an object in the tree is a leaf
    public boolean isLeaf(Object node) {  return ((JFile)node).isFile(); }
    // Tell JTree how many children a node has
    public int getChildCount(Object parent) {
    String[] children = ((JFile)parent).list();
    if (children == null) return 0;
    return children.length;
    // Fetch any numbered child of a node for the JTree.
    // Our model returns File objects for all nodes in the tree. The
    // JTree displays these by calling the File.toString() method.
    public Object getChild(Object parent, int index) {
    String[] children = ((JFile)parent).list();
    if ((children == null) || (index >= children.length)) return null;
    return new JFile((JFile)parent,children[index]);
    // Figure out a child's position in its parent node.
    public int getIndexOfChild(Object parent, Object child) {
    String[] children = ((File)parent).list();
    if (children == null) return -1;
    String childname = ((File)child).getName();
    for(int i = 0; i < children.length; i++) {
    if (childname.equals(children)) return i;
    return -1;
    // This method is invoked by the JTree only for editable trees.
    // This TreeModel does not allow editing, so we do not implement
    // this method. The JTree editable property is false by default.
    public void valueForPathChanged(TreePath path, Object newvalue) {}
    // Since this is not an editable tree model, we never fire any events,
    // so we don't actually have to keep track of interested listeners
    public void addTreeModelListener(TreeModelListener l) {}
    public void removeTreeModelListener(TreeModelListener l) {}
    class TreeBar implements ActionListener{
    public JTree tree = new JTree();
    public File[] roots = File.listRoots();
    JToolBar toolbar = new JToolBar();
    public TreeBar(){
    FileTreeModel model = new FileTreeModel(new JFile(System.getProperty("user.home")));
    tree.setModel(model);
    tree.setCellRenderer(new MyRenderer());
    public JToolBar CreatingTreeBar(){
    for(int i=0;i<roots.length;i++){
    JButton button = new JButton(roots[i].getPath(),new MyRenderer().inicon);
    button.addActionListener(this);
    button.setActionCommand(roots[i].getPath());
    toolbar.add(button);
    toolbar.setFloatable(false);
    toolbar.setRollover(true);
    return(toolbar);
    public void actionPerformed(java.awt.event.ActionEvent e) {
    FileTreeModel model = new FileTreeModel(new JFile(e.getActionCommand()));
    tree.setModel(model);
    class MyRenderer extends DefaultTreeCellRenderer {
    ImageIcon inicon = createImageIcon("1.gif");
    ImageIcon exicon = createImageIcon("2.gif");
    ImageIcon leaficon = createImageIcon("3.gif");
    public ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = TreeIconDemo2.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    public Component getTreeCellRendererComponent(
    JTree tree,
    Object value,
    boolean sel,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    if (leaf){
    setIcon(leaficon);
    }else
    if(expanded)
    setIcon(exicon);
    else
    setIcon(inicon);
    return this;
    class JFile extends File{
    public JFile(String path){
    super(path);
    public JFile(File parent,String child){
    super(parent,child);
    public String toString(){
    FileSystem fs = new FileSystem();
    if(fs.isFileSystemRoot(this))
    return(this.getPath());
    else
    return(fs.getSystemDisplayName(this));
    class FileSystem extends FileSystemView{
    public File createNewFolder(File containingDir) throws java.io.IOException {
    return(this.createFileObject(containingDir,"harish"));

  • Asynchronous Queue listener - stale connection.

    Tom,
              I have an asynchronous listener for a remote distributed queue (4 jms servers). The listener process is running which had connected with the queue say 10-12 hours ago. The problem I have is, once message comes to one of the queue, even though listener has not lost the connection (as nothing comes in logs and ExceptionListener is implemented), Listener doesnt pickup the message. why?
              we are using WL 8.1 right now.
              Thanks,
              Malav

    You need to either ensure that the there's a listener on every distributed queue member, or configure the distributed queue to automatically forward messages from idle queues to queues that have consumers ("queue forwarding").
              Tom

  • Problem with new window opening with basic test JTree program

    I'm still getting to grips with Swing, and have now moved on to basic JTrees.
    I'm currently trying to use an add and delete button to add new nodes to the root etc. The addition and deletion is working ok, except that each time the addButton is pressed, a completely new window is created on top of the current window with the new node added to the root etc.
    I know this is probably a simple mistake, but I can't quite see it at the moment.
    My current code is as follows,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class TreeAdditionDeletionTester_1 extends JFrame implements ActionListener
        private JTree tree;
        private DefaultTreeModel treeModel;
        private DefaultMutableTreeNode rootNode;
        private JButton addButton;
        private JButton deleteButton;
        private JPanel panel;
        private int newNodeSuffix = 1;
        private static String Add_Command = "Add Node";
        private static String Delete_Command = "Remove Node";
        //DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
        //TreeAdditionDeletionTester_1 treeChange;
        public TreeAdditionDeletionTester_1() 
            setTitle("Tree with Add and Remove Buttons");
            //DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
            rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            tree.setEditable(false);
            tree.setSelectionRow(0);
            JScrollPane scrollPane = new JScrollPane(tree);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            JPanel panel = new JPanel();
            addButton = new JButton("Add Node");
            addButton.setActionCommand(Add_Command);
            addButton.addActionListener(this);
            panel.add(addButton);
            getContentPane().add(panel, BorderLayout.SOUTH);
            deleteButton = new JButton("Delete Node");
            deleteButton.setActionCommand(Delete_Command);
            deleteButton.addActionListener(this);
            panel.add(deleteButton);
            getContentPane().add(panel, BorderLayout.SOUTH);    
            setSize(300, 400);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        public void actionPerformed(ActionEvent event) 
           TreeAdditionDeletionTester_1 treeChange = new TreeAdditionDeletionTester_1();
            String command = event.getActionCommand();
            if (Add_Command.equals(command)) {
                //Add button clicked
                treeChange.addObject("New Node " + newNodeSuffix++);
            } if (Delete_Command.equals(command)) {
                //Remove button clicked
                treeChange.removeCurrentNode();
        public void removeSelectedNode()
            //get the selected node
            DefaultMutableTreeNode selNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            //method from Class JTree
            if (selNode != null)
                //get the parent of the selected node
                MutableTreeNode parent = (MutableTreeNode)(selNode.getParent());
                //getParent() from Interface TreeNode
                // if the parent is not null
                if (parent != null)
                    //remove the node from the parent
                    treeModel.removeNodeFromParent(selNode);//method from Class DefaultTreeModel
                    return;
        public DefaultMutableTreeNode addObject(Object child) {
            DefaultMutableTreeNode parentNode = null;
            TreePath parentPath = tree.getSelectionPath();
            if (parentPath == null) {
                parentNode = rootNode;
            } else {
                parentNode = (DefaultMutableTreeNode)
                             (parentPath.getLastPathComponent());
            return addObject(parentNode, child, true);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child,
                                                boolean shouldBeVisible) {
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
            if (parent == null) {
                parent = rootNode;
            treeModel.insertNodeInto(childNode, parent,
                                     parent.getChildCount());
            //Make sure the user can see the new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        public void removeCurrentNode() {
            TreePath currentSelection = tree.getSelectionPath();
            if (currentSelection != null) {
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                             (currentSelection.getLastPathComponent());
                MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
                if (parent != null) {
                    treeModel.removeNodeFromParent(currentNode);
                    return;
         * Main method to run as an Application
        public static void main(String[] arg) 
            TreeAdditionDeletionTester_1 addDeleteTree = new TreeAdditionDeletionTester_1();
    }      Thanks.

    I'm currently trying to use an add and delete button
    to add new nodes to the root etc. The addition and
    deletion is working ok, except that each time the
    addButton is pressed, a completely new window is
    created on top of the current window with the new
    node added to the root etc.
    I know this is probably a simple mistake, but I can't
    quite see it at the moment.
    Look at the actionPerformed code for your buttons. The first thing you do there is to create a new TreeAdditionDeletionTester_1, so I don't know why you are surprised you get a new window. There is no need to create a new instance in there, just call addObject/removeCurrentNode on the "this" instance.

  • DnD from JTree to JTable

    Hi guys,
    It seems JTree DnD support is a quit difficult feature to implement of all swing components.
    I'm writing an application in which I have a JTree structure representing the file system of user machine and another JTable component at the right.
    I want to be able to drag files nodes from left JTree to right JTable.
    I would appreciate a lot if someone share with me some source code examples for this functionality.
    can someone post some basic java code to get me started or point me to some web resource discussing this feature?
    thanks much.

    http://forum.java.sun.com/thread.jspa?threadID=296255Thank you. I already looked at this thread but it's not what i'm looking for: it shows dnd from a JTree to another JTree..however i need to implement dnd from JTree to JTable.
    Is there some basic example on how to do that ?
    thanks.

  • Help with Jtree for a file navigator

    Hi there,
    I'm trying to do something with a JTree, but I can't find anywhere how to perform that.
    I'm making a little file explorer, with a JTree to navigate through the file structure. I have also two buttons (up and back). When I select a directory with the mouse, the corresponding node is highlighted, but when I push the button up, or the button back, it isn't (I mean, the directory is caught well, but no nodes are highlighted). It uses the DefaultTreeCellRenderer
    Any ideas to highlight the directory when I push the up or back button?.
    Thank you very much!!!!

    Strange. Does this small, simplified example work for you?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Xxx extends JFrame implements ActionListener {
      private JTree tree = new JTree();
      private JButton butt = new JButton("!");
      public static void main(String[] args) {
        new Xxx();
      public Xxx() {
        getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
        getContentPane().add(butt, BorderLayout.SOUTH);
        butt.addActionListener(this);
        pack();
        setVisible(true);
      public void actionPerformed(ActionEvent e) {
        int[] rows = tree.getSelectionRows();
        if ((rows != null) && (rows.length == 1)) {
          int next = rows[0] + 1;
          if (next >= tree.getRowCount()) {
            next = 0;
          tree.setSelectionRow(next);
    }

  • Horizontal JTree

    I think I'm beating a dead horse with this one.... all previous posts to the forums have been more or less fruitless (aside from do-it-yerself)
    BUT! Does anyone know of a publicly available implementation of a Horizontal JTree or something like it?
    I'd really like something that looks similarly:
                                    [Node1]  [Node2]  [Node3]
                                                         |
                             |       |       |      |      |      |
                          [Node3a]   |    [Node3c]  |   [Node3e]  |
                             |    [Node3b]       [Node3d]      [Node3f]
                             |
                                 |       |      |      |      |
                              ....etc....Thanks,
    --Spencer

    Looking through the JTree API, I found in javax.swing.tree the RowMapper interface, which is implemented by various *LayoutCache classes.
    How do you use these, and extending one of these classes a possible/easier solution to implementing a horizontal JTree apart from reimplementing JTree and all its inards?
    Thanks,
    --Spencer

Maybe you are looking for