Removechildren() in JTree

Hi All,
I want to remove all the children of a root node at runtime. How can i do this.
If i do :
System.out.println (defaultMutableTreeNode.getChildCount();
defaultMutableTreeNode.removeAllChildren();
System.out.println (defaultMutableTreeNode.getChildCount();
It prints out :
3 (Originaly tree childs)
0 (no childs)
but i still see them in the JTree at runtime.
I heard that one should use the DefaultTreeModel
Does anybody have an example of how to use this ?
or does anybody know another way ?
(withoud using a loop to remove the nodes one by one !).
Thanx in advance !!
Ronald

after removing the children I think you should call:
DefaultTreeModel m = (DefaultTreeModel)jtree.getModel();
m.reload(defaultMutableTreeNode);

Similar Messages

  • Checkbox with JTree

    hai,
    i added checkbox to each tree node and my coding is
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.KeyStroke;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    /** Provides checkbox-based selection of tree nodes. Override the protected
    * methods to adapt this renderer's behavior to your local tree table flavor.
    * No change listener notifications are provided.
    public class CheckBoxTreeCellRenderer implements TreeCellRenderer {
    public static final int UNSELECTABLE = 0;
    public static final int FULLSELECTED = 1;
    public static final int NOTSELECTED = 2;
    public static final int PARTIALSELECTED = 3;
    private TreeCellRenderer renderer;
    public static JCheckBox checkBox;
    private Point mouseLocation;
    private int mouseRow = -1;
    private int pressedRow = -1;
    private boolean mouseInCheck;
    private int state = NOTSELECTED;
    private Set checkedPaths;
    private JTree tree;
    private MouseHandler handler;
    /** Create a per-tree instance of the checkbox renderer. */
    public CheckBoxTreeCellRenderer(JTree tree, TreeCellRenderer original) {
    this.tree = tree;
    this.renderer = original;
    checkedPaths = new HashSet();
    checkBox = new JCheckBox();
    checkBox.setOpaque(false);
    System.out.println(checkBox.isSelected());
    checkBox.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              trace(checkBox);
    // ActionListener actionListener = new ActionListener() {
    // public void actionPerformed(ActionEvent actionEvent) {
    // AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
    // boolean selected = abstractButton.getModel().isSelected();
    // System.out.println(selected);
    // // abstractButton.setText(newLabel);
    // checkBox.addActionListener(new ActionListener(){
    //               public void actionPerformed(ActionEvent actionEvent) {
    //                    Checkbox cb = actionEvent.getSource();
    //     boolean selected = abstractButton.getModel().isSelected();
    //     System.out.println(selected);
    checkBox.setSize(checkBox.getPreferredSize());
    private static void trace(JCheckBox cb) {
         if (cb.isSelected())
              System.out.println(cb.getText()+" is " + cb.isSelected());
         else
              System.out.println(cb.getText()+" is " + cb.isSelected());
    protected void installMouseHandler() {
    if (handler == null) {
    handler = new MouseHandler();
    addMouseHandler(handler);
    protected void addMouseHandler(MouseHandler handler) {
    tree.addMouseListener(handler);
    tree.addMouseMotionListener(handler);
    private void updateMouseLocation(Point newLoc) {
    if (mouseRow != -1) {
    repaint(mouseRow);
    mouseLocation = newLoc;
    if (mouseLocation != null) {
    mouseRow = getRow(newLoc);
    repaint(mouseRow);
    else {
    mouseRow = -1;
    if (mouseRow != -1 && mouseLocation != null) {
    Point mouseLoc = new Point(mouseLocation);
    Rectangle r = getRowBounds(mouseRow);
    if (r != null)
    mouseLoc.x -= r.x;
    mouseInCheck = isInCheckBox(mouseLoc);
    else {
    mouseInCheck = false;
    protected int getRow(Point p) {
    return tree.getRowForLocation(p.x, p.y);
    protected Rectangle getRowBounds(int row) {
    return tree.getRowBounds(row);
    protected TreePath getPathForRow(int row) {
    return tree.getPathForRow(row);
    protected int getRowForPath(TreePath path) {
    return tree.getRowForPath(path);
    public void repaint(Rectangle r) {
    tree.repaint(r);
    public void repaint() {
    tree.repaint();
    private void repaint(int row) {
    Rectangle r = getRowBounds(row);
    if (r != null)
    repaint(r);
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    installMouseHandler();
    TreePath path = getPathForRow(row);
    state = UNSELECTABLE;
    if (path != null) {
    if (isChecked(path)) {
    state = FULLSELECTED;
    else if (isPartiallyChecked(path)) {
    state = PARTIALSELECTED;
    else if (isSelectable(path)) {
    state = NOTSELECTED;
    checkBox.setSelected(state == FULLSELECTED);
    checkBox.getModel().setArmed(mouseRow == row && pressedRow == row && mouseInCheck);
    checkBox.getModel().setPressed(pressedRow == row && mouseInCheck);
    checkBox.getModel().setRollover(mouseRow == row && mouseInCheck);
    Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
    checkBox.setForeground(c.getForeground());
    if (c instanceof JLabel) {
    JLabel label = (JLabel)c;
    // Augment the icon to include the checkbox
    Icon customOpenIcon = new ImageIcon("browse.gif");
    label.setIcon(new CompoundIcon(label.getIcon()));
    return c;
    private boolean isInCheckBox(Point where) {
    Insets insets = tree.getInsets();
    int right = checkBox.getWidth();
    int left = 0;
    if (insets != null) {
    left += insets.left;
    right += insets.left;
    return where.x >= left && where.x < right;
    public boolean isExplicitlyChecked(TreePath path) {
    return checkedPaths.contains(path);
    /** Returns whether selecting the given path is allowed. The default
    * returns true. You should return false if the given path represents
    * a placeholder for a node that has not yet loaded, or anything else
    * that doesn't represent a normal, operable object in the tree.
    public boolean isSelectable(TreePath path) {
    return true;
    /** Returns whether the given path is currently checked. */
    public boolean isChecked(TreePath path) {
    if (isExplicitlyChecked(path)) {
    return true;
    else {
    if (path.getParentPath() != null) {
    return isChecked(path.getParentPath());
    else {
    return false;
    public boolean isPartiallyChecked(TreePath path) {
    Object node = path.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath childPath = path.pathByAddingChild(child);
    if (isChecked(childPath) || isPartiallyChecked(childPath)) {
    return true;
    return false;
    private boolean isFullyChecked(TreePath parent) {
    Object node = parent.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath childPath = parent.pathByAddingChild(child);
    if (!isExplicitlyChecked(childPath)) {
    return false;
    return true;
    public void toggleChecked(int row) {
    TreePath path = getPathForRow(row);
    boolean isChecked = isChecked(path);
    removeDescendants(path);
    if (!isChecked) {
    checkedPaths.add(path);
    setParent(path);
    repaint();
    private void setParent(TreePath path) {
    TreePath parent = path.getParentPath();
    if (parent != null) {
    if (isFullyChecked(parent)) {
    removeChildren(parent);
    checkedPaths.add(parent);
    } else {
    if (isChecked(parent)) {
    checkedPaths.remove(parent);
    addChildren(parent);
    checkedPaths.remove(path);
    setParent(parent);
    private void addChildren(TreePath parent) {
    Object node = parent.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath path = parent.pathByAddingChild(child);
    checkedPaths.add(path);
    private void removeChildren(TreePath parent) {
    for (Iterator i = checkedPaths.iterator(); i.hasNext();) {
    TreePath p = (TreePath) i.next();
    if (p.getParentPath() != null && parent.equals(p.getParentPath())) {
    i.remove();
    private void removeDescendants(TreePath ancestor) {
    for (Iterator i = checkedPaths.iterator(); i.hasNext();) {
    TreePath path = (TreePath) i.next();
    if (ancestor.isDescendant(path)) {
    i.remove();
    /** Returns all checked rows. */
    public int[] getCheckedRows() {
    TreePath[] paths = getCheckedPaths();
    int[] rows = new int[checkedPaths.size()];
    for (int i = 0; i < checkedPaths.size(); i++) {
    rows[i] = getRowForPath(paths);
    Arrays.sort(rows);
    return rows;
    /** Returns all checked paths. */
    public TreePath[] getCheckedPaths() {
    return (TreePath[]) checkedPaths.toArray(new TreePath[checkedPaths.size()]);
    protected class MouseHandler extends MouseAdapter implements MouseMotionListener {
    public void mouseEntered(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mouseExited(MouseEvent e) {
    updateMouseLocation(null);
    public void mouseMoved(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mouseDragged(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mousePressed(MouseEvent e) {
    pressedRow = e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK
    ? getRow(e.getPoint()) : -1;
    updateMouseLocation(e.getPoint());
    public void mouseReleased(MouseEvent e) {
    if (pressedRow != -1) {
    int row = getRow(e.getPoint());
    if (row == pressedRow) {
    Point p = e.getPoint();
    Rectangle r = getRowBounds(row);
    p.x -= r.x;
    if (isInCheckBox(p)) {
    toggleChecked(row);
    pressedRow = -1;
    updateMouseLocation(e.getPoint());
    public void mouseClicked(MouseEvent e){
         if(checkBox.isSelected()){
              System.out.println(checkBox.getName());
    /** Combine a JCheckBox's checkbox with another icon. */
    private final class CompoundIcon implements Icon {
    private final Icon icon;
    private final int w;
    private final int h;
    private CompoundIcon(Icon icon) {
    if (icon == null) {
    icon = new Icon() {
    public int getIconHeight() { return 0; }
    public int getIconWidth() { return 0; }
    public void paintIcon(Component c, Graphics g, int x, int y) { }
    this.icon = icon;
    this.w = icon.getIconWidth();
    this.h = icon.getIconHeight();
    public int getIconWidth() {
    return checkBox.getPreferredSize().width + w;
    public int getIconHeight() {
    return Math.max(checkBox.getPreferredSize().height, h);
    public void paintIcon(Component c, Graphics g, int x, int y) {
    if (c.getComponentOrientation().isLeftToRight()) {
    int xoffset = checkBox.getPreferredSize().width;
    int yoffset = (getIconHeight()-icon.getIconHeight())/2;
    icon.paintIcon(c, g, x + xoffset, y + yoffset);
    if (state != UNSELECTABLE) {
    paintCheckBox(g, x, y);
    else {
    int yoffset = (getIconHeight()-icon.getIconHeight())/2;
    icon.paintIcon(c, g, x, y + yoffset);
    if (state != UNSELECTABLE) {
    paintCheckBox(g, x + icon.getIconWidth(), y);
    private void paintCheckBox(Graphics g, int x, int y) {
    int yoffset;
    boolean db = checkBox.isDoubleBuffered();
    checkBox.setDoubleBuffered(false);
    try {
    yoffset = (getIconHeight()-checkBox.getPreferredSize().height)/2;
    g = g.create(x, y+yoffset, getIconWidth(), getIconHeight());
    checkBox.paint(g);
    if (state == PARTIALSELECTED) {
    final int WIDTH = 2;
    g.setColor(UIManager.getColor("CheckBox.foreground"));
    Graphics2D g2d = (Graphics2D)g;
    g2d.setStroke(new BasicStroke(WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int w = checkBox.getWidth();
    int h = checkBox.getHeight();
    g.drawLine(w/4+2, h/2-WIDTH/2+1, w/4+w/2-3, h/2-WIDTH/2+1);
    g.dispose();
    finally {
    checkBox.setDoubleBuffered(db);
    private static String createText(TreePath[] paths) {
    if (paths.length == 0) {
    return "Nothing checked";
    String checked = "Checked:\n";
    for (int i=0;i < paths.length;i++) {
    checked += paths[i] + "\n";
    return checked;
    public static void main(String[] args) {
    try {
    final String SWITCH = "toggle-componentOrientation";
    try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e1) {
                   e1.printStackTrace();
              } catch (InstantiationException e1) {
                   e1.printStackTrace();
              } catch (IllegalAccessException e1) {
                   e1.printStackTrace();
              } catch (UnsupportedLookAndFeelException e1) {
                   e1.printStackTrace();
    JFrame frame = new JFrame("Tree with Check Boxes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final DefaultMutableTreeNode a = new DefaultMutableTreeNode("Node 1");
    for(int i =0 ; i<3; i++ ){
         DefaultMutableTreeNode b = new DefaultMutableTreeNode("ChildNode "+i);
         a.add(b);
    DefaultMutableTreeNode e = new DefaultMutableTreeNode("Node 2");
    for(int i =0 ; i<3; i++ ){
         DefaultMutableTreeNode f = new DefaultMutableTreeNode("ChildNode "+i);
         e.add(f);
    DefaultMutableTreeNode al = new DefaultMutableTreeNode("Sample");
    al.add(a);
    al.add(e);
    final JTree tree = new JTree(al);
    final CheckBoxTreeCellRenderer r =
    new CheckBoxTreeCellRenderer(tree, tree.getCellRenderer());
    tree.setCellRenderer(r);
    int rc = tree.getRowCount();
    tree.getActionMap().put(SWITCH, new AbstractAction(SWITCH) {
    public void actionPerformed(ActionEvent e) {
    ComponentOrientation o = tree.getComponentOrientation();
    if (o.isLeftToRight()) {
    o = ComponentOrientation.RIGHT_TO_LEFT;
    else {
    o = ComponentOrientation.LEFT_TO_RIGHT;
    tree.setComponentOrientation(o);
    tree.repaint();
    int mask = InputEvent.SHIFT_MASK|Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_O, mask), SWITCH);
    final JTextArea text = new JTextArea(createText(r.getCheckedPaths()));
    text.setPreferredSize(new Dimension(200, 100));
    tree.addMouseListener(new MouseAdapter() {
    public void mouseReleased(MouseEvent e) {
    // Invoke later to ensure all mouse handling is completed
    SwingUtilities.invokeLater(new Runnable() { public void run() {
    text.setText(createText(r.getCheckedPaths()));
    JScrollPane pane = new JScrollPane(tree);
    frame.getContentPane().add(pane);
    // frame.getContentPane().add(new JScrollPane(text), BorderLayout.SOUTH);
    frame.pack();
    frame.setSize(600,400);
    frame.setVisible(true);
    catch(Exception e) {
    e.printStackTrace();
    System.exit(1);
    now i need to get nodes names which has been selected, how can i do this
    can anyone help me ...
    regards,
    shobi

    Also, use code tags and post a SSCCE -- I'm sure more of your posted code is irrelevant to your question and few people are going to look at a code listing that long.
    [http://mindprod.com/jgloss/sscce.html]

  • Exist a Jtree node.id or something like this ?

    I would want to retrieve a node using a unique 'id', for example the absolute index (into the total nodes count)
    Is there something like this ?
    Can I add a particular property to a node ? ( for example this 'id' if it does not exist )
    Another question :
    If I want to implement a search code, this 'id' can be useful, or must I transverse the whole Jtree
    Thanks

    Hello.
    Do the following:
    1. Go to the Apple Menu at the top left of the screen
    2. Select Software Update...
    3. Install any updates that are found.
    If the Amazon issue continues after these updates, then do this:
    1. Open Safari
    2. Erase any web address you have currently showing (for example www.apple.com or www.google.com)
    3. Type in www.amazon.com
    4. That should take you directly to amazon.com
    It should look like this in your Safari::

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Expanding a JTree Node on selection

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

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

  • Rename a Jtree node directly & Popup Menu

    Pls assist with codes to rename a Jree node directly without using a dialog box or optionpane. I tried
    tree.startEditingAtPath(/* path of selected node*/);
    to go to edit mode and it does not work.
    II. Is it possible to attach different popmenu to the root, separate from the parent and child? Pls assist with code as the popupmenu i use at the moment shows up on the nodes(root, parent, leaf).
    I have benefiited greatly from questions asked and answers proferred at this forum and I use this opportunity to thank everyone greatly as I have migrated to Java based on all the materials sourced on the net.
    [email protected]

    public class AutomatedTreeMouseHandler extends MouseAdapter {
         public void mousePressed(MouseEvent e) {
              JTree tree = (JTree) (e.getSource());
              int x = e.getX();
              int y = e.getY();
              TreePath path = tree.getPathForLocation(x, y);
              if (path != null) {
                   // generate your popup here
    Dennis,
    are you saying that i have to define the popmenu for each category of node in the mouseadapter and att'd these to the tree depending on whether root, leaf or whatever type of node is selected?
    I will try this and revert.
    I can not make anything out of the reference giving with regard to renaming a node in edit mode.
    Pls provide more explanation and sample code, if necessary.
    Thanks a million.

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Problem in Jtree while retrieving values from a hashtable

    Hi
    I am trying to show some values in a Jtree.I am receiving the values in a hashtable.The hashtable contains unique key but duplicate values.i want to show that values of that hashtable in a tree(but unique values)and under each value show all the key of it.can you please tell me how to do that.
    thanks

    If i understand right, you want to do something like this:
                   Hashtable values = yourhashtable;        
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("Values");
              HashMap<Object, DefaultMutableTreeNode> nodes = new HashMap<Object, DefaultMutableTreeNode>();
              Iterator ii = values.keySet().iterator();
              while (ii.hasNext()) {
                   Object key = ii.next();
                   Object value = values.get(key);
                   if (nodes.containsKey(value)) {
                        DefaultMutableTreeNode node = nodes.get(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                   } else {
                        DefaultMutableTreeNode node = new DefaultMutableTreeNode(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                        nodes.put(value, node);
                        root.add(node);
              JTree tree = new JTree(root);Hope this helps,
    Alex.

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • Problem with JTree

    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
        private TreePanel treePanel;
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (treePanel = new TreePanel ());
            getContentPane ().add (new SearchPanel (), BorderLayout.SOUTH);
            pack ();
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public Dimension getPreferredSize () {
            return new Dimension (600, 600);
        private class TreePanel extends JPanel {
            private DefaultTreeModel model;
            private JTree tree;
            public TreePanel () {
                model = new DefaultTreeModel (createRoot ());
                tree = new JTree (model);
                tree.setRootVisible (false);
                tree.setShowsRootHandles (true);
                setLayout (new BorderLayout ());
                add (new JScrollPane (tree));
            private TreeNode createRoot () {
                DefaultMutableTreeNode root = new DefaultMutableTreeNode ("");
                add (root, 1, 3);
                return root;
            private void add (DefaultMutableTreeNode node, int i, int n) {
                for (int l = 0; l < 26; l ++) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode (((String) node.getUserObject ()) + (char) ('a' + l));
                    if (i < n) {
                        add (child, i + 1, n);
                    node.add (child);
            public void searchAndExpand (String text) {
                TreeNode[] path = search ((DefaultMutableTreeNode) model.getRoot (), text);
                if (path != null) {
                    TreePath treePath = new TreePath (path);
                    tree.scrollPathToVisible (treePath);
                    tree.setSelectionPath (treePath);
            private TreeNode[] search (DefaultMutableTreeNode node, Object object) {
                TreeNode[] path = null;
                if (node.getUserObject ().equals (object)) {
                    path = model.getPathToRoot (node);
                } else {
                    int i = 0;
                    int n = model.getChildCount (node);
                    while ((i < n) && (path == null)) {
                        path = search ((DefaultMutableTreeNode) model.getChild (node, i), object);
                        i ++;
                return path;
        private class SearchPanel extends JPanel {
            public SearchPanel () {
                JTextField searchField = new JTextField (10);
                searchField.addActionListener (new ActionListener () {
                    public void actionPerformed (ActionEvent event) {
                        treePanel.searchAndExpand (((JTextField) event.getSource ()).getText ());
                setLayout (new GridBagLayout ());
                add (searchField, new GridBagConstraints ());
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

  • Problem with Jtree to xml tranform..how to set/get parent of a node?

    Hi,
    I am trying to develop xml import/export module.In import wizard, I am parsing the xml file and the display it in Jtree view using xml tree model which implements TreeModel and xml tree node.I am using jaxp api..
    It is workin fine.
    I got stuck with removal of selected node and save it as a new xml.
    I am not able to get parent node of selected node in remove process,itz throwing null.I think i missed to define parent when i load treemodel.Plz help me out..give some ideas to do it..
    thanks
    -bala
    Edited by: r_bala on May 9, 2008 4:44 AM

    there's no way anyone can help you without seeing your code.

  • Problem with JTree while expanding/collapsing a node

    Hi,
    I'm using a JTree for displaying the file system.
    Here, i want that whenever a node get expanded,
    it should show the latest files/directories under that node.
    Now, what i'm doing is, getting all the files/dir's using files.listFiles(),
    under that node and then creating a new node and adding it to parent (all in expand() method).
    But, now the problem is, while doing this whenever the parent node get expanded its adding all the latest files/dirs into the previous instance
    resulting the same file/dir is displaying twice,thrice.. and so on, as that node is expanded and collapsed.
    i tried removeAllChildren() in collapse() method but then that node is notexpanding at all .
    Can anybody help me please...
    i got stuck b'coz of this only.
    Thanks...

    Now what i'm doing is every time expand() get called,
    i'm comparing all the children of that node in the
    current instance with all the children present in the
    file system (because there is a possibility that some
    file/dir may be added or deleted)
    is this the right wy or not?it certainly is not wrong, but as usual, there is more than 1 way to implement this...
    b'coz right now i'm getting all the files/dirs that
    are newly added but facing some problem if somebody
    deletes a file/dir.
    i'm still trying to get the solutionthen you should not just compare all the children of the node with the files/dirs but also the other way round. compare the files/dirs with the children to determine if the file/dir still exists and if not remove the node.
    or you could check if the file which a node represents exists and if not remove the node.
    thomas

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Problem with jtree selection

    Hi all,
    I've got a JTree that represents a sort of data that I'm going to change dynamically in my application. I'd like to reset the selection of the user to the leaf she has selected before the change to the tree structure.
    First of all my tree uses DefaultMutableTreeNode to build each node, and each DefaultMutableTreeNode contains a SingleKeyValue object, that is a key-value object (two strings) and that has an hashcode defined as follows:
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         public int hashCode() {
              return this.key.hashCode();
         I hope the hashcode can help me finding the right object even when its value changes (but the key is the same). The construction of the tree is the following:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("The root");
    // iterate and build each node
    SingleKeyValue object = new SingleKeyValue("key","value");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(object);
    root.add(node);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree  tree = new JTree(model);             
                so the tree is associated to a DefaultTreeModel. Then, when I need to change something in the tree I rebuild the tree and all leafs (with the SingleKeyValues) and rebuild the model:
              TreeModel treeModel = this.myTree.getModel();
              TreeSelectionModel selectionModel = this.myTree.getSelectionModel();
              DefaultTreeModel defaultTreeModel = null;
              DefaultTreeSelectionModel defaultTreeSelectionModel = null;
              TreePath selectedPath = null;
              TreeNode root = null;
              Logger.info("SimpleTreePanel.refreshDatabaseView: treemodel "+treeModel + " selectionModel " + selectionModel);
              if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
                   defaultTreeModel = (DefaultTreeModel) treeModel;
                   root = this.getRoot();
                   // get the selection
                   if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                        defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                        selectedPath = defaultTreeSelectionModel.getSelectionPath();
                        Logger.warn("Selection path of the tree: "+selectedPath);
                   // rebuild the tree
                   defaultTreeModel.setRoot(root);
                   // set the selected element
                   defaultTreeSelectionModel.setSelectionPath(selectedPath);The problem is that after the above code the tree is all closed, no leaf are selected. I guess the problem is with the SingleKeyValueObject because I've tried the default model and it works with, for example, simple strings. Any idea about?
    Thanks,
    Luca

    Here's a complete test program that creates a few SingleKeyValue objetcs (objects with a key and a description) and that then places them into a JTree using the DefaultMutableTreeNode. After that, the selection of user is took and one node is changed, but while the selection is working, the reload/refresh of the tree is not.
    Any idea about how to work on it?
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         // constants related to the type of the table this object refers to
         public static final String COMPETENCE = "competenza";
         public static final String FAMILY            = "famiglia_competenza";
         public static final String ROLE              = "ruolo";
         public static final String PROVINCE      = "provincia";
         public static final String KNOWLEDGE  = "titolo_studio";
         public final static String OBJECTIVE      = "obiettivo";
         public final static String PERSON         = "persona";
         public SingleKeyValue( String key, String value, String table){
              super();
              this.key = key;
              this.value = value;
              this.SQLTable = table;
          * @return the key
         public final String getKey() {
              return key;
          * @param key the key to set
         public final void setKey(String key) {
              this.key = key;
          * @return the value
         public final String getValue() {
              return value;
          * @param value the value to set
         public final void setValue(String value) {
              this.value = value;
          * Shows this element.
         public String toString(){
              String ret;
              if( this.showKey ){
                   ret =  this.label + this.key +" { "+ this.value +" }";
              else
                   ret = this.label + this.value;
              // trim the string
              if( ret.length() > this.maxLength )
                   return ret.substring(0 , this.maxLength);
              else
                   return ret;
          * The hash code of this object is the hash code of the key.
          * @return the hash code of the key of the object
         public int hashCode() {
              return this.key.hashCode();
          * Returns true if the object passed is a single key value equals (i.e., with the same key) of this one.
         public boolean equals(Object o){
              if( o== null || (! (o instanceof SingleKeyValue) ) )     return false;
              else
                   return (this.hashCode() == o.hashCode());
         public static void main(String argv[]) throws Exception{
             SingleKeyValue skv1 = new SingleKeyValue("Key1","Description1", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv2 = new SingleKeyValue("Key1a","Description1a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv3 = new SingleKeyValue("Key1b","Description1b", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv4 = new SingleKeyValue("Key2","Description2", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv5 = new SingleKeyValue("Key2a","Description2a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv6 = new SingleKeyValue("Key2b","Description2b", SingleKeyValue.COMPETENCE);
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
             DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(skv1);
             DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(skv2);
             DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(skv3);
             DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(skv4);
             DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(skv5);
             DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(skv6);
             rootNode.add(node1);
             node1.add(node2);
             node1.add(node3);
             rootNode.add(node4);
             node4.add(node5);
             node4.add(node6);
             JTree tree = new JTree(rootNode);
             JFrame f = new JFrame("Tree try");
             f.add( new JScrollPane(tree) );
             f.setSize(300,300);
             f.setVisible(true);
             System.out.println("Please select a node within 10 seconds");
             Thread.sleep(10000);
             // now get the user selection
         TreeModel treeModel = tree.getModel();
         TreeSelectionModel selectionModel = tree.getSelectionModel();
         DefaultTreeModel defaultTreeModel = null;
         DefaultTreeSelectionModel defaultTreeSelectionModel = null;
         TreePath selectedPath = null;
         TreeNode root = null;
         if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
              defaultTreeModel = (DefaultTreeModel) treeModel;
              // get the selection
              if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                   defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                   selectedPath = defaultTreeSelectionModel.getSelectionPath();
              // rebuild the tree
              node1.setUserObject(new SingleKeyValue("key20","key changed",SingleKeyValue.FAMILY));
              defaultTreeModel.reload();
              // set the selected element
              defaultTreeSelectionModel.setSelectionPath(selectedPath);
    }

  • Problem with JTree.isExpanded()

    Working with a JTree, I encountered into a strange behavior - I hope someone could explain me...
    For exporting a tree I need the information whether nodes are expanded or not.
    The first strange thing is that the root always seems to be collapsed - but this I can handle somehow.
    The problem is, that a expanded node containing a leaf, is reported as collapsed - but it is not. Why?
    Here the output of a expand-checking method, which prints the state of the node and its parents.
    (the "+" indicates a expanded node, the "-" indicated a collapsed node)
    + - Abasdf
    + - EP/asdf
    + - - Prosadf
    + - - - Altasdf
    + - - - - V1sadf
    + - - - - - 059asdf
    + - - - - - - 059asdf
    + - - - - - - + 059asdf
    + - - - - - - + + this_is_a_leafWhy is the expanded node containing the leaf reported as collapsed?
    I'm using the following for checking if a node is expanded:
    view.isExpanded(node.getIndex())I also tried this - with the same wrong result:
    view.isExpanded(view.getPathForRow(node.getIndex()))Any hint is highly appretiated.

    I was not able to reproduce your problemimport javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.util.Random;
    import java.util.Enumeration;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class HamsterChipsyTest extends JPanel {
         private static final Random RANDOM = new Random(System.currentTimeMillis());
         private JTree theTree;
         private DefaultTreeModel theTreeModel;
         private DefaultMutableTreeNode theRoot;
         public HamsterChipsyTest() {
              super(new BorderLayout());
              theRoot = createRandomNode();
              addNodes(theRoot, 0, 2);
              theTreeModel = new DefaultTreeModel(theRoot);
              theTree = new JTree(theTreeModel);
              add(new JScrollPane(theTree), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("dump nodes' extension state") {
                   public void actionPerformed(ActionEvent e) {
                        dumpExtensionState(theRoot);
              }), BorderLayout.NORTH);
         private void dumpExtensionState(DefaultMutableTreeNode aTreeNode) {
              TreeNode[] path = aTreeNode.getPath();
              for (int i = 0; i < path.length; i++) {
                   System.out.print('-');
              System.out.println(" " + aTreeNode.getUserObject().toString() + " " + theTree.isExpanded(new TreePath(path)));
              Enumeration children  = aTreeNode.children();
              while(children.hasMoreElements()) {
                   DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
                   dumpExtensionState(child);
         private static void addNodes(DefaultMutableTreeNode aParent, int aCurrentDepth, int aMaxDepth) {
              if (aCurrentDepth >= aMaxDepth) return;
              int nodeCount = RANDOM.nextInt(3);
              for (int i = 0; i < nodeCount + 1; i++) {
                   DefaultMutableTreeNode child = createRandomNode();
                   aParent.add(child);
                   addNodes(child, aCurrentDepth + 1, aMaxDepth);
         private static DefaultMutableTreeNode createRandomNode() {
              char[] chars = new char[5];
              for (int i = 0; i < chars.length; i++) {
                   chars[i] = (char)('a' + RANDOM.nextInt(26));
              return new DefaultMutableTreeNode(new String(chars));
         public static void main(String[] args) {
              final JFrame frame = new JFrame(HamsterChipsyTest.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new HamsterChipsyTest());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }

Maybe you are looking for