Help with JTree's opaque methods

I have been looking through the methods provided for JTree in Netbeans GUIBuilder and I do not see accessor methods for actions like insertion, retrieval, deletion and replacement. I am looking for something like this.
JTree.insert('object', JTree.getSelectedNode());
JTree.getSelectedNode().getObject();
JTree.deleteNode(JTree.getSelected());
JTree. supplantObject(‘object’, JTree.getSelectedNode());
JTree.insert('object', JTree.getSelectedNode()) should accept to inputs; the object you wish to insert and the location you wish to insert it. JTree.getSelectedNode() would be an accessor method returning the selected node. The insert would have to find the next available element in the LinkedList, array, hashtable, stack, (or whatever it uses) and inserts the object.
JTree.getSelectedNode().getObject(); I assume that if I have “apple” selected in the JTree, “apple” will be returned.
JTree.deleteNode(JTree.getSelected()); deleting the node wipes out all its children as well.
JTree. supplantObject(‘object’, JTree.getSelectedNode()); overwrites the object in the selected with a new object.
These seem like the more obvious accessor methods and I am astonished to find them missing or named something inconsistent with java standards.
So I guess my question is, what are the equivalent method names for the aforementioned methods?
BM

Take a look at [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html] which has most of the methods that you are interested in. A JTree has a single root node, which by default is of this type.

