Updating a Jtree

Hello frens ,
I'm designing my project of file uploading in swings and am i'm using JCombobox n JTree.
JCombobox contains system drives(A:,C:,D:) as the combo elemnts.
By default the selected item in the JCombobox is C:
The JTree contains elemnts ofthe drive(C:/D:)By default it contains elemnts C:.
Now wht i want is when the elemnts in the Jcombobox are changed the Jtree contents shud also changed.
Suppoose the user changes the selction in JComboBox to D:.
Then the JTree elemnts elemnst shud consist of elemnts in D:.
So how do i do this.I have different classes for JComboBox and JTree.
How do i fire evnts to update the Tree.
Thanking you
jyo

Just modify the tree model with the data u have.

Similar Messages

  • Updating a JTree without application restart

    I would like to update the JTree in my application without restarting the application. The JTree elements come from a file, therefore, I update the file and want the JTree to be refreshed! I understand that this is done with swing and model and already do so eg: I update combo boxes and these automatically reflect the changes. I use the code below to update the boxes:-
    public void updateBoxes()
    DefaultComboBoxModel newComboModel = new DefaultComboBoxModel(getItems());
    myBox.setModel(newComboModel);
    I would basically like to do exactly the same using another model for a JTree.  Is this possible?  Also, as the JTree has actually been added to a scroll panel, so does this affect things?  Hopefully I can use a simple method like the one provided above for updaing a combo box.
    Thanks for any assistance

    * TestTree.java
    package com.test;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class TestTree extends javax.swing.JFrame {
        private javax.swing.JScrollPane mainScrollPane;
        private javax.swing.JButton btnChooseThree;
        private javax.swing.JTree mainTree;
        private javax.swing.JButton btnChooseOne;
        private javax.swing.JPanel buttonPanel;
        private javax.swing.JButton btnChooseTwo;
        public TestTree() {
            java.awt.GridBagConstraints gridBagConstraints;
            mainScrollPane = new javax.swing.JScrollPane();
            mainTree = new javax.swing.JTree();
            buttonPanel = new javax.swing.JPanel();
            btnChooseOne = new javax.swing.JButton();
            btnChooseTwo = new javax.swing.JButton();
            btnChooseThree = new javax.swing.JButton();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            mainScrollPane.setViewportView(mainTree);
            getContentPane().add(mainScrollPane, java.awt.BorderLayout.CENTER);
            buttonPanel.setLayout(new java.awt.GridBagLayout());
            btnChooseOne.setText("One");
            btnChooseOne.setMaximumSize(new java.awt.Dimension(70, 27));
            btnChooseOne.setMinimumSize(new java.awt.Dimension(70, 27));
            btnChooseOne.setPreferredSize(new java.awt.Dimension(70, 27));
            btnChooseOne.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnChooseOneActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
            buttonPanel.add(btnChooseOne, gridBagConstraints);
            btnChooseTwo.setText("Two");
            btnChooseTwo.setMaximumSize(new java.awt.Dimension(70, 27));
            btnChooseTwo.setMinimumSize(new java.awt.Dimension(70, 27));
            btnChooseTwo.setPreferredSize(new java.awt.Dimension(70, 27));
            btnChooseTwo.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnChooseTwoActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
            buttonPanel.add(btnChooseTwo, gridBagConstraints);
            btnChooseThree.setText("Three");
            btnChooseThree.setMaximumSize(new java.awt.Dimension(70, 27));
            btnChooseThree.setMinimumSize(new java.awt.Dimension(70, 27));
            btnChooseThree.setPreferredSize(new java.awt.Dimension(70, 27));
            btnChooseThree.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnChooseThreeActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
            buttonPanel.add(btnChooseThree, gridBagConstraints);
            getContentPane().add(buttonPanel, java.awt.BorderLayout.NORTH);
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Three");
            rootNode.add(new DefaultMutableTreeNode("One"));
            rootNode.add(new DefaultMutableTreeNode("Two"));
            rootNode.add(new DefaultMutableTreeNode("Three"));
            mainTree.setModel(new javax.swing.tree.DefaultTreeModel(rootNode));
            pack();
        private void btnChooseThreeActionPerformed(java.awt.event.ActionEvent evt) {
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Three");
            rootNode.add(new DefaultMutableTreeNode("One"));
            rootNode.add(new DefaultMutableTreeNode("Two"));
            rootNode.add(new DefaultMutableTreeNode("Three"));
            mainTree.setModel(new javax.swing.tree.DefaultTreeModel(rootNode));
        private void btnChooseTwoActionPerformed(java.awt.event.ActionEvent evt) {
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Two");
            DefaultMutableTreeNode subNode;
            subNode = new DefaultMutableTreeNode("One");
            subNode.add(new DefaultMutableTreeNode("Sub One"));
            subNode.add(new DefaultMutableTreeNode("Sub Two"));
            subNode.add(new DefaultMutableTreeNode("Sub Three"));
            rootNode.add(subNode);
            subNode = new DefaultMutableTreeNode("Two");
            subNode.add(new DefaultMutableTreeNode("Sub One"));
            subNode.add(new DefaultMutableTreeNode("Sub Two"));
            subNode.add(new DefaultMutableTreeNode("Sub Three"));
            rootNode.add(subNode);
            subNode = new DefaultMutableTreeNode("Three");
            subNode.add(new DefaultMutableTreeNode("Sub One"));
            subNode.add(new DefaultMutableTreeNode("Sub Two"));
            subNode.add(new DefaultMutableTreeNode("Sub Three"));
            rootNode.add(subNode);
            mainTree.setModel(new javax.swing.tree.DefaultTreeModel(rootNode));
        private void btnChooseOneActionPerformed(java.awt.event.ActionEvent evt) {
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("One");
            DefaultMutableTreeNode subNode;
            DefaultMutableTreeNode subSubNode;
            subNode = new DefaultMutableTreeNode("One");
            subSubNode = new DefaultMutableTreeNode("Sub One");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub A"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub B"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub C"));
            subNode.add(subSubNode);
            subSubNode = new DefaultMutableTreeNode("Sub Two");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 1"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 2"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 3"));
            subNode.add(subSubNode);
            subSubNode = new DefaultMutableTreeNode("Sub Three");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub X"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub Y"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub Z"));
            subNode.add(subSubNode);
            rootNode.add(subNode);
            subNode = new DefaultMutableTreeNode("Two");
            subSubNode = new DefaultMutableTreeNode("Sub One");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub A"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub B"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub C"));
            subNode.add(subSubNode);
            subSubNode = new DefaultMutableTreeNode("Sub Two");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 1"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 2"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 3"));
            subNode.add(subSubNode);
            subSubNode = new DefaultMutableTreeNode("Sub Three");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub X"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub Y"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub Z"));
            subNode.add(subSubNode);
            rootNode.add(subNode);
            subNode = new DefaultMutableTreeNode("Three");
            subSubNode = new DefaultMutableTreeNode("Sub One");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub A"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub B"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub C"));
            subNode.add(subSubNode);
            subSubNode = new DefaultMutableTreeNode("Sub Two");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 1"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 2"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub 3"));
            subNode.add(subSubNode);
            subSubNode = new DefaultMutableTreeNode("Sub Three");
            subSubNode.add(new DefaultMutableTreeNode("Very Sub X"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub Y"));
            subSubNode.add(new DefaultMutableTreeNode("Very Sub Z"));
            subNode.add(subSubNode);
            rootNode.add(subNode);
            mainTree.setModel(new javax.swing.tree.DefaultTreeModel(rootNode));
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            new TestTree().show();
    }

  • Update a JTree from a file

    Hello everyone i have a wee bit of a problem here i have a JTree that gets updated by a text file. That bit works grand when the JTree is loaded it reads the text file and displays the contents now the bother i am having is the user has the option to add a new item to the text file but i cannot not seem to get it to update the JTree. I got to a point where it displayed the old and the new data in the tree is there a way to delete the old stuff

    I think you need to rebuild the entire tree each time there is a change. This way, you are certain that all the items that are removed from the textfile are also removed from the tree.
    Unless off course the text file is edited through the same application that displayes the tree, then you can come up with something smarter then that...
    Mark

  • Need help with updateing a JTree

    I have a JList, and JTree which mimic each other. User makes selection in list presses OK and in the JTree I need the node that matches their selection to update and have child nodes under it. Can't seem to get it working right.
    right now I have this:
    Logic Trail
      item one
      item two
      item three
      item four
    after update I need this
    Logic Trail
      item one
         testing
      item two
      item three
      item four
    // in the GUI
    // pass the selected int to the method in class TreePanel
    treePanel.updateTree( questionList.getSelectedIndex());
    // here is the TreePanel class
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class TreePanel extends javax.swing.JPanel {
      private String[] questions;
      DefaultTreeModel treeModel;
      DefaultMutableTreeNode root;
        public TreePanel(String[] questions) {
        this.questions = questions;
        root = new DefaultMutableTreeNode("Logic Trail");
        treeModel = new DefaultTreeModel(root);
        initComponents ();
      private void initComponents () {
      jScrollPane1 = new javax.swing.JScrollPane ();
      logicTree = new JTree(treeModel);
      setLayout (new java.awt.BorderLayout ());
        jScrollPane1.setViewportView (logicTree);
      add (jScrollPane1, java.awt.BorderLayout.CENTER);
    // method to update JTree, when user selects accept tree will update with new logic path
    public void updateTree(int selectedNode){
      DefaultMutableTreeNode newNode = new DefaultMutableTreeNode( treeModel.getChild(root, selectedNode));
      logicTree.setSelectionRow(selectedNode);
      DefaultMutableTreeNode logicNode = new DefaultMutableTreeNode( logicTree.getSelectionPath() );
      DefaultMutableTreeNode testNode = new DefaultMutableTreeNode(" testing" );
      treeModel.insertNodeInto(testNode, logicNode, 0);
      treeModel.reload();
    public void createTree(){
      for( int i = 0; i < questions.length; i++ ){
      DefaultMutableTreeNode questionNode = new DefaultMutableTreeNode( questions[i] );
      treeModel.insertNodeInto(questionNode, root, i );
    treeModel.reload();
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree logicTree;
    // End of variables declaration
    }

    Thanks for nothing

  • Grouped table doesn't update underlying JTree

    I'm having a problem getting a groupable JTable to work. The JTable has an underlying JTree which is used to group on a specific column. The table can expand and retract it's nodes perfectly however when I call JTree.expandPath it doesn't update the table view immediately, instead it updates after a call to showVisible on a dialog.
    My question is; when does the view of a table get updated after having called expandPath on a tree. From my perspective at least it seems it doesn't expand it immediately on the call to expandPath. Do I need to a function like refresh to model?
    Thanks for the help!
    EDIT: My assumption is it has something to do with the same reason why doing :
    setVisible(false)
    setVisible(true)
    and stepping through those statements doesn't produce changes in the UI. Is there some kind of commit method in Swing?
    Edited by: alex.p on 29-Nov-2010 03:58

    I've used this basic code structure before:
    DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
    root.add(new DefaultMutableTreeNode("another_child"));
    model.reload(root);If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Dynamic update of JTree?

    Hi
    I have one JTree and one form. When I load data from database the JTree is not changed. When I click on the root the data apper, but when I make second query the Tree is not changed.
    How can I solve this two problems.
    Can someone help me.
    Thanks.

    Whichever TreeModel class you use to expose the data as a tree needs to fire events to let the tree know that the data changed. DefaultTreeModel does this for you, but if you implement your own TreeModel you'll need to fire events to the TreeModelListeners yourself.

  • Dynamic JTree; updating the Jtree during app execution

    I have a JTree that renders a DOM Tree. All is well. I can set different icons in the tree depending on the type of node. The functionality I need is to dynamically change the icon in the JTree for a given node. I have a wrapper object that extends DefaultMutableTreeNode and contains an Icon member varrialbe. The problem is that this varriable is initialized by a custom TreeCellRenderer depending on the contents of the node.
    I have also tried having a node_status flag inside my wrapper node, to give the Cell Renderer something to check to determine what to make the icon. The problem, I think, is that the JTree gets rerendered everytime an AWT event is fired; rerendering the JTree causes my wrapper nodes to be reinstanticated thus clearing all information in the Node, including the node_status flag.
    Has anyone done anything similar, or does anyone have any insight into what is going on?
    thanks.
    -karl

    I have figured out my problem and am posting it in the hopes that it helps others.
    I created a custom TreeModel to deal with taking an XML (DOM) Tree and rendering it in a JTree. The problem comes from the custom class that I created to wrap the DOM nodes. The geometry for the DOM tree is contained in the DOM Node (getChild(x), an XML Tree is really just a single node with children, etc) and the problem stems from the wrapper object not knowing about the geometry of the tree except by traversing the tree through the DOM Nodes; since the DOM Node is a member of the wrapper node, traversal through the DOM tree breaks any data stored in the wrapper node which is reinitialized whenever you try to get a node's child.
    Solution:
    Do not render the tree recursivly with the DOM Nodes: render the tree itteratively with wrapper nodes. Because of the frequency the JTree gets redrawn, and thus the TreeModel gets hit with events, maintaining a semi-static tree will keep the information in the nodes.
    -Karl

  • Using threads (SwingWorker) to update JTree component

    Hi,
    Im having a problem trying to update a JTree component (adding child nodes to an existing node) using threads. Im using the SwingWorker3 class (http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html) for threading.
    When the user selects a node for expansion, the logic for fetching the children of the selected node is executed under the construct() method of SwingWorker.
    Once this data is obtained, the job of adding the children to the selected node is done in the finished() method which runs on the event-dispatch thread as per documentation of SwingWorker3.
    The problem Im facing is that even though the data for the children is obtained and the finished() method executes and adds the children to the selected node, they are not visible in the UI.
    If anybody knows how this can be resolved, please let me know. Any help/pointers would be greatly appreciated.
    Rgds
    Sridhar

    I added the tree.updateUI() method call in the finished() method. This renders the children (Yipee!).
    But now I have a new problem. If I collapse and again expand a node, I get a NPE. (I see all the child nodes but a exception is still thrown) The exception happens after my treeWillExpand() and treeExpanded() method implementations. So no probs in my code.
    If you know of a solution, pleeease let me know.
    TIA
    Sridhar
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTreeUI.updateSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.handleExpandControlClick(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.checkForClickInExpandControl(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(Unknown Source)
    at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  • Updating Jtree

    hi
    i am having problem as i am not able to update the jtree , i dont understand why i cant??
    and at start it is empty and it will remain empty
    public class Gui extends JFrame
    {  Vector root = new Vector();
    public JTree theTree ;
    public SERGui( )
    DefaultMutableTreeNode roott = new DefaultMutableTreeNode (root) ;
    DefaultTreeModel model = new DefaultTreeModel (roott) ;
    theTree = new JTree (model) ;      
    theTree.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Category"));
        JScrollPane left = new JScrollPane(theTree);
        JScrollPane right = new JScrollPane(contentPanel);
        JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,left,right);
    //  model.nodeStructureChanged();
        JScrollPane bottom = new JScrollPane(contentPanel1);
        JSplitPane pane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,pane,bottom);
         //pane.setDividerLocation(0.50); // or sp.setDividerLocation(150);  
        c.add(pane1, BorderLayout.CENTER ); // add empty content panel
         contentPanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"browser"));
        show( ); // display window
    public Vector addOne(String newString)
    {  // System.out.println(newString);
       if (!root.contains(getQuery))
               root.add(newString);
    //      print_vector(root);
    //print_vector(root);
    return root;
    }and my other class
    where i call this methos is as follow
    Class Search()
    public void countWord(String newString)
    {Gui.addOne(newString);
    }}

    hi guys
    i used print to figure out the problem??
    and i realise that my vector does not get updated when i try to print element it return null!!{inside constructor}
    how can i refresh the vector or the tree??
    because the vector will have element after it has been filled by addone() method?
    can i repaint the tree again after the addone() method??
    thanks in advance

  • JTree Display Update

    I use a JTree that requires periodic changes to its nodes. I cannot get the display of the JTree to update however. I have tried many different things such as JTree.updateUI(), DefaultTreeModel.reload(), DefaultTreeModel.nodesChanged().
    Currently my code looks like this:
    // initialization
    createTreeNodes();
    treeModel = new DefaultTreeModel(rootNode); treeModel.addTreeModelListener(this);
    tree = new JTree(treeModel);
    // code invoked whenever changes to JTree must be made
    createTreeNodes();
    treeModel.reload();
    tree.repaint();
    // this is the function "createTreeNodes"
    private void createTreeNodes()
    rootNode = new DefaultMutableTreeNode("File Name");
    DefaultMutableTreeNode headerNode = new DefaultMutableTreeNode("Header 1");
    for(int i=0; i<cardArray.size(); i++)
    DefaultMutableTreeNode cardNode = new DefaultMutableTreeNode(cardArray.get(i).getFront() + " (" + (i+1) + ")");
    // above line simply creates a node with a string
    System.out.println(cardArray.get(i).getFront() + " (" + (i+1) + ")");
    // the above line recreates the code 2 lines above for debugging purposes
    headerNode.add(cardNode);
    // above code adds child to parent
    rootNode.add(headerNode);
    // above code adds parent to root node
    }The tree is updated in createTreeNodes().
    If a file is opened by a user, cardArray changes and I reflect these changes by updating the JTree. The System.out.println() statement in the createTreeNodes() function prints the expected data to the console, which proves that the data is being updated. The display of the JTree does not update however.
    And for further explanation about my code:
    - the part that I commented "Initialization" is located in the program constructor. At this point cardArray is equal to 0, and the program simply displays one leaf node with a value of 'null'
    - If the user opens a new file, cardArray (an ArrayList) is updated. I call the createTreeNodes() function which updates the JTree data. I also call treeModel.reload() to signal to the DefaultTreeModel that its data has been updated
    - the function 'createTreeNodes()' simply adds DefaultMutableTreeNodes to the JTree hierarchy
    My thanks in advance for any help you may be able to provide.

    Hi,
    I have taken a look at your code, and I can't see that you are updating the tree. Your createTreeNodes method does only create a new root node, and stores the reference in the attribute rootNode. That does neither affect the root or the model created in the initialization block.
    /Kaj

  • JTree Update Leaf Icon

    Hi,
    I have two problem with Jtree.
    1.How can I put different Icons for different leafs of the same node?
    2.How is it possible to refresh or update the Jtree(by adding or removing some leaf) that the leaf Icons remain?
    Thanks for your help.

    1.How can I put different Icons for different leafs of the same node?Yes, ... either write a custom cell renderer or find a "merged icon".. there are examples of both around the forums.
    2.How is it possible to refresh or update the Jtree(by adding or removing
    some leaf) that the leaf Icons remain?No. if you remove a node, the node is gone. If you don't remove the node, the node stays. IF you want to leave the leaf icon, you can have a renderer which just displays the icon and not the text.

  • Problem updating JTree via RMI

    I'm programming an Instant Messenger application in Java using RMI extensively. Much like most IM applications, my IM clients display a "buddy list" window upon successful authentication with the server. I have reached a huge stumbling block at this point. My Buddylist JFrame contains a JTree that is used to display the status of the user's buddies (i.e. online, offline). I am able to populate the JTree without any problems BEFORE the JFrame is displayed by using the DefaultTreeModel's insertNodeInto() method. But the problem I'm having is that, once the Buddylist is displayed to the user, I can't successfully update the JTree to reflect changing user status. For example, let's say a user with the screename "qwerty" logs in to the server. Now "qwerty" sees his Buddylist pop up on screen. His Buddylist contains 1 user (for simplicity's sake) with screename "foo". "foo" is currently not logged into the system so "foo" is shown in the Buddylist as a child of node Offline. But right now, let's say that "foo" logs into the system. "qwerty's" Buddylist should be updated to reflect the fact that "foo" just signed in by removing "foo" as a child node of Offline and adding a new node to Online called "foo".
    I currently have this functionality implemented as an RMI callback method on the server side. When "foo" logs in, the server calls the method fireBuddyLoggedOnEvent() with "foo" as the argument. Because "qwerty" is already logged in, and both users are each other's buddy, the statement
         c.getCallback().buddySignedOn(screenname);
    will be executed on the client side. Unfortunately, even though this code is successfully executed remotely, "qwerty's" Buddylist's JTree does not update to show that "foo" is now online. My only suspicion is that this is due to the fact that the Buddylist is already visible and this somehow affects its ability to be updated (remember that I have no problem populating the tree BEFORE it's visible). However, I've weeded out this possibility by creating a test frame in which its JTree is successfully updated, but in response to an ActionEvent in response to a button click. Of course, this test case was not an RMI application and does not come with the complexities of RMI. Please help me resolve this issue as it's preventing me from proceeding with my project.
    ~BTW, sorry for the poor code formatting. I added all the code in wordpad and pasted it in here, which stripped the formatting.
    * Frame that allows the user to enter information to
    * be used to login to the server.
    public class LoginFrame extends JFrame {
         signonButton.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   if (!screenameTextField.getText().equals("") &&
                   !passwordTextField.getPassword().equals("")) {
                        try {
                             serverInter = (ServerInter) Naming.lookup(serverName);
                             String username = screenameTextField.getText();
                             String password = String.valueOf(passwordTextField.getPassword());
                             int connectionID = serverInter.connect(username, password);
                             System.out.println("authenticate successful");
                             dispose();
                             Buddylist buddyList = new Buddylist(username, connectionID);
                             // Registers the buddylist with the server so that
                             // the server can remotely call methods on the
                             // Buddylist.
                             serverInter.registerCallback(buddyList, connectionID);
                             return;
                             } catch (Exception e1) {
                                  JOptionPane.showMessageDialog(LoginFrame.this, e1.getMessage(),
                                            "Connection Error", JOptionPane.ERROR_MESSAGE);
                                  passwordTextField.setText("");
                                  signonButton.setEnabled(false);
                                  e1.printStackTrace();
         public static void main(String[] args) {
              new LoginFrame();
    public class Buddylist extends JFrame implements BuddylistInter {
         public Buddylist(String username, int connectionID) {
              try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   initialize();
                   } catch (Exception e) {
                        e.printStackTrace();
         * Method of interest. Note that this method uses a DynamicTree
         * object as included in the Sun tutorial on JTree's
         * (located at http://www.iam.ubc.ca/guides/javatut99/uiswing/components/tree.html#dynamic).
         * Don't worry too much about where the node is getting added
         * but rather, that i wish to verify that an arbitrary node
         * can successfully be inserted into the tree during this
         * remote method call
         public void buddySignedOn(String screenname) throws RemoteException {
              // should add screename at some location in the tree
              // but doesn't!
              treePanel.addObject(screename);
    * Oversimplified interface for the Buddylist that is intended
    * to be used to allow callbacks to the clientside.
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
    * Another oversimplified interface that is to be
    * implemented by the server so that the client can
    * call remote server methods.
    public interface ServerInter extends java.rmi.Remote {
         // "Registers" the given Buddylist with this server to allow
         // remote callbacks on the Buddylist.
         public void registerCallback(Buddylist buddylist, int connectionID)
                             throws RemoteException;
    public class Server extends UnicastRemoteObject implements ServerInter {
         private Vector loggedInUsers = new Vector();
         // Note that this method assumes that a Connection object
         // representing the Buddylist with connectionID was added
         // to the loggedInUsers list during authentication.
         public void registerCallback(Buddylist buddylist, int connectionID) throws RemoteException {          
              int index = loggedInUsers.indexOf(new Connection(connectionID));
              Connection c = (Connection) loggedInUsers.get(index);
              c.setCallback(buddylist);
         // Method that's called whenever a client successfully
         // connects to this server object.
         // screename is the name of the user that successfully
         // logged in.
         private void fireBuddyLoggedOnEvent(String screenname) {
              // Examines each logged in client to determine whether
              // or not that client should be notified of screename's
              // newly logged in status.
              for (int i = 0; i < loggedInUsers.size(); i++) {
                   Connection c = (Connection) loggedInUsers.get(i);
                   if (database1.areBuddies(screenname, c.getUsername())) {
                        try {
                             // getCallback() returns a reference to
                             // the Buddylist that was registered
                             // with this server. At this point,
                             // the server attempts to notify the
                             // client that one of his "buddies" has
                             // just logged into the server.
                             c.getCallback().buddySignedOn(screenname);
                        } catch (RemoteException e) {
                             e.printStackTrace();
    }

    Ok, I deleted all .class files, recomplied, and rmic'd, and I still get the IllegalArgumentException. So I've decided to just post all the code here because I don't want to make an assumption that all the code is correct. Thanks for helping me out with this very stressful problem.
    * Created on Nov 13, 2006
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.rmi.Naming;
    import java.rmi.NotBoundException;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Buddylist extends JFrame implements BuddylistInter {
         private String serverName = "//Broom:" + "5001" + "/IMServer";
         private DynamicTree treePanel = null;
         private String onlineString = "Online";
         private String offlineString = "Offline";
         private DefaultMutableTreeNode onlineNode = null;
         private DefaultMutableTreeNode offlineNode = null;
         private ImageUpdater imageUpdater = null;
         private javax.swing.JPanel jContentPane = null;
         private ServerInter serverInter = null;
         private String username = null;
         // A connectionID of -1 indicates that this Buddylist
         // has not yet received a valid id from the server.
         private int connectionID = -1;
         private JMenuBar jJMenuBar = null;
         private JMenu jMenu = null;
         private JMenu jMenu1 = null;
         private JMenu jMenu2 = null;
         private JPanel imagePanel = null;
         private JSeparator jSeparator1 = null;
         public Buddylist(String username, int connectionID) {
             try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   imageUpdater = new ImageChooser(this);
                   initialize();
                    * This statement is causing an IllegalArgumentException
                    * to be thrown! I've tried inserting it at the beginning
                    * of the constructor and that doesn't help.
                   UnicastRemoteObject.exportObject(this);
              } catch (MalformedURLException e) {
                   e.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
              } catch (NotBoundException e) {
                   e.printStackTrace();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setJMenuBar(getJJMenuBar());
              this.setPreferredSize(new java.awt.Dimension(196,466));
              this.setMinimumSize(new java.awt.Dimension(150,439));
              this.setSize(196, 466);
              this.setContentPane(getJContentPane());
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(getJSeparator1(), null);
                   jContentPane.add(getTreePanel(), null);
              return jContentPane;
         private DynamicTree getTreePanel() {
              if (treePanel == null) {
                   treePanel = new DynamicTree();
                   onlineNode = treePanel.addObject(null, onlineString);
                   offlineNode = treePanel.addObject(null, offlineString);
                   treePanel.setBounds(6, 138, 177, 196);
                   populateTree();
                   return treePanel;
              return null;
         private void populateTree() {
              try {
                   String [] buddies = serverInter.getBuddyList(this.username);
                   for (int i = 0; i < buddies.length; i++) {
                        try {
                             if (serverInter.isBuddyOnline(buddies)) {
                                  treePanel.addObject(onlineNode, buddies[i]);
                             else {
                                  treePanel.addObject(offlineNode, buddies[i]);
                        } catch (RemoteException e1) {
                             e1.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
         * This method initializes jJMenuBar     
         * @return javax.swing.JMenuBar     
         private JMenuBar getJJMenuBar() {
              if (jJMenuBar == null) {
                   jJMenuBar = new JMenuBar();
                   jJMenuBar.add(getJMenu());
                   jJMenuBar.add(getJMenu1());
                   jJMenuBar.add(getJMenu2());
              return jJMenuBar;
         * This method initializes jMenu     
         * @return javax.swing.JMenu     
         private JMenu getJMenu() {
              if (jMenu == null) {
                   jMenu = new JMenu();
                   jMenu.setText("My IM");
              return jMenu;
         * This method initializes jMenu1     
         * @return javax.swing.JMenu     
         private JMenu getJMenu1() {
              if (jMenu1 == null) {
                   jMenu1 = new JMenu();
                   jMenu1.setText("People");
              return jMenu1;
         * This method initializes jMenu2     
         * @return javax.swing.JMenu     
         private JMenu getJMenu2() {
              if (jMenu2 == null) {
                   jMenu2 = new JMenu();
                   jMenu2.setText("Help");
              return jMenu2;
         * This method initializes imagePanel     
         * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(6, 2, 176, 125);
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/cute_dog.jpg"));
                        Image scaled = bi.getScaledInstance(
                                  imagePanel.getWidth(), imagePanel.getHeight(), BufferedImage.SCALE_FAST);
                        final JLabel imageLabel = new JLabel(new ImageIcon(scaled));
                        imageLabel.setToolTipText("Double click to change image");
                        imagePanel.add(imageLabel, imageLabel.getName());
                        imageLabel.addMouseListener(new java.awt.event.MouseAdapter() {
                             public void mouseClicked(java.awt.event.MouseEvent e) {
                                  if (e.getClickCount() == 2) {
                                       Image selected = imageUpdater.getSelectedImage();
                                       if (selected != null) {
                                            BufferedImage bi = (BufferedImage) selected;
                                            Image scaled = bi.getScaledInstance(
                                                      imageLabel.getWidth(), imageLabel.getHeight(), BufferedImage.SCALE_DEFAULT);
                                            imageLabel.setIcon(new ImageIcon(scaled));
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
         * This method initializes jSeparator1     
         * @return javax.swing.JSeparator     
         private JSeparator getJSeparator1() {
              if (jSeparator1 == null) {
                   jSeparator1 = new JSeparator();
                   jSeparator1.setBounds(6, 132, 176, 1);
              return jSeparator1;
         public void buddySignedOn(String screenname) throws RemoteException {
              final String temp = screenname;
              Runnable addBuddy = new Runnable() {
                   public void run() {
                        treePanel.addObject(onlineNode, temp);
              SwingUtilities.invokeLater(addBuddy);
         public void buddySignedOff(String screenname) throws RemoteException {
              // TODO Auto-generated method stub
         public boolean equals(Object o) {
              Buddylist buddylist = (Buddylist) o;
              return connectionID == buddylist.connectionID;
         public int hashCode() {
              return connectionID;
    } // @jve:decl-index=0:visual-constraint="10,11"
    * Created on Nov 4, 2006
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
         public void buddySignedOff(String screenname) throws RemoteException;
    * Created on Oct 14, 2006
    * Models a single endpoint of a connection between machines.
    * @author Josh Feldman
    public class Connection {
         private String username;
         private final int connectionID;
         private Buddylist callback = null;
         public Connection(String username, int connectionID) {
              this.username = username;
              this.connectionID = connectionID;
         public Connection(int connectionID) {
              this.connectionID = connectionID;
         public String getUsername() {
              return username;
         public int getConnectionID() {
              return connectionID;
         public void setCallback(Buddylist buddylist) {
              this.callback = buddylist;
         public Buddylist getCallback() {
              return callback;
         public boolean equals(Object o) {     
              Connection otherConnection = (Connection) o;
              if (otherConnection.getConnectionID() == this.connectionID) {
                   return true;
              else {
                   return false;
         public int hashCode() {
              return connectionID;
    * Created on Nov 4, 2006
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.Serializable;
    import java.util.Properties;
    public class Database implements Serializable{
         private final String regex = ";";
         private Properties db = null;
         private String dbPath = "buddies.txt";
         public Database() throws IOException {
              db = new Properties();
              File buddiesFile = new File(dbPath);
              if (!buddiesFile.canRead()) {
                   throw new IOException("Can't read database!");
              try {
                   FileInputStream fis = new FileInputStream(buddiesFile);
                   db.load(fis);
                   System.out.println("database loaded from file");
              } catch (IOException e) {
                   e.printStackTrace();
                   System.err.println("Can't load the database! Exiting program...");
                   System.exit(0);
          * called when a user adds/deletes a user from the buddylist
         public void changeBuddyList() {
              //TODO
         public boolean doesUserExist(String username) {
              System.out.println(db.getProperty(username));
              return db.getProperty(username) != null;
         public String getPassword(String username) {
              String temp = db.getProperty(username);
              String [] split = temp.split(regex);
              if (split.length == 2)
                   return split[0];
              else {
                   return null;
         public String getBuddies(String username) {
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1];
          * Determines whether screename1 is a buddy of screename2
          * @return
         public boolean areBuddies(String screename1, String screename2) {
              String [] buddies = getUserBuddies(screename2);
              if (buddies == null) {
                   return false;
              else {
                   for (int i = 0; i < buddies.length; i++) {
                        if (buddies.equals(screename1)) {
                             return true;
              return false;
         public String [] getUserBuddies(String username) {
              System.out.println("in db getUserBuddies: username = " + username);
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1].split(",");
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    // Note that this is not my code but rather code taken
    // from java Sun tutorial
    public class DynamicTree extends JPanel {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        public DynamicTree() {
            rootNode = new DefaultMutableTreeNode("Root Node");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setRootVisible(false);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(false);
            JScrollPane scrollPane = new JScrollPane(tree);
            setLayout(new GridLayout(1,0));
            add(scrollPane);
        /** Remove all nodes except the root node. */
        public void clear() {
            rootNode.removeAllChildren();
            treeModel.reload();
        /** Remove the currently selected node. */
        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;
        public void removeObject(DefaultMutableTreeNode child) {
             treeModel.removeNodeFromParent(child);
    //         treeModel.reload();
        /** Add child to the currently selected node. */
        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) {
            return addObject(parent, child, false);
        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 lovely new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        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) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
        public DefaultTreeModel getModel() {
             return treeModel;
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import javax.swing.JComponent;
    * Generic Dialog for allowing a user to browse
    * his filesystem for an image file. Dialog
    * displays a preview of the image (if it is in fact
    * displayable).
    * @author Josh Feldman
    public class ImageChooser extends JComponent implements ImageUpdater{
         private Frame parent = null;
         public ImageChooser(Frame parent) {
              super();
              this.parent = parent;
         public Image getSelectedImage() {
              ImageChooserDialog dialog = new ImageChooserDialog(parent);
              if (dialog.showDialog() == ImageChooserDialog.OK_OPTION) {
                   return dialog.getSelectedImage();
              return null;
    }  //  @jve:decl-index=0:visual-constraint="10,10"
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    * Class that displays a dialog that allows a user
    * to browse his/her filesystem for an image file
    * for selection.
    * @author Josh Feldman
    public class ImageChooserDialog extends JDialog {
         private Frame parent = null;
         private JFileChooser fileChooser = new JFileChooser();
         private int option;
         public final static int OK_OPTION = 1;
         public final static int CANCEL_OPTION = 2;
         private Image selectedImage = null;
         private javax.swing.JPanel jContentPane = null;
         private JPanel previewPanel = null;
         private JLabel jLabel = null;
         private JTextField filenameTextField = null;
         private JButton browseButton = null;
         private JButton cancelButton = null;
         private JButton okButton = null;
         private JLabel previewLabel = null;
          * This is the default constructor
         public ImageChooserDialog(Frame parent) {
              super();
              this.parent = parent;
              this.setTitle("Select Image");
              initialize();
         public ImageChooserDialog(Frame parent, String title) {
              super();
              this.parent = parent;
              this.setTitle(title);
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setModal(true);
              this.setSize(377, 246);
              this.setContentPane(getJContentPane());
              this.setVisible(false);
              this.setLocationRelativeTo(parent);
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        selectedImage = null;
                        option = CANCEL_OPTION;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jLabel.setBounds(87, 192, 58, 10);
                   jLabel.setText("Preview");
                   jContentPane.add(getPreviewPanel(), null);
                   jContentPane.add(jLabel, null);
                   jContentPane.add(getFilenameTextField(), null);
                   jContentPane.add(getBrowseButton(), null);
                   jContentPane.add(getCancelButton(), null);
                   jContentPane.add(getOkButton(), null);
              return jContentPane;
          * This method initializes previewPanel     
          * @return javax.swing.JPanel     
         private JPanel getPreviewPanel() {
              if (previewPanel == null) {
                   previewPanel = new JPanel();
                   previewLabel = new JLabel();
                   previewPanel.setLayout(null);
                   previewPanel.setLocation(25, 62);
                   previewPanel.setSize(172, 125);
                   previewPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
                   previewLabel.setText("");
                   previewLabel.setLocation(2, 2);
                   previewLabel.setSize(172, 125);
                   previewPanel.add(previewLabel, null);
              return previewPanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField
         private JTextField getFilenameTextField() {
              if (filenameTextField == null) {
                   filenameTextField = new JTextField();
                   filenameTextField.setBounds(26, 17, 212, 23);
                   filenameTextField.setEditable(false);
              return filenameTextField;
          * This method initializes jButton     
          * @return javax.swing.JButton     
         private JButton getBrowseButton() {
              if (browseButton == null) {
                   browseButton = new JButton();
                   browseButton.setBounds(254, 18, 102, 21);
                   browseButton.setText("Browse");
                   browseButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) { 
                             ImageFilter imageFilter = new ImageFilter();
                             fileChooser.setFileFilter(imageFilter);
                             int value = fileChooser.showOpenDialog(ImageChooserDialog.this);
                             if (value == JFileChooser.APPROVE_OPTION) {
                                  File selected = fileChooser.getSelectedFile();
                                  if (selected.canRead()) {
                                       try {
                                            BufferedImage bi = ImageIO.read(selected);
                                            selectedImage = bi;
                                            Image scaled = bi.getScaledInstance(
                                                      previewPanel.getWidth(), previewPanel.getHeight(), BufferedImage.SCALE_FAST);
                                            ImageIcon imageIcon = new ImageIcon(scaled);
                                            previewLabel.setIcon(imageIcon);
                                            filenameTextField.setText(selected.getAbsolutePath());
                                       } catch (IOException e1) {
                                            previewLabel.setText("Preview unavailable...");
                                            selectedImage = null;
                                            e1.printStackTrace();
              return browseButton;
          * This method initializes jButton1     
          * @return javax.swing.JButton     
         private JButton getCancelButton() {
              if (cancelButton == null) {
                   cancelButton = new JButton();
                   cancelButton.setBounds(254, 122, 100, 24);
                   cancelButton.setText("Cancel");
                   cancelButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             selectedImage = null;
                             option = CANCEL_OPTION;
                             ImageChooserDialog.this.dispose();
              return cancelButton;
          * This method initializes jButton2     
          * @return javax.swing.JButton     
         private JButton getOkButton() {
              if (okButton == null) {
                   okButton = new JButton();
                   okButton.setBounds(256, 159, 97, 24);
                   okButton.setText("OK");
                   okButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             option = OK_OPTION;
                             ImageChooserDialog.this.dispose();
              return okButton;
          * Displays this chooser dialog.
          * @return - The user selected option
          *                (i.e. OK_OPTION, CANCEL_OPTION)
         public int showDialog() {
              this.setVisible(true);
              return option;
          * Returns the image chosen by the user.
          * @return
         public Image getSelectedImage() {
              return selectedImage;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    public class ImageFilter extends FileFilter {
        //Accept all directories and all gif, jpg, tiff, or png files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = Utils.getExtension(f);
            if (extension != null) {
                if (extension.equals(Utils.tiff) ||
                    extension.equals(Utils.tif) ||
                    extension.equals(Utils.gif) ||
                    extension.equals(Utils.jpeg) ||
                    extension.equals(Utils.jpg) ||
                    extension.equals(Utils.png)) {
                        return true;
                } else {
                    return false;
            return false;
        //The description of this filter
        public String getDescription() {
            return "Just Images";
    * Created on Sep 24, 2006
    import java.awt.Image;
    * Contract that specifies how a class can update
    * the view in its graphical display.
    * @author Josh Feldman
    public interface ImageUpdater {
         public Image getSelectedImage();
    * Created on Nov 4, 2006
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.rmi.Naming;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    public class LoginFrame extends JFrame {
         private String serverName = "//Broom:5001/IMServer";
         private ServerInter serverInter = null;
         // The icon to be used when this frame is minimized
         private Image icon;
         // The main image to be displayed on this frame
         private Image robotImage;
         private javax.swing.JPanel jContentPane = null;
         private JPanel imagePanel = null;
         private JLabel screenameLabel = null;
         private JTextField screenameTextField = null;
         private JPanel jPanel1 = null;
         private JLabel passwordLabel = null;
         private JPasswordField passwordTextField = null;
         private JButton signonButton = null;
         private JButton helpButton = null;
          * This is the default constructor
         public LoginFrame() {
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setResizable(false);
              this.setSize(210, 368);
              this.setContentPane(getJContentPane());
              this.setTitle("Sign On");
              try {
                   this.setIconImage(ImageIO.read(new File("images/robby3.jpg")));
              } catch (IOException e) {
                   e.printStackTrace();
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jPanel     
          * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(7, 7, 190, 159);
                   imagePanel.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,0));
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/robby_big.bmp"));
                        Image scaled = bi.getScaledInstance(190, 169, BufferedImage.SCALE_FAST);
                        JLabel robotLabel = new JLabel(
                                  new ImageIcon(scaled));
                        imagePanel.add(robotLabel);
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField     
         private JTextField getScreenameTextField() {
              if (screenameTextField == null) {
                   screenameTextField = new JTextField();
                   screenameTextField.setBounds(22, 208, 168, 20);
                   screenameTextField.addKeyListener(new java.awt.event.KeyAdapter() {  
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return screenameTextField;
          * This method initializes jPanel1     
          * @return javax.swing.JPanel     
         private JPanel getJPanel1() {
              if (jPanel1 == null) {
                   jPanel1 = new JPanel();
                   jPanel1.setBounds(8, 173, 188, 1);
                   jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,5));
              return jPanel1;
          * This method initializes jPasswordField     
          * @return javax.swing.JPasswordField     
         private JPasswordField getPasswordTextField() {
              if (passwordTextField == null) {
                   passwordTextField = new JPasswordField();
                   passwordTextField.setBounds(20, 259, 170, 20);
                   passwordTextField.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return passwordTextField;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   passwordLabel = new JLabel();
                   screenameLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   screenameLabel.setBounds(22, 182, 132, 20);
                   screenameLabel.setText("Screename");
                   screenameLabel.setEnabled(true);
                   screenameLabel.setFont(new java.awt.Font("Century Gothic", java.awt.Font.BOLD, 12));
                   passwordLabel.setBounds(21, 238, 135, 17);
                   passwordLabel.setText("Password");
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(screenameLabel, null);
                   jContentPane.add(getScreenameTextField(), null);
                   jContentPane.add(getJPanel1(), null);
                   jCon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

  • Updating Jtree witout loosing selected Path

    Hi,
    I want the user to be able to get the most recent version of the database structure that is represented by the tree, without loosing the selected path.
    that's mean i would like to update the Jtree structure without changing the selected path.
    i tried to use myJtree.getModel.nodeStructureChanged((TreeNode) changedNode) but without success the selcted path is losed.
    Is there any idea?
    Thanks in advance

    no this dosen't work , here after my code:
    DefaultMutableTreeNode addedNode=new DefaultMutableTreeNode("NewNode");
    ParentNode.add(addedNode);
    // and i fired this event to cheng the tree
    ((DefaultTreeModel) myTree.getModel())).nodeStructureChanged((TreeNode) node);
    but with this i lose mu selected Path
    and i also tried this
    ((DefaultTreeModel) myTree.getModel())).nodeChanged((TreeNode) node);
    but no success i can't update my tree structure

  • ConcurrentModificationException when updating jtree

    Hi,
    I've got some code to update my jtree problem written earlier, I don't know if it works yet though!
    I'm getting a ConcurrentModificationException when accessing an iterator of a hashmap I'm using. Does anyone know of how to get rid of these horrible little exceptions?
    please help. Thanks for your possible replies!
    later - Edd.

    Get a synchronized set/map and iterate through that instead of your set/map.
    Set s = Collections.synchronizedSet(yourSet);
    Map s = Collections.synchronizedMap(yourMap);nes

  • Help with JTree refresh

    I am having trouble displaying a JTree with newly added nodes.
    I have a JTree, inside a JPanel, JScrollPane and JSplitPane.
    I create the JTree with a single root node which displays correctly.
    I update the JTree with new children which displays correctly.
    Using the same exact routine as above - I add additional new children to the root, the new children do not display in the JTree.
    I have confirmed that I am using the correct tree and root node in debug that the tree/node objects has been correctly updated. It is just not displaying the new children to the root.
    I can expand and collapse the tree which does not show the new children, just the original populated root.
    After the root has been updated, I have tried a number of methods to resolve: tree/jpanel/jscrollpane/jsplitpane .revalidate, invalidate, repaint, etc.
    I am using v1.4.1.
    What am I missing here?
    Thanks in advance.

    i use two classes fro add or insert nodes in a tree, one adds the node at the same level of the current selected node, and the other intert it inside:
    // InsertaTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class InsertaTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public InsertaTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public InsertaTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              //insertIndex = parent.getIndex(insertNode) + 1;
              //insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo Insertado"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);
    // AnadeTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class AnadeTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public AnadeTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public AnadeTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              insertIndex = parent.getIndex(insertNode) + 1;
              insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo A�adido"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);

Maybe you are looking for