Similar Messages

  • Help with JTree Update

    Hi there,
    I need to do a simple thing with a JTree but I 've got a problem. Well I want to create a very very very simple bookmark function. I have a tree with the children and I want to add new children which are going to work like link for my program. I try to add new children the same way I created them but it's not working. I tried also the updateUI method that somebody mentioned in an other topic but still nothing. Can somebody help?
    Here is the Bookmark Panel code:
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.awt.*;
    public class BookmarkTry implements TreeSelectionListener {
        private JScrollPane scrollPane;
        private JLabel label;
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Bookmarks");
        private JTree tree;
        private JPanel panel = new JPanel();
         public BookmarkTry(){
         public JPanel createpanel(){
         tree = new JTree(root);
         root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 1","about.html")));
        root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 2","aaa.html")));
        root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 3","sdss.html")));
        // build tree
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.addTreeSelectionListener(this);// get selection events!
        // build form
        scrollPane = new JScrollPane(tree);
        label = new JLabel(" ");
        //scrollPane.setViewportView(tree);
        panel.add(label);
        panel.add(scrollPane);
        return panel;
        public void addBookMarks(String name, String page){
             root.add(new DefaultMutableTreeNode(new Bookmark(name,page)));
             //DefaultTreeModel.reload();
        public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if ((selectedNode!=null)&&(selectedNode.isLeaf())) {
                Bookmark b = (Bookmark)selectedNode.getUserObject();
                label.setText("Go to page "+b.getPage());
        private static class Bookmark {
            private String caption;
            private String page;
            public String getPage() {
                return page;
            public Bookmark(String caption, String page) {
                this.caption = caption;
                this.page = page;
            public String toString() {
                return caption;
         and here how I try to add the node :
    void jButton1_actionPerformed(ActionEvent e) throws java.sql.SQLException {
            DefaultMutableTreeNode book = null;
            System.out.println("You pressed the add button of bookmarkframe");
            //Bookmark.getTreePanel().addObject(name.getText());
            //book = new DefaultMutableTreeNode(new BookInfo(name.getText(),page.getText()));
            System.out.println(name.getText());
            System.out.println(page.getText());
            tempb.addBookMarks(name.getText(),page.getText());
            frame.dispose();
       } //void jButton1_actionPerformedIt doesn't add the new node in my JTree
    Thanks in advance

    I still suspect you have two (or more) new BookmarkTry() executions somewhere. But I can't see all of your code here of course. My standard reply, so we don't waste time guessing:
    1) In the future, Swing related questions should be posted in the Swing forum.
    2) If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    Note, we don't want your whole application. We want an SSCCE!

  • Pls help with JTree editor problem

    Hi,
    I have a JTree where each node in the tree is a JPanel. In each
    JPanel are two JTextField objects. Only one of the JTextField objects
    is editable.
    When I click on node (a line in the JTree) with the mouse, it is
    painted using the custom editor (TreeCellEditor) that I have written.
    When the selected and editable JTextField has the focus, and when a
    certain key is hit, I capture that key, do some things, and then select
    a different node in the JTree.
    When selecting the new node, I need the node to be painted with
    the editor, just as if I had clicked on it with the mouse.
    In the method called as a result of the key binding, I call the
    following --
    TreeUI.stopEditing( JTree ) -- stops editing of the cell that resulted
    in the key binding call
    TreeUI.startEditingAtPath( JTree, TreePath )
    -- according to the JavaDocs, this should select the new cell and
    start editting of it.
    This last method does call my editor to get the components, but then my
    Renderer is also called (twice in fact). When the cell is painted, it is
    painted with the Renderer's components.
    PLEASE HELP HERE !

    Thank you so much for giving a reply to this problem.
    I will experiment with your suggestion. However, in looking at the JavaDocs
    I would need to make one class that implements both TreeCellEditor and
    TreeCellRenderer, with the methods getTreeCellEditorComponent() and getTreeCellRendererComponent(). Since currently, my editor is called and then
    my renderer is called, over-writing the editor's result, I would suspect that
    both of these methods would also be called (even though they are in the same
    class), having the same effect.
    Again, thank you.

  • Help with JTree data by user input

    I am trying to read data into a JTree without it being hardcoded.
    An example of the data is:
    String data[] = {"a","b","c",";","b","g","h",";","c","t",";","g","u"};
    The above data is taken from user input and stored in an array and checked for errors.
    I want to somehow read take the above array's data and put it into following format in some kind of loop but I am not sure how.
    Object[] hierarchy = {"a", new Object[]{"b",new Object[]{"g","u"},"h"},new Object[]{"c","t"}};
    This Object is then passed to a function that interpets it and prints out the appropriate JTREE structure. For the values above it would be:
    a
    ..b
    ....g
    ......l
    ......u
    ....h
    ..c
    ....t
    Tha problem is how to take the string array and put that data correctly into the Object array. I have been racking my feeble mind for quite sometime and if any one out there can see it or has a better idea of how to get my data into the JTree please let me know.
    Thanks

    //OutlookClient.java
    //uses also Console class from Bruce Eckel 
    //<applet code=OutlookClient width=500 height=300>
    //</applet>
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    import javax.swing.UIManager;
    import javax.swing.SwingUtilities;
    import BruceEckel.*;
    import DynamicTree.*;
    import DynamicTreeNode.*;
    import java.lang.reflect.*;
    /* a class creating a dialog with the version, and other details about the program*/
    class AboutDialog extends JDialog {
         private JButton ok = null;
         private Container cp = null;
         private JTextField tname = null;
            public AboutDialog() {
                   //System.out.println("constructor");
                   ok = new JButton("OK");
                   cp = getContentPane();
                   cp.setLayout(new FlowLayout());
                   JLabel tlab = new JLabel("Outlook - client side");
                   cp.add(tlab);
                   //tname.setMinimumSize(new Dimension(50,10));
                   //tname.setSize(new Dimension(70,10));
                   tlab = new JLabel("Author: Jiri Machotka");
                   cp.add(tlab);
                   tlab = new JLabel("version 1.0 (September 2001)");
                   cp.add(tlab);
                   tlab = new JLabel("----------------------------------------------");
                   cp.add(tlab);
                   ok.addActionListener( new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        dispose();
                      }//actionPerformed
                   });//addActionListener
                   cp.add(ok);
                   setSize(200,150);
                   setTitle("About the program");  
                   setModal(true);
         }//constructor
      *      <P>This class more-or-less contains a graphic design object used for interaction with a user.</P>
      *     Apart from all ScrollPanes, Buttons, and MenuItems, it contains also 3 interesting members:
      *     <ol>
      *     <li> <I>protected final DefaultMutableTreeNode topNode</I>, which is initialized with
      * a potent, non-removable object of the class <I>Node</I>
      *     <li> <I>protected final DefaultTreeModel treeModel</I>, which is initialized with the <I>topNode</I>
      *     <li> and finally <I>protected final DynamicTree dyn_tree</I>, which uses the 2 objects above
      *     </ol>
      *     <P> The <I>OutlookClient</I> is an applet, but it can be also processed as an application (thanks to
      *     a library by BruceEckel).</P>
    public class OutlookClient extends JApplet {
    //------------- properties -----------------------------------------
       private Action
            newMail = new AbstractAction ("New Mail", new ImageIcon("images/NewMailIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("NewMail");
         reply     = new AbstractAction ("Reply", new ImageIcon("images/ReplyIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("Reply");
       private JButton
         /*b1 = new JButton("Add a Node"),
         b2 = new JButton("Remove the current Node"),*/ //not used now
         tb1 = new JButton (newMail),
         tb2 = new JButton (reply);
       private JTextField
         txt = new JTextField(10);
       private Container
         leftArea = new Container(),
         rightArea = new Container();
       private JScrollPane
            left = new JScrollPane (leftArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
            right = new JScrollPane (rightArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
       private JSplitPane
            sp = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, left, right);
       private JToolBar
         toolBar = new JToolBar();
       private JMenuBar
         menuBar = new JMenuBar();
       /*ActionListener al = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String name = ( (JButton)e.getSource()).getText();
            txt.setText(name);
       };*/     //not used now - used as an action listener for buttons b1, b2
       private JMenu
         mainOutlookMenu = new JMenu ("Outlook activities"),
         othersMenu      = new JMenu ("Others"),
         mailMenu     = new JMenu ("Mails"),
         chatMenu     = new JMenu ("Chat"),
         look_and_feelMenu = new JMenu ("Look&Feel");
       private JMenuItem
         closeAppItem     = new JMenuItem ("Exit",KeyEvent.VK_F3),
         newMailItem     = new JMenuItem (newMail),
         replyItem     = new JMenuItem (reply);
       private JRadioButtonMenuItem
         windowsLookAndFeelItem;
       protected final DefaultMutableTreeNode topNode = new DefaultMutableTreeNode(new Node ("Outlook", false, true));
       protected final DefaultTreeModel treeModel = new DefaultTreeModel(topNode);
       protected final DynamicTree dyn_tree = new DynamicTree(topNode, treeModel);
    //-------------inner classes----------------------------------------
    /** <P>The class <I>MyRenderer</I> sets the renderer of the tree - by doing that icons can be assigned to
       * the tree's nodes. </P>
       * <P> It sould be probably a standard member of a class <I>DynamicTreeWithIcons</I>.</P>
       * <P> However, it uses the knowledge that the class <B>Node</B>, which is the only object that can be
       * found in the dynamic tree in this application, has a method <I>getIcon()</I>, which returns a
       * reference to the icon object assigned to the node.</P>
       * <P><B>This is the only place, where the class Node, or its methods are called explicitely.</B></P>
       protected class MyRenderer extends DefaultTreeCellRenderer {
         /** The constructor of the class.
           * - sets folders icons (opened, closed folder)
         public MyRenderer() {
                 //setLeafIcon(new ImageIcon("images/middle.gif")); //for leaves' icon, all at once!
              setOpenIcon(new ImageIcon("images/folder_open.gif"));
              setClosedIcon(new ImageIcon("images/folder_close.gif"));
         /** This overridden method gets the user-specified icon for leaf nodes. */
         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) 
              //workaround: test if icon not eq. null
                     ImageIcon ic = getRightIcon(value);
                     if (ic == null) return this;
                     else
                          setIcon(ic);
              return this;
         }//overridden: getTreeCellRendererComponent
         private ImageIcon getRightIcon(Object value) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              try{
              Node node_object = (Node)(node.getUserObject());   
                 return (node_object.getIcon());
           catch (Exception e) { return null; }
         }// ImageIcon getRightIcon(Object value)
      }//class MyRenderer
    //-------------OutlookClient methods-----------------------------------------
       private void assignListeners(){
         dyn_tree.addTreeSelectionListener(new TreeSelectionListener() {
             public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)dyn_tree.getLastSelectedPathComponent();
              if (node == null) return;
              if (node.isLeaf()) { txt.setText(node.toString()); }
       }//assignListeners()
       private void createLayout(){
         leftArea.setLayout(new BoxLayout(leftArea,BoxLayout.Y_AXIS));
         rightArea.setLayout(new BoxLayout(rightArea,BoxLayout.Y_AXIS));
         //left.setMinimumSize(new Dimension(120,200));
         right.setMinimumSize(new Dimension(50,50));
         //rightArea.add(b1);
         //rightArea.add(b2);
         rightArea.add(txt);
         //leftArea.add(tree);  ... not nice (why?)
           left = new JScrollPane (dyn_tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);       
         left.setMinimumSize(new Dimension(180,200));
         sp.setLeftComponent(left);
       }//createLayout()
       private void createMenu(){
         ButtonGroup group = new ButtonGroup();
            JRadioButtonMenuItem rbMenuItem;
         closeAppItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, ActionEvent.ALT_MASK));
         closeAppItem.getAccessibleContext().setAccessibleDescription("Closes application");
         closeAppItem.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {System.exit(0);}
         othersMenu.setMnemonic(KeyEvent.VK_O);
         othersMenu.getAccessibleContext().setAccessibleDescription("System settings&Others");
            rbMenuItem = new JRadioButtonMenuItem("Java");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_J);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF(UIManager.getCrossPlatformLookAndFeelClassName( ) );}
            look_and_feelMenu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Windows");
            rbMenuItem.setMnemonic(KeyEvent.VK_W);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");}
            look_and_feelMenu.add(rbMenuItem);
         windowsLookAndFeelItem = rbMenuItem;
         look_and_feelMenu.setMnemonic(KeyEvent.VK_L);
         look_and_feelMenu.getAccessibleContext().setAccessibleDescription("Look&Feel");
         JMenuItem aboutItem = new JMenuItem ("About");
         aboutItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   AboutDialog ad = new AboutDialog();
                   ad.show();
         othersMenu.add(look_and_feelMenu);
         othersMenu.addSeparator();
         othersMenu.add(aboutItem);
         othersMenu.addSeparator();
         othersMenu.add(closeAppItem);
         mainOutlookMenu.setMnemonic(KeyEvent.VK_A);
         mainOutlookMenu.getAccessibleContext().setAccessibleDescription("Outlook activities");
         menuBar.add(mainOutlookMenu);
         menuBar.add(othersMenu);
         mailMenu.setMnemonic(KeyEvent.VK_M);
         mailMenu.getAccessibleContext().setAccessibleDescription("Mail activities");
         chatMenu.setMnemonic(KeyEvent.VK_C);
         chatMenu.getAccessibleContext().setAccessibleDescription("Chat");
         chatMenu.setEnabled(false);
         mainOutlookMenu.add(mailMenu);
         mainOutlookMenu.addSeparator();
         mainOutlookMenu.add(chatMenu);
         //mailMenu.add(newMail);
         //mailMenu.add(reply);     //class Action has problems to catch the accelerator keys
         newMailItem.setMnemonic(KeyEvent.VK_N);
         replyItem.setMnemonic(KeyEvent.VK_R);
         mailMenu.add(newMailItem);
         mailMenu.add(replyItem);
         newMailItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
         replyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
         //newMail.putValue(Action.NAME, "New mail");
         //newMail.putValue(Action.SHORT_DESCRIPTION, "New mail");
         //newMail.putValue(Action.LONG_DESCRIPTION, "New mail");
         //newMail.putValue(Action.MNEMONIC_KEY, "N");  //cast an exception. why?
         //newMail.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));     
         setJMenuBar(menuBar);
       }//createMenu()
       private void createToolBar(){
         //toolBar.add(newMail);
         //toolBar.add(reply);    //does not provide texts and mnemonics
         tb1.setMnemonic(KeyEvent.VK_N);
         tb2.setMnemonic(KeyEvent.VK_R);
         toolBar.add(tb1);
         toolBar.add(tb2);
       }//createToolBar()
       private void createNodes(DefaultMutableTreeNode topNode){
         //new for dynamic processing
         DefaultMutableTreeNode
              parentNode = null,
              leaveNode  = null;
         parentNode = dyn_tree.addObject(null,new Node ("MailFolders", false, true));
         dyn_tree.addObject(parentNode,new Node ("Inbox","images/InboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Outbox","images/OutboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Sent","images/SentIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Deleted","images/DeletedIcon.gif", false, false));
         //leaveNode.setEnabled(false);  //TODO: disable "Chat"node
         dyn_tree.addObject(null,new Node ("Chat", false, false));
       }//createcreateNodes(DefaultMutableTreeNode)
       private void setTreeSettings(){
         //one selection at one time
         dyn_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         //connect nodes with a thin line - Java style only
         dyn_tree.putClientProperty("JTree.lineStyle","Angled");
         //collapse the root's children first
         //tree.setShowsRootHandles(false);
         //icon adjustment
         MyRenderer MyRen = new MyRenderer();
         dyn_tree.setCellRenderer(MyRen);
         //modifiable tree - by double click - allows modifying of nodes' names
         // but unfortunately also restores original icons
         //tree.setEditable(true);
       }//setTreeSettings()
       private boolean setPLAF(String LookAndFeelName){
          try{
         UIManager.setLookAndFeel(LookAndFeelName);
         SwingUtilities.updateComponentTreeUI(this);
         return true;
          } catch (Exception e) {
         //e.printStackTrace(System.err);
         return false;
       }//setPLAF(String LookAndFeelName)
       private void trytosetLookAndFeel(){
          if (setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))
              windowsLookAndFeelItem.setSelected(true);
       }//trytosetLookAndFeel()
       /** The applet's <I>init()</I>.
         * Calls methods to construct all visible objects.
         * Apart from that it also assigns the renderer to the tree.
       public void init(){
         sp.setOneTouchExpandable(true);
            //sp.setDividerLocation(150); - system puts the value to optimize the left part
         sp.setPreferredSize(new Dimension(450,200));
         Container cp = getContentPane();
         cp.setLayout(new FlowLayout());
            createLayout();     
         createMenu();
         createToolBar();
         createNodes(topNode);
         setTreeSettings();
         //createPopupMenu();
         assignListeners();
         cp.add(toolBar);
         cp.add(sp);
         trytosetLookAndFeel();
       }//init()
       /** If called as an application.
         * The desired Windows Look&Feel is re-set again, when the applet is running. Otherwise, it in an application
         * it tends not to work correctly.
       public static void main(String[] args) {
         OutlookClient theApplet;
         BruceEckel.Console.run(theApplet=new OutlookClient(), 500, 300);
         theApplet.trytosetLookAndFeel();
       }//main(String[])
    }///:~Take a look namely at createNodes
    Hope it helps.

  • Help with writing a static method in my test case class inside blue j

    I have this method that I have to test. below is the method I need to test and what I have to create inside my test case file to test it Im having big time problems getting going. Any help is appreciated.
    public String introduceSurprise ( String first, String last ) {
    int d1 = dieOne.getFace();
    Die.roll();
    if (d1 %4 == 2){
    return Emcee.introduce(first);
    else {
    return this.introduceSpy (first,last);
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!

    hammer wrote:
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!Those instructions couldn't be anymore straightforward. Make a class called TestEmCee. Have it create an EmCee object. Call introduceSurprise on that object 3 times. Then print the results of calling it a 4th time.

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

  • Help with JTree and JList

    Hi everybody!
    My problem is this:
    I have in a panel a JTree. This tree has a root and several children called GROUPs. Every GROUP has several children called MODULEs. Every MODULE have several children called RULEs.
    The JTree is already constructed with a function that I have implemented and that reads the data necessary to fill the tree.
    What I would like to get, and I do not know how, is that when I press with the mouse in "Root" I can see a list, on the right side of the tree, with all the GROUPs that it contains. Besides, when I press with the mouse in a GROUP I can see the list of MODULEs that it contains. And finally that when I press with the mouse in a MODULE I can see the RULEs that it contains.
    I think that it is done by using listeners and so on, but actually I do not understand well how it works.
    I would be very grateful whether any of you could show me a piece of code (at least some guidelines) of the function that I would have to implement. And of course, a little bit of explanation about the use of listeners and so on that are necessary to do these kind of things.
    I am a total begginer and I need your help.
    Thanks a lot in advance,
    Fran.

    Please, helpppppppppppp!!!!!!!!!!!!!!!!!!!!!!!
    :)

  • Help with JTrees

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

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

  • Need help with a reverse number method

    hey all..
    i have this program which should return the integer reversed ..
    i have done this program using methods.. but the problem is if the
    number endes with 0 when it reversed the output doesn't contain the number 0
    for example:
    input
    123450
    output
    54321
    where before the 5 there should be 0
        This program that reads an integer and then calls a method
          that receives an integer and returns the integer with its digits reversed.
          Main prints the resulting integer.
       import java.util.Scanner; // program uses class Scanner
        class Sh9q4
           // main method begins execution of Java application
           public static void main( String args[] )
          // create Scanner to obtain input from command window
             Scanner input = new Scanner( System.in );
             int number; // The number entered by the user
             System.out.println("Enter an integer"); // prompt for input
             number = input.nextInt(); // read the the integer
             reverse (number); // print the method reverse
          } // end method main
           public static void reverse ( int num )
             int lastDigit; // the last digit returned when reversed
             int reverse = 0;
             do
                lastDigit = num % 10;
                reverse = (reverse * 10) + lastDigit;
                num = num / 10;
             while (num > 0);
             System.out.println("The integer with its digits reversed " + reverse); // print the integer reversed
          }// end method reverse
       } // end class Sh9q4thanks for your help :)

    If you need the leading zero to display, then you will have to do as Keith recommended and convert the input number to a String, then reverse that String and print it as a String.
    A number is a number is a numerical value, and there is no difference between the value of 054321 and 54321 except when written as a literal, when the first is an octal, and the second a decimal, value.
    If you are still confused, plug in these few lines of code and run them:String str = "012345";
    int x = Integer.parseInt (str);
    System.out.println(str);
    System.out.println(x);db

  • Please help with JTree.setSelectionPath

    Hi....i have a split window, with a JTree on the left and a heap of small pic on the right. If i select any node in the tree, my program can highlight the corresponding pic on the right. Now, my problem is how to select the tree node, if i select the pic on the right first.
    I tried to use setSelectionPath(TreePath)...but i couldnt get the TreePath. I also tried to create a new path, by
    TreePath path1 = new TreePath(Object[]{root, object1});
    where, object1 is the selected object from the right split (the pic)
    Please help me...thanx a lot !!

    Please go to
    http://forums.java.sun.com/thread.jsp?forum=57&thread=164386
    Hope this will help u

  • Help with JTree node handles icon

    Hi
    In my application i use Jtree to display the hirearchical data.But i don't want to the node handles icon to be displayed in the screen.The root node handle icon will be not be displayed if we set jtree.setShowsRootHandles(false) .Is there any way to diable the other node handles icons too?.Please help me in overcoming the problem.
    So, i will be handling the expand/collapse operations of the node with the help of mouse click event.
    Thanks in advance.
    Regards,
    Krish.

    Hi all,
    Any ideas to overcome this problem.?
    Thanks,
    Krish

  • Help with Deque, insertRight() removeLeft() Methods in particular

    Hello,
    I am attempting to implement a deque, I have working insert left and remove right methods as a normal queue works. --->
    However I am having trouble implementing my insert right and remove left methods... keep hitting an array out of bounds problem, guess my wrap arounds aren't working properly. I've tried drawing this out, and I still can't seem to get this to work, can someone please help?
          * Javadoc Here
         public void insertRight(long j) {
              if (front == - 1)
                   front = maxSize-1;
              queArray[++front] = j;
              nItems++; // one more item
          * Javadoc Here
         public long removeLeft() {
              long temp = queArray[rear--];
              if (rear == -1)
                   rear = maxSize;
              nItems--; // one less item
              return temp;
         }

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
         at Deque.removeLeft(Deque.java:71)
         at DequeApp.main(Deque.java:134)
    My javadocs are written because im still in the process of writing the damn thing, give me a break please?
    * This class is to demonstrate.....
    * @version 1.0
    public class Deque {
         private int maxSize;
         private long[] queArray;
         private int front;
         private int rear;
         private int nItems;
          * Java Doc
         public Deque(int s) // constructor
              maxSize = s;
              queArray = new long[maxSize];
              front = 0;
              rear = -1;
              nItems = 0;
          * Javadoc Here
         public void insertLeft(long j) {
              if (rear == maxSize - 1) // deal with wraparound
                   rear = -1;
              queArray[++rear] = j; // increment rear and insert
              nItems++; // one more item
          * Javadoc Here
         public long removeRight() {
              long temp = queArray[front++]; // get value and incr front
              if (front == maxSize) // deal with wraparound
                   front = 0;
              nItems--; // one less item
              return temp;
               * Javadoc Here
              public void insertRight(long j) {
                   if (front == - 1)
                        front = maxSize-1;
                   queArray[++front] = j;
                   nItems++; // one more item
               * Javadoc Here
              public long removeLeft() {
                   long temp = queArray[rear--];
                   if (rear == -1)
                        rear = maxSize;
                   nItems--; // one less item
                   return temp;
          * Javadoc Here
         public boolean isEmpty() {
              return (nItems == 0);
          * Javadoc Here
         public boolean isFull() {
              return (nItems == maxSize);
    }// end Deque Class
    class DequeApp {
         public static void main(String[] args) {
              Deque q1 = new Deque(5); // queue holds 5 items
              q1.insertLeft(10); // insert 4 items
              q1.insertLeft(20);
              q1.insertLeft(30);
              q1.insertLeft(40);
              q1.removeRight(); // remove 3 items
              q1.removeRight(); // (10, 20, 30)
              q1.removeRight();
              q1.insertLeft(50); // insert 4 more items
              q1.insertLeft(60); // (wraps around)
              q1.insertLeft(70);
              q1.insertLeft(80);
              while (!q1.isEmpty()) // remove and display
              { // all items
                   long n = q1.removeRight(); // (40, 50, 60, 70, 80)
                   System.out.print(n);
                   System.out.print(" ");
              System.out.println("----->");
              Deque q2 = new Deque(5); // queue holds 5 items
              q2.insertRight(10); // insert 4 items
              q2.insertRight(20);
              q2.insertRight(30);
              q2.insertRight(40);
              q2.removeLeft(); // remove 3 items
              q2.removeLeft(); // (10, 20, 30)
              q2.removeLeft();
              q2.insertRight(50); // insert 4 more items
              q2.insertRight(60); // (wraps around)
              q2.insertRight(70);
              q2.insertRight(80);
              while (!q2.isEmpty()) // remove and display
              { // all items
                   long n = q2.removeLeft(); // (40, 50, 60, 70, 80)
                   System.out.print(n);
                   System.out.print(" ");
              System.out.println("<-----");
         } // end main()
    } // end class DequeApp
    // //////////////////////////////////////////////////////////////

  • Help with creating a sort method

    I'm trying to create a method that sorts three numbers entered by the user in increasing order IE 1,2,3. I'm having trouble creating the method though, heres what I have
    import java.util.Scanner;
    public class LabFivePartOne {
         public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.println("Enter a number");
              double num1 = input.nextDouble();
              System.out.println("Enter a number");
              double num2 = input.nextDouble();
              System.out.println("Enter a number");
              double num3 = input.nextDouble();
              int k = sort(num1, num2, num3);
              System.out.println(k);
              public static int sort(double num1, double num2, double num3){
                   int result;
                   if (num1 < num2 && num2 < num3)
                        result = ?;
                   else
                        result = ?;
                   return result;
    }I put ? marks after the result = because i'm not sure what to put there, thats what I'm having trouble with.

    try this:
    double [] dblArr = new double [3];
    for (int i = 0; i < 3; i++)
          System.out.println ("Please enter number " + i);
          dblArr = input.nextDouble ();
    for (int x = 0; x < 2; x++)
    for (int y = x+1; y < 3; y++)
    if (dblArr [x] > dblArr [y])
    String temp = dblArr [x];
    dblArr [x] = dblArr [y];
    dblArr [y] = temp;
    Edited by: tam826 on Oct 7, 2008 6:54 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help with JTree

    I wrote a cls that extends JTree....I have defined the root node in this class.
    Public class a extends JTree{
    /// global variable nd constructor
    public void JTReader()
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
               m_model = new DefaultTreeModel(root);
                //program logic to get the parent and child nodes
           //method defined for adding child to parent
           addNode (child,parent);
          //rest of the code
         expandRoot();
         setBounds(0,0,500,500);
    public void addNodeTo(String childNodeName, String parentNodeName)
              //code for chking if the node is already present
              //add child to parent at the end of child list
              ((DefaultTreeModel)getModel()).insertNodeInto(childNode, parentNode, parentNode.getChildCount());     
         }     I want to call this class in my main program which extends Jpanel�.
    I have written this
    public class LibGui extends JDialog{
    private JTreeReader tree;
      JTree newtree;
    Constructor{
        libInit();
    void libInit() throws Exception {
    initializing the panel�
             updateclslist(projectName);
            libScrollPane = new JScrollPane(tree);
            libScrollPane.add(tree);
           clslistHolder.add(libScrollPane, BorderLayout.CENTER);
          cbPanel.add(clslistHolder, BorderLayout.CENTER);
    //rest of code
    protected void updateclslist(String projectName){
        JTreeReader tr = new JTreeReader(projectName);
        tree.JTReader();
         }       

    Swing related questions should be posted in the Swing forum.
    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]How to Use Trees has working examples.

  • Need help with union-by-size method

    Hello :)
    I'm having a problem with a union-by-size method.
    It was originally intended for a university assignment, but as I'm getting random errors by using it, I've changed to using union-by-heigth instead (which works flawlessly :-).
    But I'm still very much interested in finding out what I did wrong with the union-by-size implementation (as I belive it'd be the better method since I use path compression and a lot of find(x)).
    So if anyone can tell me what I'm doing wrong with the following code, I'd really appreciate it. As it is it is I'm getting ArrayIndexOutOfBoundsException with a positive much higher number than the array contains (ie. 1606 with a 900 long array)...
    (I've also gotten a few stackoverflows in main, but I guess that is more with too much printouts... )
    int[] union-by-size-array = new int[n*n] //implemented in other part of the code
    private void union (int root1, int root2){
            int temporaryInteger;
            if(union-by-size-array[root2] < union-by-size-array[root1]){
                temporaryInteger = union-by-size-array[root2];
                union-by-size-array[root1] = root2;
                union-by-size-array[navn2] += temporaryInteger;
            }else {
                temporaryInteger = union-by-size-array[root1];
                union-by-size-array[root2] = root1;
                union-by-size-array[root1] += temporaryInteger;
        }

    Ok, I'll supplement.
    n is given by the user as an argument.
    int nrOfDisJointSets = 1;
    int[][] board = new int[n][n];
    int[] ] union-by-size-array = new int[n+1];
        private void createNewNodeBoard(){
            for(int i = 0; i < n; i++){
                for(int j = 0; j <n; j++){
                    board[i][j] = createNode();
        private Node createNode(){
            Node newNode = new Node(nrOfDisJointSetst);
            union-by-size-array[nrOfDisJointSets] = -1;
            nrOfDisJointSets++;
            return newNode;
        }the union method is called by the following line
    union(find(x), find(y));navn2 is supposed to be root2 btw..

Maybe you are looking for