Inserting a JTextField in a JTree as a child

Hi ..
Is it possible to insert a JTextField in a JTree as a child... this is because i want edit the names assigned to children in a JTree at runtime..?
If yes could you please tell me how or refer me to any resources indictating how this is done...
Thanks in anticipation
Sandro

I'm heading out now so I'm not able to go in and test in order to get specific examples for you but you should be able to set the individual cells in the JTree as editable. This should give you the functionality you're looking for.
At the very least, swing is broken into MVC (model, view, control) architecture so you might need to find the class responsible for the tree's view and change a method there that allows the tree cells to be editable.
Specificly, try something like
JTree myTree = new JTree();
myTree.setEditable( true );
if that doesn't work, try looking into the TreeCellRenderer (the class that handles drawing the tree) and overwriting the interface method it contains (interface should only contain one method) so that the component it returns is editable. You would then have to use your TreeCellRenderer as the renderer for the tree.
public class MyCustomTreeCellRenderer extends DefaultTreeCellRenderer{
    public Component getTreeCellRendererComponent( parameters ){
        return super.getTreeCellRendererComponent( parameters ).setEditable( true );
}//end of inner class
myTree.setCellRenderer( new MyCustomTreeCellRenderer );
You can further change how your CellRenderer works if you need to implement more complex changes. What I've given you here should give you the basis for what you want to do.
Hope this helps.
- Kevin

Similar Messages

  • [JTree performance] 4000 childs under 1 parent

    I have a database table which holds a recursive self-reference. To display the contents, I use a self-bound tree model for a JTree (obiviously).
    Now, when one node is expanded for the first time, it attempts to load all 4000 child-nodes. So far, it's taking forever to complete.
    Even though I personally think it cannot be done, I'm still going to ask: Is there anything that can be done to somehow improve performance?

    Hello Steve,
    I've been digging through that article, but I'm still unsure what to do.
    Should I disable spill over? Or should I do something else?
    I tried the following, but nothing seemed to work (ie. provide better performance):
    - setting setForwardOnly(true) on the tree's "top VO"
    - setting the property forwardOnly = true on that VO's definition
    - setting the property jbo.pers.max.active.nodes = -1 on that VO's definition
    - setting setForwardOnly(true) on any of the tree's top VO's detail rowsets, but there were actually none (as in, no generated children either), so that didn't do anything
    I understand that changing some settings on the treetop VO is actually not the way to go, since that VO usually contains only a single node (in the context of my application anyway) and thus has the least influence on performance of the tree.
    I'll also admit that my understanding of the JClient tree binding may be somewhat limited.. Am I correct when I say that the 'body VO' (in the context of a recursive model) is generated? But based on what definition? And when is it generated and 'installed'? I think I need this info because I think I should set forwardOnly on that particular VO, but at the moment I can't seem to get a hold on it.
    A little note: I have defined no detail VO's of the treetop VO myself.
    So, what's left for me to try?

  • Insert node in JTree

    Hi!
    I have a JTree created and I need to insert a node in the JTree at a particular path that the use wants. I read the path and the node to be added as a string from the user:
    //Read path and node name
    String path = JOptionPane.showInputDialog (this, "Enter new node path");
    File f = new File (path);
    //Create new child
    DefaultMutableTreeNode child = new DefaultMutableTreeNode (f.getName());
    DefaultMutableTreeNode parent = new DefaultMutableTreeNode (f.getParent());
    //Get model and add new node
    DefaultTreeModel model = (DefaultTreeModel)jTree1.getModel();
    model.insertNodeInto (child, parent, parent.getChildCount());
    child.setParent(parent);
    jTree1.scrollPathToVisible(new TreePath(child.getPath()));
    model.reload();
    But, the new node is not showing up.
    Kindly help,
    x86

    Not pretty, but should give you the idea.import java.awt.event.*;
    import java.awt.*;
    import javax.swing.tree.*;
    import javax.swing.*;
    import java.io.File;
    import java.util.Stack;
    public class Test extends JFrame implements ActionListener {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode();
      JTree jt = new JTree(root);
      File f = new File("C:\\temp\\foo\\bar\\foo.txt");
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        jt.setRootVisible(false);
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        JButton jb = new JButton("Add");
        content.add(jb,BorderLayout.SOUTH);
        jb.addActionListener(this);
        setSize(300,300);
        show();
      public static void main(String args[]) { new Test(); }
      public void actionPerformed(ActionEvent ae) {
        Stack s = new Stack();
        File p = (File)s.push(f);
        while (p.getParent()!=null) p=(File)s.push(p.getParentFile());
        DefaultMutableTreeNode current = root, tmp;
        while (!s.isEmpty()) {
          p=(File)s.pop();
          boolean found=false;
          for (int i=0; i<current.getChildCount(); i++) {
            if (current.getChildAt(i).equals(p)) {
             found=true;
             current=(DefaultMutableTreeNode)current.getChildAt(i);
          if (!found) {
            tmp = new DefaultMutableTreeNode(p);
            current.add(tmp);
            current = tmp;
        jt.updateUI();
    }

  • JTree with XML Content

    Hi Friends,
    I am trying to create a JTree whose data will come from a XML Document. Whenever the tree is refreshed (There is a JPopupMenu on the tree which allows the user to call refresh), the tree must update itself with the underlying XML document. If there is any change in the xml doc, it must be reflected in the tree. However, the tree must not collapse when the refresh is called. For example if I have a tree like this:-
    + Root
        |
        ------ Child #1
        |            |
        |            -------- A
        |            |
        |            -------- B
        |
        +------ Child #2
        |
        ------- Child #3
                    |
                    -------- AAA
                    |
                    -------- BBBThe XML Document for the above tree structure would be:-
    <?xml version="1.0" encoding="UTF-8"?>
    <Root>Root
          <Child> Child #1
                <SubChild>A</SubChild>
                <SubChild>B</SubChild>
          </Child>
          <Child> Child #2
                <SubChild>AA</SubChild>
                <SubChild>BB</SubChild>
          </Child>
          <Child> Child #3
                <SubChild>AAA</SubChild>
                <SubChild>BBB</SubChild>
          </Child>
    </Root>Now if i add another node (CCC) in Child #3 (by adding another Subchild element in the XML document), and click refresh on the tree, the tree should look like:-
    + Root
        |
        ------ Child #1
        |            |
        |            -------- A
        |            |
        |            -------- B
        |
        +------ Child #2
        |
        ------- Child #3
                    |
                    -------- AAA
                    |
                    -------- BBB
                    |
                    -------- CCCHowever, if i am trying to reload the tree model, after reading the XML file, the whole tree collapses.
    Can anyone please help me out with this problem?
    Thanx a lot in advance,
    ~Debopam

    * XMLNode.java
    * Created on December 18, 2004, 4:25 PM
    package debopam.utils.xml;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.Vector;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreeNode;
    import org.jdom.Element;
    * @author Debopam Ghoshal
    public class XMLNode implements MutableTreeNode
        private Element nodeElement;
        private XMLNode parent;
        /** optional user object */
        transient protected Object     userObject;
        /** true if the node is able to have children */
        protected boolean allowsChildren;
        /** array of children, may be null if this node has no children */
        protected Vector children;
         * An enumeration that is always empty. This is used when an enumeration
         * of a leaf node's children is requested.
        static public final Enumeration<TreeNode> EMPTY_ENUMERATION
                = new Enumeration<TreeNode>()
            public boolean hasMoreElements()
            { return false; }
            public TreeNode nextElement()
                throw new NoSuchElementException("No more elements");
        /** Creates a new instance of XMLNode */
        public XMLNode(Element nodeElement, boolean allowsChildren)
            this.nodeElement = nodeElement;
            this.allowsChildren = allowsChildren;
        public XMLNode(String nodeName, boolean allowsChildren)
            nodeElement = new Element(nodeName);
            this.allowsChildren = allowsChildren;
         * Creates and returns a forward-order enumeration of this node's
         * children.  Modifying this node's child array invalidates any child
         * enumerations created before the modification.
         * @return     an Enumeration of this node's children
        public java.util.Enumeration children()
            if(children == null)
                return EMPTY_ENUMERATION;
            else
                return children.elements();
         * Returns true if this node is allowed to have children.
         * @return     true if this node allows children, else false
        public boolean getAllowsChildren()
            return allowsChildren;
         * Determines whether or not this node is allowed to have children.
         * If <code>allows</code> is false, all of this node's children are
         * removed.
         * <p>
         * Note: By default, a node allows children.
         * @param     allows     true if this node is allowed to have children
        public void setAllowsChildren(boolean allows)
            if (allows != allowsChildren)
                allowsChildren = allows;
                if (!allowsChildren)
                    removeAllChildren();
         * Returns the child at the specified index in this node's child array.
         * @param     index     an index into this node's child array
         * @exception     ArrayIndexOutOfBoundsException     if <code>index</code>
         *                              is out of bounds
         * @return     the TreeNode in this node's child array at  the specified index
        public javax.swing.tree.TreeNode getChildAt(int index)
            if (children == null)
                throw new ArrayIndexOutOfBoundsException("node has no children");
            return (TreeNode)children.elementAt(index);
         * Returns the number of children of this node.
         * @return     an int giving the number of children of this node
        public int getChildCount()
            if (children == null)
                return 0;
            else
                return children.size();
         * Returns the index of the specified child in this node's child array.
         * If the specified node is not a child of this node, returns
         * <code>-1</code>.  This method performs a linear search and is O(n)
         * where n is the number of children.
         * @param     aChild     the TreeNode to search for among this node's children
         * @exception     IllegalArgumentException     if <code>aChild</code>
         *                                   is null
         * @return     an int giving the index of the node in this node's child
         *          array, or <code>-1</code> if the specified node is a not
         *          a child of this node
        public int getIndex(TreeNode aChild)
            if (aChild == null)
                throw new IllegalArgumentException("argument is null");
            if (!isNodeChild(aChild))
                return -1;
            return children.indexOf(aChild);     // linear search
         * Returns this node's parent or null if this node has no parent.
         * @return     this node's parent TreeNode, or null if this node has no parent
        public TreeNode getParent()
            return parent;
         * Removes <code>newChild</code> from its present parent (if it has a
         * parent), sets the child's parent to this node, and then adds the child
         * to this node's child array at index <code>childIndex</code>.
         * <code>newChild</code> must not be null and must not be an ancestor of
         * this node.
         * @param     newChild     the MutableTreeNode to insert under this node
         * @param     childIndex     the index in this node's child array
         *                    where this node is to be inserted
         * @exception     ArrayIndexOutOfBoundsException     if
         *                    <code>childIndex</code> is out of bounds
         * @exception     IllegalArgumentException     if
         *                    <code>newChild</code> is null or is an
         *                    ancestor of this node
         * @exception     IllegalStateException     if this node does not allow
         *                              children
         * @see     #isNodeDescendant
        public void insert(MutableTreeNode newChild, int childIndex)
            if (!allowsChildren)
                throw new IllegalStateException("node does not allow children");
            else if (newChild == null)
                throw new IllegalArgumentException("new child is null");
            else if (isNodeAncestor(newChild))
                throw new IllegalArgumentException("new child is an ancestor");
            MutableTreeNode oldParent = (MutableTreeNode)newChild.getParent();
            if (oldParent != null)
                oldParent.remove(newChild);
            newChild.setParent(this);
            if (children == null)
                children = new Vector();
            children.insertElementAt(newChild, childIndex);
        public boolean isLeaf()
            return !nodeElement.hasChildren();
         * Removes the child at the specified index from this node's children
         * and sets that node's parent to null. The child node to remove
         * must be a <code>MutableTreeNode</code>.
         * @param     childIndex     the index in this node's child array
         *                    of the child to remove
         * @exception     ArrayIndexOutOfBoundsException     if
         *                    <code>childIndex</code> is out of bounds
        public void remove(int childIndex)
            MutableTreeNode child = (MutableTreeNode)getChildAt(childIndex);
            children.removeElementAt(childIndex);
            child.setParent(null);
         * Removes <code>aChild</code> from this node's child array, giving it a
         * null parent.
         * @param     aChild     a child of this node to remove
         * @exception     IllegalArgumentException     if <code>aChild</code>
         *                         is null or is not a child of this node
        public void remove(MutableTreeNode aChild)
            if (aChild == null)
                throw new IllegalArgumentException("argument is null");
            if (!isNodeChild(aChild))
                throw new IllegalArgumentException("argument is not a child");
            remove(getIndex(aChild));     // linear search
         * Removes the subtree rooted at this node from the tree, giving this
         * node a null parent.  Does nothing if this node is the root of its
         * tree.
        public void removeFromParent()
            MutableTreeNode parent = (MutableTreeNode)getParent();
            if (parent != null)
                parent.remove(this);
         * Sets this node's parent to <code>newParent</code> but does not
         * change the parent's child array.  This method is called from
         * <code>insert()</code> and <code>remove()</code> to
         * reassign a child's parent, it should not be messaged from anywhere
         * else.
         * @param     newParent     this node's new parent
        public void setParent(MutableTreeNode mutableTreeNode)
            this.parent = parent;
        public void setUserObject(Object obj)
            this.userObject = obj;
        public Element getXMLElement()
            return this.nodeElement;
        public String toString()
            return this.nodeElement.getTextTrim();
         * Returns true if <code>anotherNode</code> is an ancestor of this node
         * -- if it is this node, this node's parent, or an ancestor of this
         * node's parent.  (Note that a node is considered an ancestor of itself.)
         * If <code>anotherNode</code> is null, this method returns false.  This
         * operation is at worst O(h) where h is the distance from the root to
         * this node.
         * @see          #isNodeDescendant
         * @see          #getSharedAncestor
         * @param     anotherNode     node to test as an ancestor of this node
         * @return     true if this node is a descendant of <code>anotherNode</code>
        public boolean isNodeAncestor(TreeNode anotherNode)
            if (anotherNode == null)
                return false;
            TreeNode ancestor = this;
            do
                if (ancestor == anotherNode)
                    return true;
            } while((ancestor = ancestor.getParent()) != null);
            return false;
         * Returns true if <code>aNode</code> is a child of this node.  If
         * <code>aNode</code> is null, this method returns false.
         * @return     true if <code>aNode</code> is a child of this node; false if
         *            <code>aNode</code> is null
        public boolean isNodeChild(TreeNode aNode)
            boolean retval;
            if (aNode == null)
                retval = false;
            else
                if (getChildCount() == 0)
                    retval = false;
                else
                    retval = (aNode.getParent() == this);
            return retval;
         * Removes all of this node's children, setting their parents to null.
         * If this node has no children, this method does nothing.
        public void removeAllChildren()
            for (int i = getChildCount()-1; i >= 0; i--)
                remove(i);
         * Removes <code>newChild</code> from its parent and makes it a child of
         * this node by adding it to the end of this node's child array.
         * @see          #insert
         * @param     newChild     node to add as a child of this node
         * @exception     IllegalArgumentException    if <code>newChild</code>
         *                              is null
         * @exception     IllegalStateException     if this node does not allow
         *                              children
        public void add(MutableTreeNode newChild)
            if(newChild != null && newChild.getParent() == this)
                insert(newChild, getChildCount() - 1);
            else
                insert(newChild, getChildCount());
         * Indicates whether some other object is "equal to" this one.
         * @param   obj   the reference object with which to compare.
         * @return  <code>true</code> if this object is the same as the obj
         *          argument; <code>false</code> otherwise.
        public boolean equals(XMLNode node)
            boolean retValue;
            retValue = (this.getXMLElement().getTextTrim().equals(node.getXMLElement().getTextTrim())) &&
                    (this.getXMLElement().getParent().getTextTrim().equals(node.getXMLElement().getParent().getTextTrim()));
            return retValue;
    * XMLTreeModel.java
    * Created on December 20, 2004, 11:29 AM
    package debopam.utils.xml;
    import java.io.File;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.EventListener;
    import java.util.List;
    import java.util.Vector;
    import javax.swing.event.EventListenerList;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    * @author Debopam Ghoshal
    public class XMLTreeModel implements TreeModel
        private XMLNode rootNode;
        private String xmlFileName;
        private Document xmlDocument;
        /** Listeners. */
        protected EventListenerList listenerList = new EventListenerList();
         * Determines how the <code>isLeaf</code> method figures
         * out if a node is a leaf node. If true, a node is a leaf
         * node if it does not allow children. (If it allows
         * children, it is not a leaf node, even if no children
         * are present.) That lets you distinguish between <i>folder</i>
         * nodes and <i>file</i> nodes in a file system, for example.
         * <p>
         * If this value is false, then any node which has no
         * children is a leaf node, and any node may acquire
         * children.
         * @see TreeNode#getAllowsChildren
         * @see TreeModel#isLeaf
         * @see #setAsksAllowsChildren
        protected boolean asksAllowsChildren;
        /** Creates a new instance of XMLTreeModel */
        public XMLTreeModel(String xmlFileName, boolean asksAllowsChildren)
            this.xmlFileName = xmlFileName;
            this.asksAllowsChildren = asksAllowsChildren;
            loadXMLDocument();
            rootNode = makeRootNode();
        public XMLTreeModel(String xmlFileName)
            this(xmlFileName, false);
        private void loadXMLDocument()
            System.out.println("loading xml document...");
            try
                this.xmlDocument = null;
                this.xmlDocument = new SAXBuilder().build(new File(xmlFileName));
            catch(Exception x)
                System.out.println("Error while loading XML Document.");
                x.printStackTrace();
        private XMLNode makeRootNode()
            XMLNode root = new XMLNode(xmlDocument.getRootElement(), true);
            addChildren(root, xmlDocument.getRootElement());
            return root;
        private void addChildren(XMLNode parentXMLNode, Element element)
            List children = element.getChildren();
            for(int i = 0; i < children.size(); i++)
                Element childElement = (Element)children.get(i);
                XMLNode childNode = new XMLNode(childElement, true);
                parentXMLNode.add(childNode);
                addChildren(childNode, childElement);
         * Sets whether or not to test leafness by asking getAllowsChildren()
         * or isLeaf() to the TreeNodes.  If newvalue is true, getAllowsChildren()
         * is messaged, otherwise isLeaf() is messaged.
        public void setAsksAllowsChildren(boolean newValue)
            asksAllowsChildren = newValue;
         * Tells how leaf nodes are determined.
         * @return true if only nodes which do not allow children are
         *         leaf nodes, false if nodes which have no children
         *         (even if allowed) are leaf nodes
         * @see #asksAllowsChildren
        public boolean asksAllowsChildren()
            return asksAllowsChildren;
         * Returns the child of <I>parent</I> at index <I>index</I> in the parent's
         * child array.  <I>parent</I> must be a node previously obtained from
         * this data source. This should not return null if <i>index</i>
         * is a valid index for <i>parent</i> (that is <i>index</i> >= 0 &&
         * <i>index</i> < getChildCount(<i>parent</i>)).
         * @param   parent  a node in the tree, obtained from this data source
         * @return  the child of <I>parent</I> at index <I>index</I>
        public Object getChild(Object parent, int index)
            return ((XMLNode)parent).getChildAt(index);
         * Returns the number of children of <I>parent</I>.  Returns 0 if the node
         * is a leaf or if it has no children.  <I>parent</I> must be a node
         * previously obtained from this data source.
         * @param   parent  a node in the tree, obtained from this data source
         * @return  the number of children of the node <I>parent</I>
        public int getChildCount(Object parent)
            return ((XMLNode)parent).getChildCount();
         * Returns the index of child in parent.
         * If either the parent or child is <code>null</code>, returns -1.
         * @param parent a note in the tree, obtained from this data source
         * @param child the node we are interested in
         * @return the index of the child in the parent, or -1
         *    if either the parent or the child is <code>null</code>
        public int getIndexOfChild(Object parent, Object child)
            if(parent == null || child == null)
                return -1;
            return ((XMLNode)parent).getIndex((XMLNode)child);
         * Sets the root to <code>root</code>. A null <code>root</code> implies
         * the tree is to display nothing, and is legal.
        public void setRoot(XMLNode rootNode)
            Object oldRoot = this.rootNode;
            this.rootNode = rootNode;
            if (rootNode == null && oldRoot != null)
                fireTreeStructureChanged(this, null);
            else
                nodeStructureChanged(rootNode);
         * Returns the root of the tree.  Returns null only if the tree has
         * no nodes.
         * @return  the root of the tree
        public Object getRoot()
            return rootNode;
         * Returns whether the specified node is a leaf node.
         * The way the test is performed depends on the
         * <code>askAllowsChildren</code> setting.
         * @param node the node to check
         * @return true if the node is a leaf node
         * @see #asksAllowsChildren
         * @see TreeModel#isLeaf
        public boolean isLeaf(Object node)
            if(asksAllowsChildren)
                return !((XMLNode)node).getAllowsChildren();
            return ((XMLNode)node).isLeaf();
         * This sets the user object of the TreeNode identified by path
         * and posts a node changed.  If you use custom user objects in
         * the TreeModel you're going to need to subclass this and
         * set the user object of the changed node to something meaningful.
        public void valueForPathChanged(TreePath path, Object newValue)
            XMLNode aNode = (XMLNode)path.getLastPathComponent();
            aNode.setUserObject(newValue);
            nodeChanged(aNode);
         * Invoked this to insert newChild at location index in parents children.
         * This will then message nodesWereInserted to create the appropriate
         * event. This is the preferred way to add children as it will create
         * the appropriate event.
        public void insertNodeInto(XMLNode newChild, XMLNode parent, int index)
            parent.insert(newChild, index);
            int[] newIndexs = new int[1];
            newIndexs[0] = index;
            nodesWereInserted(parent, newIndexs);
         * Message this to remove node from its parent. This will message
         * nodesWereRemoved to create the appropriate event. This is the
         * preferred way to remove a node as it handles the event creation
         * for you.
        public void removeNodeFromParent(XMLNode node)
            XMLNode parent = (XMLNode)node.getParent();
            if(parent == null)
                throw new IllegalArgumentException("node does not have a parent.");
            int[] childIndex = new int[1];
            Object[] removedArray = new Object[1];
            childIndex[0] = parent.getIndex(node);
            parent.remove(childIndex[0]);
            removedArray[0] = node;
            nodesWereRemoved(parent, childIndex, removedArray);
         * Invoke this method after you've changed how node is to be
         * represented in the tree.
        public void nodeChanged(XMLNode node)
            if(listenerList != null && node != null)
                XMLNode parent = (XMLNode)node.getParent();
                if(parent != null)
                    int        anIndex = parent.getIndex(node);
                    if(anIndex != -1)
                        int[] cIndexs = new int[1];
                        cIndexs[0] = anIndex;
                        nodesChanged(parent, cIndexs);
                else if (node == getRoot())
                    nodesChanged(node, null);
         * Invoke this method if you've modified the TreeNodes upon which this
         * model depends.  The model will notify all of its listeners that the
         * model has changed.
        public void reload()
            loadXMLDocument();
            XMLNode tempRootNode = makeRootNode();
            if(!tempRootNode.equals(rootNode))
                // Means that the root node itself has changed.
                System.out.println("Root node changed");
                reload(rootNode);
            //else
                checkForNodesChanged(tempRootNode, rootNode);
         * Invoke this method if you've modified the TreeNodes upon which this
         * model depends.  The model will notify all of its listeners that the
         * model has changed below the node <code>node</code> (PENDING).
        public void reload(XMLNode node)
            if(node != null)
                fireTreeStructureChanged(this, getPathToRoot(node), null, null);
         * Invoke this method after you've inserted some TreeNodes into
         * node.  childIndices should be the index of the new elements and
         * must be sorted in ascending order.
        public void nodesWereInserted(XMLNode node, int[] childIndices)
            if(listenerList != null && node != null && childIndices != null
                    && childIndices.length > 0)
                int               cCount = childIndices.length;
                Object[]          newChildren = new Object[cCount];
                for(int counter = 0; counter < cCount; counter++)
                    newChildren[counter] = node.getChildAt(childIndices[counter]);
                fireTreeNodesInserted(this, getPathToRoot(node), childIndices,
                        newChildren);
         * Invoke this method after you've removed some TreeNodes from
         * node.  childIndices should be the index of the removed elements and
         * must be sorted in ascending order. And removedChildren should be
         * the array of the children objects that were removed.
        public void nodesWereRemoved(XMLNode node, int[] childIndices,
                Object[] removedChildren)
            if(node != null && childIndices != null)
                fireTreeNodesRemoved(this, getPathToRoot(node), childIndices,
                        removedChildren);
         * Invoke this method after you've changed how the children identified by
         * childIndicies are to be represented in the tree.
        public void nodesChanged(XMLNode node, int[] childIndices)
            if(node != null)
                if (childIndices != null)
                    int cCount = childIndices.length;
                    if(cCount > 0)
                        Object[] cChildren = new Object[cCount];
                        for(int counter = 0; counter < cCount; counter++)
                            cChildren[counter] = node.getChildAt
                                    (childIndices[counter]);
                        fireTreeNodesChanged(this, getPathToRoot(node),
                                childIndices, cChildren);
                else if (node == getRoot())
                    fireTreeNodesChanged(this, getPathToRoot(node), null, null);
         * Invoke this method if you've totally changed the children of
         * node and its childrens children...  This will post a
         * treeStructureChanged event.
        public void nodeStructureChanged(XMLNode node)
            if(node != null)
                fireTreeStructureChanged(this, getPathToRoot(node), null, null);
         * Builds the parents of node up to and including the root node,
         * where the original node is the last element in the returned array.
         * The length of the returned array gives the node's depth in the
         * tree.
         * @param aNode the TreeNode to get the path for
        public XMLNode[] getPathToRoot(XMLNode aNode)
            return getPathToRoot(aNode, 0);
         * Builds the parents of node up to and including the root node,
         * where the original node is the last element in the returned array.
         * The length of the returned array gives the node's depth in the
         * tree.
         * @param aNode  the TreeNode to get the path for
         * @param depth  an int giving the number of steps already taken towards
         *        the root (on recursive calls), used to size the returned array
         * @return an array of TreeNodes giving the path from the root to the
         *         specified node
        protected XMLNode[] getPathToRoot(XMLNode aNode, int depth)
            XMLNode[] retNodes;
            // This method recurses, traversing towards the root in order
            // size the array. On the way back, it fills in the nodes,
            // starting from the root and working back to the original node.
            /* Check for null, in case someone passed in a null node, or
               they passed in an element that isn't rooted at root. */
            if(aNode == null)
                if(depth == 0)
                    return null;
                else
                    retNodes = new XMLNode[depth];
            else
                depth++;
                if(aNode == rootNode)
                    retNodes = new XMLNode[depth];
                else
                    retNodes = getPathToRoot((XMLNode)aNode.getParent(), depth);
                retNodes[retNodes.length - depth] = aNode;
            return retNodes;
        //  Events
         * Adds a listener for the TreeModelEvent posted after the tree changes.
         * @see     #removeTreeModelListener
         * @param   l       the listener to add
        public void addTreeModelListener(TreeModelListener l)
            listenerList.add(TreeModelListener.class, l);
         * Removes a listener previously added with <B>addTreeModelListener()</B>.
         * @see     #addTreeModelListener
         * @param   l       the listener to remove
        public void removeTreeModelListener(TreeModelListener l)
            listenerList.remove(TreeModelListener.class, l);
         * Returns an array of all the tree model listeners
         * registered on this model.
         * @return all of this model's <code>TreeModelListener</code>s
         *         or an empty
         *         array if no tree model listeners are currently registered
         * @see #addTreeModelListener
         * @see #removeTreeModelListener
         * @since 1.4
        public TreeModelListener[] getTreeModelListeners()
            return (TreeModelListener[])listenerList.getListeners(
                    TreeModelListener.class);
         * Notifies all listeners that have registered interest for
         * notification on this event type.  The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @param source the node being changed
         * @param path the path to the root node
         * @param childIndices the indices of the changed elements
         * @param children the changed elements
         * @see EventListenerList
        protected void fireTreeNodesChanged(Object source, Object[] path,
                int[] childIndices,
                Object[] children)
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            TreeModelEvent e = null;
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2)
                if (listeners==TreeModelListener.class)
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
    * Notifies all listeners that have registered interest for
    * notification on this event type. The event instance

  • Inserting issue while ruuning a DBUnit TestCase

    Hi all,
    Iam trying to run a sample program which inserts data in to two tables(master and Child ), while iam reading data from a flatxml file.
    Iam using MS SQLServer 2000 .
    The child table has a auto increment coloumn, now i need to explicitly override the column and add the data in to the column.when i try to run the testcase iam getting this exception.
    FaltXML File:
    <?xml version='1.0' encoding='UTF-8'?>
    <dataset>
    <ServiceRequest ID="2222226" Priority="1" Status="3" ReceiptMethod="2" RequestType="1" OperatingChannel="9" DeadlineDate="2001-03-10 00:00:00.0" IsEscalated="false" LastActionedBy="mapdev02" LastActionedDate="2005-02-28 00:00:00.0" CreationDate="2000-08-29 00:00:00.0" ClosedDate="2000-12-20 00:00:00.0" IsDuplicateCheckComplete="false"/>
    <Account ID="9999999" ServiceRequest="2222226" Number="12344565" ProductCode="SVC" SubProductCode="SHC" Status="PreApproval" ServicingBranchBSB="2001" ControllingPostID="A0010" ShortName="ANZ" OperatingChannel="2" LastChangeDate="2002-12-24 00:00:00.0"/>
    </dataset>
    Class File :
    package com.db.unitTest;
    import java.io.FileInputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import org.dbunit.DatabaseTestCase;
    import org.dbunit.database.AbstractDatabaseConnection;
    import org.dbunit.database.DatabaseConfig;
    import org.dbunit.database.DatabaseConnection;
    import org.dbunit.database.IDatabaseConnection;
    import org.dbunit.dataset.IDataSet;
    import org.dbunit.dataset.xml.FlatXmlDataSet;
    import org.dbunit.ext.mssql.InsertIdentityOperation;
    import org.dbunit.ext.mssql.MsSqlConnection;
    import org.dbunit.operation.DatabaseOperation;
    import org.dbunit.operation.TransactionOperation;
    public class SampleTest extends DatabaseTestCase {
         private FlatXmlDataSet loadedDataSet;
         protected IDatabaseConnection getConnection() throws Exception {
              System.out.println("==============getConnection()");
              Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection connection = DriverManager
              .getConnection(
         "jdbc:sqlserver://161.11.4.1:49168;DatabaseName=MAPDM;SelectMethod=cursor","mapUser", "map");
              MsSqlConnection msConnection = new MsSqlConnection(connection);
         return msConnection;
         protected IDataSet getDataSet() throws Exception {
              System.out.println("==============getDataSet()");
    loadedDataSet = new FlatXmlDataSet(new FileInputStream(".\\data\\input.xml"));
         return loadedDataSet;
         protected DatabaseOperation getSetUpOperation() throws Exception {
              System.out.println("==============getSetUpOperation()");
              InsertIdentityOperation.INSERT.execute(getConnection(),getDataSet());     
              return null;
         protected DatabaseOperation getTearDownOperation() throws Exception {
              System.out.println("==============getTearDownOperation()");
              return DatabaseOperation.DELETE;
         public void testCheckDataLoaded() throws Exception {
              System.out.println("==============testCheckDataLoaded()");
    }Please help.
    Cheers
    Jeevan
    com.microsoft.sqlserver.jdbc.SQLServerException: sp_cursoropen/sp_cursorprepare: The statement parameter can only be a single select or a single stored procedure.
         at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source)
         at com.microsoft.sqlserver.jdbc.IOBuffer.processPackets(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerStatement.sendExecute(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecute(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(Unknown Source)
         at org.dbunit.database.statement.SimplePreparedStatement.addBatch(SimplePreparedStatement.java:67)
         at org.dbunit.database.statement.AutomaticPreparedBatchStatement.addBatch(AutomaticPreparedBatchStatement.java:57)
         at org.dbunit.operation.AbstractBatchOperation.execute(AbstractBatchOperation.java:187)
         at org.dbunit.ext.mssql.InsertIdentityOperation.execute(InsertIdentityOperation.java:162)
         at com.db.unitTest.SampleTest.getSetUpOperation(SampleTest.java:66)
         at org.dbunit.DatabaseTestCase.setUp(DatabaseTestCase.java:118)
         at junit.framework.TestCase.runBare(TestCase.java:125)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at junit.framework.TestSuite.runTest(TestSuite.java:208)
         at junit.framework.TestSuite.run(TestSuite.java:203)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:421)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:305)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:186)

    Thanks Ranganath,
    Yes there is a problem in the PA30. employee is not enrolled in benefits so it is throughing me error.
    Thanks a lot
    Ravi

  • JTree custom components ... ?

    Hello
    I did some simple work with JTrees. But now I want to build a JTree where all childs of a given node are displayed horizontally.
    It should resemble the permissions a given user has on a given category. The categories are ordered in a tree. So I click a category and I'll see 4 Icons which are like 4 of that permission (read/write/add/delete).
    Since I do not have any idea how to pack 4 icons into one CellEditor or something like that I'd be happy for hints and advices how I could go on.
    Thank you very much.

    Hello (thanks for your reply)
    It is the first option: myFile 1234
    I was thinking that your suggestion is the way, but I'm having problems to really figure it out.
    So do you mean I first create a JPanel, set 4 Icons on it and deal with the model which is represented by the icons?
    And after initializing each of that panels with the data I create a DefaultMutableTreeNode with that?
    That's how I can figure it out roughly, not knowing if it's right anyway.
    If so, I can not imagine how I deal with the events from the tree itself down to the panel and its icons.
    I'd be glad for more clarification.
    Thank you.

  • Using threads (SwingWorker) to update JTree component

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

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

  • Refreshing JTable from JTree?

    Hello everyone,
    I've created a JTable using my own table model extending AbstractTableModel...
    I'm sending data to JTable as Vector through it's constructor...
    I have also created a JTree in another class... What i intend to achieve is this:
    Whenever i click on a node of the JTree, all the childs
    of that node should be displayed in the jtable...
    I have solved part of the problem by creating a new instance of JTable whenever the tree node is clicked... obtaining the names of all the childs in a Vector and sending it to the JTable...
    The problem with this approach is that a table row is only refreshed when it's clicked upon... or if i minimize and then maximize the app...
    Please tell me how to solve this problem... if you have any other comments on the approach i've used, please share it with me...
    Thanks

    Hope the folling code snippet will help.
    jTableModel.setDataVector(rowVector,tableColumnVector);
    //get the table model and pass it in setModel() method or use the global Modal object.
    jTable.setModel(jctableModel);
    tableModelEvent=new TableModelEvent(jctableModel);
    Thanks,
    Vikas Karwal
    [email protected]

  • Insertion using objects and update using queries in a single unit of work

    HI All,
    I have a set of objects that i want to insert and then perform some update queries ( direct queries ) on the inserted data in the same transaction. but when i register the objects and execute the update SQL's on the same data in a same unit of work, the update statements are executed first and then the inserts are happening, I've also tried with child unit of work and parent unit of work but the result is the same.
    Can any one suggest a way to do object insertion and sql updates in a single transaction, Thanks in advance
    Regards,
    Sai Krishna

    The UnitOfWork is an abstraction for the physical database query. By default nothing is actually written into the database until the UnitOfWork commits. This means making updates to new objects involves modifying them in-memory and then the updated values will be included in the INSERT during commit.
    If you are having difficulty finding the newly created objects you can enable the query conforming capabilities to have modified and new objects included in query comparisons without requiring them to first be written to the database.
    Doug

  • Unable to insert .flv Template Child Pages

    Unable to insert .flv Flash video in template pages
    When you attempt to insert a Flash Video file (.flv) into a
    child page created from a Dreamweaver template, you see the
    following error message: "Making this change would require changing
    code that is locked by a template or a translator. The change will
    be discarded."
    The Adobe recommended solution: “ 1. Make a parent
    template page that already contains the Flash Player detection
    code. 2. Insert the Flash Video into the child page created from
    the template, without the Flash Player detection code. To do this,
    uncheck the "Prompt users to download Flash Player if necessary"
    checkbox in the Insert Flash Video dialog box.”
    This solution does not work. It doesn’t work because
    the checkbox is grayed out - it is impossible to “…
    uncheck the "Prompt users to download Flash Player … checkbox
    What Can I do?
    I want to uncheck that grayed out “Prompt” box.
    How can I do that?

    I am unable to duplicate what you are describing.
    When you go to insert the flv, you Insert/Media/Flash
    Video... and the box
    is grayed out?
    The unchecking of the box solves the problem, why yours is
    doing that I dont
    understand. I assume you are in an editable region in the
    child?
    Gary
    "AdCracker.com" <[email protected]> wrote in message
    news:gdiuj0$86g$[email protected]..
    > Unable to insert .flv Flash video in template pages
    >
    > When you attempt to insert a Flash Video file (.flv)
    into a child page
    > created
    > from a Dreamweaver template, you see the following error
    message: "Making
    > this
    > change would require changing code that is locked by a
    template or a
    > translator. The change will be discarded."
    >
    > The Adobe recommended solution: ? 1. Make a parent
    template page that
    > already
    > contains the Flash Player detection code. 2. Insert the
    Flash Video into
    > the
    > child page created from the template, without the Flash
    Player detection
    > code.
    > To do this, uncheck the "Prompt users to download Flash
    Player if
    > necessary"
    > checkbox in the Insert Flash Video dialog box.?
    >
    > This solution does not work. It doesn?t work because the
    checkbox is
    > grayed
    > out - it is impossible to ?? uncheck the "Prompt users
    to download Flash
    > Player
    > ? checkbox ?
    >
    > What Can I do?
    >
    > I want to uncheck that grayed out ?Prompt? box. How can
    I do that?
    >
    >

  • Insert unsharable because of INST_DRTLD_MISMATCH

    Hi,
    I've got like 2000 insert statements in shared pool that despite of bind variables usage are not sharable:
    INSERT INTO tmpagreement
                (no, indicator, customerno, isrid, source_system
         VALUES (:b5, :b4, LTRIM (:b3), :b2, :b1
                );after checking v$sql_shared_cursor
    I've got 'Y' for INST_DRTLD_MISMATCH - which is 'Insert direct load does not match the existing child cursor' .
    That's strange to me because there is no direct load here .
    One more think is that query comes via dblink (got remote = y in v$sql) I'm
    not sure if that matters.
    DB is 9.2.0.8 .
    Any ideas ?
    Regards.
    Greg

    GregG wrote:
    One more think is that query comes via dblink (got remote = y in v$sql) I'm
    not sure if that matters.
    DB is 9.2.0.8 .So you did figure out how to join V$SQL to V$SQL_SHARED_CURSOR. ;)
    Can't see which query are you talking about. Your INSERT statement uses VALUES and not SELECT.

  • Problem with gridbaglayout in JPanel

    Hello I am trying to display contact information in three serperate Jpanels on tabbbed panes.I would like to get help in configuring maybe just the pane of void showPane1().I need something like
    Searchlb | Combodropname1
    firstnamelb | firstnametxt | lastnamelb | lastnametxt
    Addresslb addresslb.Horizontal-----------------------*-
    citylb | citytxt | statelb | statetxt
    postcodelb | postcodetxt | countrylb | countrytxt
    emaillb | emailtxt | homephonelb | homephonetxt
    faxnumberlb | faxnumbertxt
    Other panes have buttons
    Here`s the code it operates on login of MSAccess table called persons:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.io.*;
    import java.util.Date;
    import java.text.NumberFormat;
    public class Addressbook extends JFrame{
         // Define constant variables
         final static String driver      = "sun.jdbc.odbc.JdbcOdbcDriver";
         final static String url      = "jdbc:odbc:addBKTAFE";
         final static String login      = "LOG-IN";
         final static String tab_login      = "Log-in";
         final static String tab1      = "INQUIRE Personnel Details";
         final static String tab2      = "UPDATE/DELETE Personnel Details";
         final static String tab3      = "INSERT Personnel Details";
         final static String insert      = "SAVE RECORD";
         final static String update           = "UPDATE RECORD";
         final static String delete      = "DELETE RECORD";
         final static String inquire      = "INQUIRE RECORD";
         final static String clear      = " CLEAR ";
         final static String relogin      = "Log-in failed! Please relog-in!";
         final static String norecfound      = "No Record Found!";
         final static String recinserted     = "Record Inserted!";
         final static String recupdated      = "Record Updated!";
         final static String recdeleted      = "Record Deleted!";
         final static String numericerror = "Age should be numeric!";
         final static String information = "INFORMATION";
         final static String error      = "ERROR";
         final static String genexception = "GENERAL EXCEPTION";
         final static String sqlexception = "SQL EXCEPTION";
         final static String confdelete = "CONFIRM DELETE";
         final static String slash      = "/";
         final static String table1      = "persons";
         final static String table2      = "Addresses";
    // Events events = new Events(this);
         // Define variables     for general use
         String sql = ""; // Used to store sql statements
         int pane_number = 0; // Used to indicate what screen needs to be processed
                                       // like resetting input fields and comboboxes
         boolean abort = false;// Used to indicate if error found to avoid further
                                       // processing/validations
         // Define container, panels and tabbedpane
    Container cntr = getContentPane();
    JTabbedPane tpane = new JTabbedPane();
         JPanel      cbpanel1 , cbpanel2 , cbpanel3,
                   panel1 , panel2 , panel3;
         // Setup constraints and type of layout
         GridBagConstraints constraints = new GridBagConstraints();
         GridBagConstraints constraints1 = new GridBagConstraints();
         GridBagConstraints constraints2 = new GridBagConstraints();
         GridBagConstraints constraints3 = new GridBagConstraints();
         GridBagLayout layout = new GridBagLayout ();
         // Define fonts to be used
         Font labelFont = new Font("Arial",Font.PLAIN,12);
         Font buttonFont = new Font("Arial",Font.BOLD,13);
         // Define labels
         JLabel lbUser      = new JLabel("Enter User ID: " );
         JLabel lbPassword      = new JLabel("Enter Password: ");
         JLabel lbSelectName      = new JLabel("Search Name: " );
         JLabel lbFirstName      = new JLabel("First Name: " );
         JLabel lbLastName      = new JLabel("Last Name: " );
         JLabel lbAddress           = new JLabel("Address: " );
         JLabel lbCity           = new JLabel("City" );
         JLabel lbState           = new JLabel("State: " );
         JLabel lbPostcode      = new JLabel("Postcode" );
    JLabel lbCountry           = new JLabel("Country" );
         JLabel lbEmailAddress      = new JLabel("Email Address: " );
    JLabel lbHomeNumber      = new JLabel("Home Phone No.: " );
    JLabel lbFaxNumber      = new JLabel("Fax No.: " );
         // Define combo boxes in third screen (insert pane)
         JComboBox cbName1          = new JComboBox();
         JComboBox cbPersonId1          = new JComboBox();
         // Define combo boxes in second (update/delete pane)
         JComboBox cbName2          = new JComboBox();
         JComboBox cbPersonId2          = new JComboBox();
         // Define buttons, text fields and password field
         JButton btLogin      = new JButton (login );
         JButton btInsert = new JButton (insert );
         JButton btUpdate      = new JButton (update );
         JButton btDelete      = new JButton (delete );
         JButton btInquire      = new JButton (inquire);
         JButton btClear      = new JButton (clear );
         JPasswordField jpPassword           = new JPasswordField(10 );
         JTextField tfUser           = new JTextField("",10 );
         // Inquiry fields on first screen (inquiry pane)
         JTextField tfFirstName1      = new JTextField("",30);
         JTextField tfLastName1           = new JTextField("",30);
         JTextField      tfAddress1          = new JTextField("",30);
         JTextField      tfCity1 = new JTextField("",15);
         JTextField      tfState1 = new JTextField("",15);
         JTextField      tfPostcode1      = new JTextField("",30);
         JTextField      tfCountry1          = new JTextField("",15 );
    JTextField      tfEmailAddress1      = new JTextField("",30);
    JTextField      tfHomeNumber1      = new JTextField("",15);
         JTextField      tfFaxNumber1           = new JTextField("",15 );
         // Input fields on second screen (update/delete pane)
         JTextField tfFirstName2      = new JTextField("",30);
         JTextField tfLastName2          = new JTextField("",30);
         JTextField      tfAddress2          = new JTextField("",30);
         JTextField      tfCity2 = new JTextField("",15);
         JTextField      tfState2 = new JTextField("",15);
         JTextField      tfPostcode2      = new JTextField("",30);
         JTextField      tfCountry2          = new JTextField("",15 );
    JTextField      tfEmailAddress2      = new JTextField("",30);
    JTextField      tfHomeNumber2      = new JTextField("",15);
         JTextField      tfFaxNumber2      = new JTextField("",15 );
         // Input fields on third screen (insert pane)
         JTextField tfFirstName3      = new JTextField("",30);
         JTextField tfLastName3          = new JTextField("",30);
         JTextField      tfAddress3          = new JTextField("",30);
         JTextField      tfCity3 = new JTextField("",15);
         JTextField      tfState3 = new JTextField("",15);
         JTextField      tfPostcode3      = new JTextField("",30);
         JTextField      tfCountry3          = new JTextField("",15 );
    JTextField      tfEmailAddress3      = new JTextField("",30);
    JTextField      tfHomeNumber3      = new JTextField("",15);
         JTextField      tfFaxNumber3           = new JTextField("",15 );
    //------------------------------------------------------------------------------>>>
    //-----------------------Start Addressbook()------------------------------------>>>
    Addressbook(){
    // define listener after adding items to CB to avoid triggering it
         //     cbName1.addItemListener(new ItemListener());
    // public void itemStateChanged(ItemEvent e){
    //--------------------------END Addressbook constructor------------------------------------->>>
    //------------------------------------------------------------------------------>>>
    //------------------------------------------------------------------------------>>>
    //--------------------Start setupLoginPanel()----------------------------------->>>
         // Setup the login screen
         public void setupLoginPanel(){
              // set application title
         setTitle("Address Book Application");
              // center screen
              setLocation((Toolkit.getDefaultToolkit().getScreenSize().width
                                  - getWidth())/2,
                        (Toolkit.getDefaultToolkit().getScreenSize().height
                             - getHeight())/2);
         panel1 = new JPanel();
              // set screen border
              panel1.setBorder(BorderFactory.createTitledBorder(
                                  BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab_login, panel1);
              // add panel to container
              cntr.add(tpane);
              // setup layout as GridBagLayout
              constraints.insets = new Insets(2,2,2,2);
              panel1.setLayout(layout);
              // setup User ID label in display area
              lbUser.setFont(labelFont);
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbUser, constraints);
              panel1.add(lbUser);
              // setup User ID input field in display area
              tfUser.setFont(labelFont);
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 1;
              constraints.gridy = 0;
              constraints.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(tfUser, constraints);
              panel1.add(tfUser);
              // setup Password label in display area
              lbPassword.setFont(labelFont);
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 0;
              constraints.gridy = 1;
              constraints.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbPassword, constraints);
              panel1.add(lbPassword);
              // setup Password input field in display area
              jpPassword.setEchoChar('*');
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 1;
              constraints.gridy = 1;
              layout.setConstraints(jpPassword, constraints);
              panel1.add(jpPassword);
              // setup Login button in display area
              btLogin.setFont(buttonFont);
              constraints.anchor = GridBagConstraints.WEST;
              constraints.gridy = 3;
              constraints.gridx = 1;
              layout.setConstraints(btLogin, constraints);
              panel1.add(btLogin);
              // setup login button listener
              btLogin.addActionListener(new ButtonHandler());
              // allow ALT L to press login button
              btLogin.setMnemonic('l');
    //--------------------End setupLoginPanel()------------------------------------->>>
    //--------------------Start login()--------------------------------------------->>>
         // Validate user input from the login screen based on information from login
         // table (note: manually create/update your login from table LOGIN).
         public void login(){
              String user = tfUser.getText();
              user = user.trim();
              char[] pw = jpPassword.getPassword();
    String password = new String(pw).trim();
              sql = "SELECT * FROM persons WHERE username='"+
                   user+"' AND password='"+password+"'";
              try{
                   // load MS Access driver
                   Class.forName(driver);
              }catch(java.lang.ClassNotFoundException ex){
                   JOptionPane.showMessageDialog(null,ex.getMessage(), error ,
                        JOptionPane.PLAIN_MESSAGE);
              try{
                   // setup connection to DBMS
                   Connection conn = DriverManager.getConnection(url);
                   // create statement
                   Statement stmt = conn.createStatement();
                   // execute sql statement
                   stmt.execute(sql);
                   ResultSet rs = stmt.getResultSet();
                   boolean recordfound = rs.next();
                   if (recordfound){
                        tpane.removeTabAt(0);
                        showPane1();
                        showPane2();
                        showPane3();
                   else{
                        // username/password invalid
                        JOptionPane.showMessageDialog(null,relogin, error,
                             JOptionPane.INFORMATION_MESSAGE);
                        //clear login and password fields
                        tfUser.setText ("");
                        jpPassword.setText("");
                   conn.close();
              }catch(Exception ex){
                   JOptionPane.showMessageDialog(null,ex.getMessage(), genexception,
                        JOptionPane.INFORMATION_MESSAGE);
    //--------------------End login()----------------------------------------------->>>
    //--------------------Start showPane1()----------------------------------------->>>
         // Setup screen 1(inquiry pane) including labels, input fields, comboboxes.
         // Table PERSONS is read to list inquiry parameters.
         void showPane1(){
              panel1 = new JPanel();
              cbpanel1 = new JPanel();
              // set screen border
              panel1.setBorder(BorderFactory.createTitledBorder(
                                  BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab1, panel1);
              // setup layout as GridBagLayout
              constraints1.insets = new Insets(2,2,2,2);
              panel1.setLayout (layout);
              cbpanel1.setLayout (layout);
              // setup Name combobox label
              lbSelectName.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 0;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbSelectName, constraints1);
              panel1.add(lbSelectName);
              // setup Name combobox as search key
              cbName1.setFont(labelFont);
              constraints1.ipady = 10;
              constraints1.gridx = 1;
              constraints1.gridy = 0;
              constraints1.gridwidth = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(cbName1, constraints1);
              panel1.add(cbName1);
              // setup search combobox (Name and corresponding key)
              cbName1.addItem ("Choose one:");
              cbPersonId1.addItem("0");
              // setup First Name label in display area
              lbFirstName.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.NONE;
              constraints1.gridwidth = 1;
              layout.setConstraints(lbFirstName, constraints1);
              panel1.add(lbFirstName);
              // setup First Name input field in display area
              tfFirstName1.setFont(labelFont);
              tfFirstName1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFirstName1, constraints1);
              panel1.add(tfFirstName1);
              // setup Last Name label in display area
              lbLastName.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.NONE;
              layout.setConstraints(lbLastName, constraints1);
              panel1.add(lbLastName);
              // setup Last Name input field in display area
              tfLastName1.setFont(labelFont);
              tfLastName1.setEditable(false);
              constraints1.gridx = 3;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfLastName1, constraints1);
              panel1.add(tfLastName1);
              // setup Address label in display area
              lbAddress.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 2;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbAddress, constraints1);
              panel1.add(lbAddress);
              // setup Address input field in display area
              tfAddress1.setFont(labelFont);
              tfAddress1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 2;
              constraints1.gridwidth = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(tfAddress1, constraints1);
              panel1.add(tfAddress1);
              // setup City label in display area
              lbCity.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCity, constraints1);
              panel1.add(lbCity);
              // setup City input field in display area
              tfCity1.setFont(labelFont);
              tfCity1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCity1, constraints1);
              panel1.add(tfCity1);
              // setup State label in display area
              lbState.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbState, constraints1);
              panel1.add(lbState);
              // setup State input field in display area
              tfState1.setFont(labelFont);
              tfState1.setEnabled(false);
              constraints1.gridx = 3;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfState1, constraints1);
              panel1.add(tfState1);
              // setup Postcode label in display area
              lbPostcode.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbPostcode, constraints1);
              panel1.add(lbPostcode);
              // setup Address input field in display area
              tfPostcode1.setFont(labelFont);
              tfPostcode1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfPostcode1, constraints1);
              panel1.add(tfPostcode1);
              // setup Country label in display area
              lbCountry.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCountry, constraints1);
              panel1.add(lbCountry);
              // setup Country input field in display area
              tfCountry1.setFont(labelFont);
              tfCountry1.setEditable(false);
              constraints1.gridx = 3;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCountry1, constraints1);
              panel1.add(tfCountry1);
              // setup Email Address label in display area
              lbEmailAddress = new JLabel ("Email Address:");
              lbEmailAddress.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbEmailAddress, constraints1);
              panel1.add(lbEmailAddress);
              // setup Email Address input field in display area
              tfEmailAddress1.setFont(labelFont);
              constraints1.gridx = 1;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfEmailAddress1, constraints1);
              panel1.add(tfEmailAddress1);
              // setup Home Phone Number label in display area
              lbHomeNumber.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbHomeNumber, constraints1);
              panel1.add(lbHomeNumber);
              // setup Home Phone Number input field in display area
              tfHomeNumber1.setFont(labelFont);
              tfHomeNumber1.setEditable(false);
              constraints1.gridx = 3;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfHomeNumber1, constraints1);
              panel1.add(tfHomeNumber1);
              // setup Fax Number label in display area
              lbFaxNumber.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 6;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbFaxNumber, constraints1);
              panel1.add(lbFaxNumber);
              // setup Fax Number input field in display area
              tfFaxNumber1.setFont(labelFont);
              tfFaxNumber1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 6;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFaxNumber1, constraints1);
              panel1.add(tfFaxNumber1);
    // indicate inquiry pane
              pane_number = 1;
              // read table get the list of names in CB search key
         accessDBInit();
              // define listener after adding items to CB to avoid triggering it
              cbName1.addItemListener(new ComboBoxHandler());
    //--------------------End showPane1()------------------------------------------->>>
    //--------------------Start showPane2()----------------------------------------->>>
         // Setup screen 2(update and delete pane) including labels, input fields,
         // comboboxes, and buttons. Table PERSONS is read to list inquiry parameters.
         void showPane2(){
              panel2 = new JPanel();
              cbpanel2 = new JPanel();
              labelFont = new Font("Arial",Font.PLAIN,12);
              buttonFont = new Font("Arial",Font.BOLD,12);
              // set screen border
              panel2.setBorder(BorderFactory.createTitledBorder(
                   BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab2, panel2);
              // setup layout as GridBagLayout
              constraints2.insets = new Insets(2,2,2,2);
              panel2.setLayout (layout);
              cbpanel2.setLayout (layout);
              // setup Name combobox label
              lbSelectName.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 0;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbSelectName, constraints2);
              panel1.add(lbSelectName);
              // setup Name combobox as search key
              cbName2.setFont(labelFont);
              constraints2.ipady = 10;
              constraints2.gridx = 1;
              constraints2.gridy = 0;
              constraints2.gridwidth = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(cbName1, constraints2);
              panel1.add (cbName1);
              // setup search combobox (Name and corresponding key)
              cbName1.addItem ("Choose one:");
              cbPersonId1.addItem("0");
              // setup First Name label in display area
              lbFirstName.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.NONE;
              constraints2.gridwidth = 1;
              layout.setConstraints(lbFirstName, constraints2);
              panel1.add(lbFirstName);
              // setup First Name input field in display area
              tfFirstName2.setFont(labelFont);
              tfFirstName2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFirstName2, constraints2);
              panel1.add(tfFirstName2);
              // setup Last Name label in display area
              lbLastName.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.NONE;
              layout.setConstraints(lbLastName, constraints2);
              panel1.add(lbLastName);
              // setup Last Name input field in display area
              tfLastName2.setFont(labelFont);
              tfLastName2.setEditable(false);
              constraints2.gridx = 3;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfLastName2, constraints2);
              panel1.add(tfLastName2);
              // setup Address label in display area
              lbAddress.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 2;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbAddress, constraints2);
              panel1.add(lbAddress);
              // setup Address input field in display area
              tfAddress2.setFont(labelFont);
              tfAddress2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 2;
              constraints2.gridwidth = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(tfAddress2, constraints2);
              panel1.add(tfAddress2);
              // setup City label in display area
              lbCity.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCity, constraints2);
              panel1.add(lbCity);
              // setup City input field in display area
              tfCity2.setFont(labelFont);
              tfCity2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCity2, constraints2);
              panel1.add(tfCity2);
              // setup State label in display area
              lbState.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbState, constraints2);
              panel1.add(lbState);
              // setup State input field in display area
              tfState2.setFont(labelFont);
              tfState2.setEnabled(false);
              constraints2.gridx = 3;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfState2, constraints2);
              panel1.add(tfState2);
              // indicate inquiry pane
              pane_number = 1;
              // setup Address label in display area
              lbPostcode.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbPostcode, constraints2);
              panel1.add(lbPostcode);
              // setup Address input field in display area
              tfPostcode2.setFont(labelFont);
              tfPostcode2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfPostcode2, constraints2);
              panel1.add(tfPostcode2);
              // setup Country label in display area
              lbCountry.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCountry, constraints2);
              panel1.add(lbCountry);
              // setup Country input field in display area
              tfCountry2.setFont(labelFont);
              tfCountry2.setEditable(false);
              constraints2.gridx = 3;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCountry2, constraints2);
              panel1.add(tfCountry2);
              // setup Email Address label in display area
              lbEmailAddress = new JLabel ("Email Address:");
              lbEmailAddress.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbEmailAddress, constraints2);
              panel1.add(lbEmailAddress);
              // setup Email Address input field in display area
              tfEmailAddress2.setFont(labelFont);
              constraints2.gridx = 1;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfEmailAddress2, constraints2);
              panel1.add(tfEmailAddress2);
              // setup Home Phone Number label in display area
              lbHomeNumber.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbHomeNumber, constraints2);
              panel1.add(lbHomeNumber);
              // setup Home Phone Number input field in display area
              tfHomeNumber2.setFont(labelFont);
              tfHomeNumber2.setEditable(false);
              constraints2.gridx = 3;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfHomeNumber2, constraints2);
              panel1.add(tfHomeNumber2);
              // setup Fax Number label in display area
              lbFaxNumber.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 6;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbFaxNumber, constraints2);
              panel1.add(lbFaxNumber);
              // setup Fax Number input field in display area
              tfFaxNumber2.setFont(labelFont);
              tfFaxNumber2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 6;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFaxNumber2, constraints2);
              panel1.add(tfFaxNumber2);
              // setup UPDATE button in display area
              btUpdate.setFont(buttonFont);
              constraints2.gridx = 3;
              constraints2.gridy = 7;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(btUpdate, constraints2);
              panel2.add(btUpdate);
              // setup DELETE button in display area
              btDelete.setFont(buttonFont);
              constraints2.gridx = 1;
              constraints2.gridy = 7;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(btDelete, constraints2);
              panel2.add(btDelete);
              btUpdate.addActionListener(new ButtonHandler());
              btDelete.addActionListener(new ButtonHandler());
              // allow ALT U to press update button
              btUpdate.setMnemonic('u');
              // allow ALT D to press delete button
              btDelete.setMnemonic('d');
              // read table get the list of names in combo box search key
    accessDBInit();
              // define listener after adding items to CB to avoid triggering it
              cbName2.addItemListener(new ComboBoxHandler());
    //--------------------End showPane2()------------------------------------------->>>
    //--------------------Start showPane3()----------------------------------------->>>
         // Setup screen 2(insert pane) including labels, input fields, comboboxes,
         // and buttons.
         void showPane3(){
              panel3      = new JPanel();
              // set screen border
              panel3.setBorder(BorderFactory.createTitledBorder(
                   BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab3, panel3);
              // setup layout as GridBagLayout
              constraints3.insets = new Insets(2,2,2,2);
              panel3.setLayout (layout);
              // setup First Name label in display area
              JLabel lbFirstName = new JLabel("First Name:");
              lbFirstName.setFont(labelFont);
              constraints3.gridx = 0;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbFirstName, constraints3);
              panel3.add(lbFirstName);
              // setup First Name input field in display area
              tfFirstName3.setFont(labelFont);
              constraints3.ipady = 8; // adjust heigth of input field
              constraints3.gridx = 1;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFirstName3, constraints3);
              panel3.add(tfFirstName3);
              // setup Last Name label in display area
              lbLastName = new JLabel("Last Name: ");
              lbLastName.setFont(labelFont);
              constraints3.gridx = 2;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbLastName, constraints3);
              panel3.add(lbLastName);
              // setup Last Name input field in display area
              tfLastName3.setFont(labelFont);
              constraints3.gridx = 3;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfLastName3, constraints3);
              panel3.add(tfLastName3);
              // setup Middle Name label in display area
              lbAddress = new JLabel("Address: ");
              lbAddress.setFont(labelFont);
              constraints3.gridx = 0;
              constraints3.gridy = 1;
              constraints3.anch

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class andy extends JFrame {
      // Define constant variables
      final static String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
      final static String url = "jdbc:odbc:addBKTAFE";
      final static String login = "LOG-IN";
      final static String tab_login = "Log-in";
      final static String tab1 = "INQUIRE Personnel Details";
      final static String tab2 = "UPDATE/DELETE Personnel Details";
      final static String tab3 = "INSERT Personnel Details";
      final static String tab4 = "PRINT";
      final static String insert = "SAVE RECORD";
      final static String update = "UPDATE RECORD";
      final static String delete = "DELETE RECORD";
      final static String inquire = "INQUIRE RECORD";
      final static String clear = " CLEAR ";
      final static String relogin = "Log-in failed! Please relog-in!";
      final static String norecfound = "No Record Found!";
      final static String recinserted = "Record Inserted!";
      final static String recupdated = "Record Updated!";
      final static String recdeleted = "Record Deleted!";
      final static String numericerror = "Age should be numeric!";
      final static String information = "INFORMATION";
      final static String error = "ERROR";
      final static String genexception = "GENERAL EXCEPTION";
      final static String sqlexception = "SQL EXCEPTION";
      final static String confdelete = "CONFIRM DELETE";
      final static String slash = "/";
      final static String table1 = "persons";
      final static String table2 = "Addresses";
      // Define container, panels and tabbedpane
      Container cntr = getContentPane();
      JTabbedPane tpane = new JTabbedPane();
      JPanel cbpanel1 , cbpanel2 , cbpanel3,
             panel1 , panel2 , panel3, panel4;
      // Define fonts to be used
      Font labelFont = new Font("Arial",Font.PLAIN,12);
      Font buttonFont = new Font("Arial",Font.BOLD,13);
      // Define labels
      JLabel lbUser = new JLabel("Enter User ID: " );
      JLabel lbPassword = new JLabel("Enter Password: ");
      JLabel lbSelectName = new JLabel("Search Name: " );
      JLabel lbFirstName = new JLabel("First Name: " );
      JLabel lbLastName = new JLabel("Last Name: " );
      JLabel lbAddress = new JLabel("Address: " );
      JLabel lbCity = new JLabel("City: " );
      JLabel lbState = new JLabel("State: " );
      JLabel lbPostcode = new JLabel("Postcode: " );
      JLabel lbCountry = new JLabel("Country: " );
      JLabel lbEmailAddress = new JLabel("Email Address: " );
      JLabel lbHomeNumber = new JLabel("Home Phone No.: " );
      JLabel lbFaxNumber = new JLabel("Fax No.: " );
      // Define combo boxes in third screen (insert pane)
      JComboBox cbName1     = new JComboBox();
      JComboBox cbName2     = new JComboBox();
      JComboBox cbName3     = new JComboBox();
      JComboBox cbPersonId1 = new JComboBox();
      JComboBox cbPersonId2 = new JComboBox();
      JComboBox cbPersonId3 = new JComboBox();
      // Inquiry fields on first screen (inquiry pane)
      JTextField tfFirstName1 = new JTextField("",30);
      JTextField tfLastName1 = new JTextField("",30);
      JTextField tfAddress1 = new JTextField("",30);
      JTextField tfCity1 = new JTextField("",15);
      JTextField tfState1 = new JTextField("",15);
      JTextField tfPostcode1 = new JTextField("",30);
      JTextField tfCountry1 = new JTextField("",15 );
      JTextField tfEmailAddress1 = new JTextField("",30);
      JTextField tfHomeNumber1 = new JTextField("",15);
      JTextField tfFaxNumber1 = new JTextField("",15 );
      // Input fields on second screen (update/delete pane)
      JTextField tfFirstName2 = new JTextField("",30);
      JTextField tfLastName2 = new JTextField("",30);
      JTextField tfAddress2 = new JTextField("",30);
      JTextField tfCity2 = new JTextField("",15);
      JTextField tfState2 = new JTextField("",15);
      JTextField tfPostcode2 = new JTextField("",30);
      JTextField tfCountry2 = new JTextField("",15);
      JTextField tfEmailAddress2 = new JTextField("",30);
      JTextField tfHomeNumber2 = new JTextField("",15);
      JTextField tfFaxNumber2 = new JTextField("",15);
      // Input fields on third screen (inset details pane)
      JTextField tfFirstName3 = new JTextField("",30);
      JTextField tfLastName3 = new JTextField("",30);
      JTextField tfAddress3 = new JTextField("",30);
      JTextField tfCity3 = new JTextField("",15);
      JTextField tfState3 = new JTextField("",15);
      JTextField tfPostcode3 = new JTextField("",30);
      JTextField tfCountry3 = new JTextField("",15);
      JTextField tfEmailAddress3 = new JTextField("",30);
      JTextField tfHomeNumber3 = new JTextField("",15);
      JTextField tfFaxNumber3 = new JTextField("",15);
      GridBagLayout layout = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      public andy() {
        super("Address Book Application");
        showPane1();
        showPane2();
        showPane3();
        showPane4();
        cntr.add(tpane, "Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900,385);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screenSize.width  - getWidth())/2,
                    (screenSize.height - getHeight())/2);
        setVisible(true);
      // Setup screen 1(inquiry pane) including labels, input fields, comboboxes.
      // Table PERSONS is read to list inquiry parameters.
      void showPane1() {
        panel1 = new JPanel();
        cbpanel1 = new JPanel();
        // set screen border
        panel1.setBorder(BorderFactory.createTitledBorder(
          BorderFactory.createEtchedBorder(),""));
        // add tabbedpane to panel
        tpane.addTab(tab1, panel1);
        // setup layout as GridBagLayout
        constraints.insets = new Insets(2,2,2,2);
        panel1.setLayout (layout);
        cbpanel1.setLayout (layout);
        // setup Name combobox label
        lbSelectName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbSelectName, constraints);
        panel1.add(lbSelectName);
        // setup Name combobox as search key
        cbName1.setFont(labelFont);
        constraints.ipady = 10;
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(cbName1, constraints);
        panel1.add(cbName1);
        // setup search combobox (Name and corresponding key)
        cbName1.addItem ("Choose one:");
        cbPersonId1.addItem("0");
        // setup First Name label in display area
        lbFirstName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFirstName, constraints);
        panel1.add(lbFirstName);
        // setup First Name input field in display area
        tfFirstName1.setFont(labelFont);
        tfFirstName1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFirstName1, constraints);
        panel1.add(tfFirstName1);
        // setup Last Name label in display area
        lbLastName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbLastName, constraints);
        panel1.add(lbLastName);
        // setup Last Name input field in display area
        tfLastName1.setFont(labelFont);
        tfLastName1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfLastName1, constraints);
        panel1.add(tfLastName1);
        // setup Address label in display area
        lbAddress.setFont(labelFont);
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbAddress, constraints);
        panel1.add(lbAddress);
        // setup Address input field in display area
        tfAddress1.setFont(labelFont);
        tfAddress1.setEditable(false);
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        layout.setConstraints(tfAddress1, constraints);
        panel1.add(tfAddress1);
        // setup City label in display area
        lbCity.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.NONE;
            layout.setConstraints(lbCity, constraints);
        panel1.add(lbCity);
        // setup City input field in display area
        tfCity1.setFont(labelFont);
        tfCity1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfCity1, constraints);
        panel1.add(tfCity1);
        // setup State label in display area
        lbState.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbState, constraints);
        panel1.add(lbState);
        // setup State input field in display area
        tfState1.setFont(labelFont);
        tfState1.setEnabled(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfState1, constraints);
        panel1.add(tfState1);
        // setup Postcode label in display area
        lbPostcode.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbPostcode, constraints);
        panel1.add(lbPostcode);
        // setup Address input field in display area
        tfPostcode1.setFont(labelFont);
        tfPostcode1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfPostcode1, constraints);
        panel1.add(tfPostcode1);
        // setup Country label in display area
        lbCountry.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbCountry, constraints);
        panel1.add(lbCountry);
        // setup Country input field in display area
        tfCountry1.setFont(labelFont);
        tfCountry1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfCountry1, constraints);
        panel1.add(tfCountry1);
        // setup Email Address label in display area
        lbEmailAddress.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbEmailAddress, constraints);
        panel1.add(lbEmailAddress);
        // setup Email Address input field in display area
        tfEmailAddress1.setFont(labelFont);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfEmailAddress1, constraints);
        panel1.add(tfEmailAddress1);
        // setup Home Phone Number label in display area
        lbHomeNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbHomeNumber, constraints);
        panel1.add(lbHomeNumber);
        // setup Home Phone Number input field in display area
        tfHomeNumber1.setFont(labelFont);
        tfHomeNumber1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfHomeNumber1, constraints);
        panel1.add(tfHomeNumber1);
        // setup Fax Number label in display area
        lbFaxNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFaxNumber, constraints);
        panel1.add(lbFaxNumber);
        // setup Fax Number input field in display area
        tfFaxNumber1.setFont(labelFont);
        tfFaxNumber1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFaxNumber1, constraints);
        panel1.add(tfFaxNumber1);
        // indicate inquiry pane
        // pane_number = 1;
        // read table get the list of names in CB search key
        // accessDBInit();
        // define listener after adding items to CB to avoid triggering it
        // cbName1.addItemListener(new ComboBoxHandler());
      //--------------------End showPane1()------------------------------------------->>>
      //--------------------Start showPane2()----------------------------------------->>>
      void showPane2() {
        panel2 = new JPanel();
        cbpanel2 = new JPanel();
        // set screen border
        panel2.setBorder(BorderFactory.createTitledBorder(
          BorderFactory.createEtchedBorder(),""));
        // add tabbedpane to panel
        tpane.addTab(tab2, panel2);
        // setup layout as GridBagLayout
        constraints.ipady = 0;
        panel2.setLayout (layout);
        cbpanel2.setLayout (layout);
        // setup Name combobox label
        lbSelectName = new JLabel("Search Name: ");
        lbSelectName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbSelectName, constraints);
        panel2.add(lbSelectName);
        // setup Name combobox as search key
        cbName2.setFont(labelFont);
        constraints.ipady = 10;
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(cbName2, constraints);
        panel2.add(cbName2);
        // setup search combobox (Name and corresponding key)
        cbName2.addItem ("Choose one:");
        cbPersonId2.addItem("0");
        // setup UPDATE button in display area
        JButton btUpdate = new JButton("Update");
        btUpdate.setFont(buttonFont);
    //    btUpdate.addActionListener(new ButtonHandler());
        btUpdate.setMnemonic(KeyEvent.VK_U);
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(btUpdate, constraints);
        panel2.add(btUpdate);
        // setup DELETE button in display area
        JButton btDelete = new JButton("Delete");
        btDelete.setFont(buttonFont);
    //    btDelete.addActionListener(new ButtonHandler());
        btDelete.setMnemonic(KeyEvent.VK_D);
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(btDelete, constraints);
        panel2.add(btDelete);
        // setup First Name label in display area
        lbFirstName = new JLabel("First Name: ");
        lbFirstName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFirstName, constraints);
        panel2.add(lbFirstName);
        // setup First Name input field in display area
        tfFirstName2.setFont(labelFont);
        tfFirstName2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFirstName2, constraints);
        panel2.add(tfFirstName2);
        // setup Last Name label in display area
        lbLastName = new JLabel("Last Name: ");
        lbLastName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbLastName, constraints);
        panel2.add(lbLastName);
        // setup Last Name input field in display area
        tfLastName2.setFont(labelFont);
        tfLastName2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfLastName2, constraints);
        panel2.add(tfLastName2);
        // setup Address label in display area
        lbAddress = new JLabel("Address: ");
        lbAddress.setFont(labelFont);
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbAddress, constraints);
        panel2.add(lbAddress);
        // setup Address input field in display area
        tfAddress2.setFont(labelFont);
        tfAddress2.setEditable(true);
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        layout.setConstraints(tfAddress2, constraints);
        panel2.add(tfAddress2);
        // setup City label in display area
        lbCity = new JLabel("City: ");
        lbCity.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.NONE;
        layout.setConstraints(lbCity, constraints);
        panel2.add(lbCity);
        // setup City input field in display area
        tfCity2.setFont(labelFont);
        tfCity2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfCity2, constraints);
        panel2.add(tfCity2);
        // setup State label in display area
        lbState = new JLabel("State: ");
        lbState.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbState, constraints);
        panel2.add(lbState);
        // setup State input field in display area
        tfState2.setFont(labelFont);
        tfState2.setEnabled(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfState2, constraints);
        panel2.add(tfState2);
        // setup Postcode label in display area
        lbPostcode = new JLabel("Postcode: ");
        lbPostcode.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbPostcode, constraints);
        panel2.add(lbPostcode);
        // setup Address input field in display area
        tfPostcode2.setFont(labelFont);
        tfPostcode2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfPostcode2, constraints);
        panel2.add(tfPostcode2);
        // setup Country label in display area
        lbCountry = new JLabel("Country: ");
        lbCountry.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbCountry, constraints);
        panel2.add(lbCountry);
        // setup Country input field in display area
        tfCountry2.setFont(labelFont);
        tfCountry2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfCountry2, constraints);
        panel2.add(tfCountry2);
        // setup Email Address label in display area
        lbEmailAddress = new JLabel ("Email Address: ");
        lbEmailAddress.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbEmailAddress, constraints);
        panel2.add(lbEmailAddress);
        // setup Email Address input field in display area
        tfEmailAddress2.setFont(labelFont);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfEmailAddress2, constraints);
        panel2.add(tfEmailAddress2);
        // setup Home Phone Number label in display area
        lbHomeNumber = new JLabel("Home Phone No.: ");
        lbHomeNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbHomeNumber, constraints);
        panel2.add(lbHomeNumber);
        // setup Home Phone Number input field in display area
        tfHomeNumber2.setFont(labelFont);
        tfHomeNumber2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfHomeNumber2, constraints);
        panel2.add(tfHomeNumber2);
        // setup Fax Number label in display area
        lbFaxNumber = new JLabel("Fax No.: ");
        lbFaxNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFaxNumber, constraints);
        panel2.add(lbFaxNumber);
        // setup Fax Number input field in display area
        tfFaxNumber2.setFont(labelFont);
        tfFaxNumber2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFaxNumber2, constraints);
        panel2.add(tfFaxNumber2);
      //-----------------------------End showpane2()---------------------------------->>
      //--------------------Start showPane3()----------------------------------------->>>
      void showPane3() {
        panel3 = new JPanel();
        // cbpanel3 = new JPanel();
        // set screen border
        panel3.setBorder(BorderFactory.createTitledBorder(
          BorderFactory.createEtchedBorder(),""));
        // add tabbedpane to panel
        tpane.addTab(tab3, panel3);
        // setup layout as GridBagLayout
        panel3.setLayout(layout);
        constraints.ipady = 0;
        panel3.setLayout (layout);
        // cbpanel3.setLayout (layout);
        // setup Name combobox label
        lbSelectName = new JLabel("Search Name: ");
        lbSelectName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbSelectName, constraints);
        panel3.add(lbSelectName);
        // setup Name combobox as search key
        cbName3 = new JComboBox();
        cbName3.setFont(labelFont);
        constraints.ipady = 10;
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(cbName3, constraints);
        panel3.add(cbName3);
        // setup search combobox (Name and corresponding key)
        cbName3.addItem ("Choose one:");
        cbPersonId3.addItem("0");
        // setup INSERT button in display area
        JButton btInsert = new JButton("Insert");
        btInsert.setFont(buttonFont);
    //    btInsert.addActionListener(new ButtonListener());
        btInsert.setMnemonic(KeyEvent.VK_S);
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(btInsert, constraints);
        panel3.add(btInsert);
        // setup CLEAR button in display area
        JButton btClear = new JButton("Clear");
        btClear.setFont(buttonFont);
    //    btClear.addActionListener(new ButtonListener());
        btClear.setMnemonic(KeyEvent.VK_C);
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(btClear, constraints);
        panel3.add(btClear);
        // setup First Name label in display area
        lbFirstName = new JLabel("First Name: ");
        lbFirstName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFirstName, constraints);
        panel3.add(lbFirstName);
        // setup First Name input field in display area
        tfFirstName3.setFont(labelFont);
        tfFirstName3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFirstName3, constraints);
        panel3.add(tfFirstName3);
        // setup Last Name label in display area
        lbLastName = new JLabel("Last Name: ");
        lbLastName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbLastName, constraints);
        panel3.add(lbLastName);
        // setup Last Name input field in display area
        tfLastName3.setFont(labelFont);
        tfLastName3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfLastName3, constraints);
        panel3.add(tfLastName3);
        // setup Address label in display area
        lbAddress = new JLabel("Address: ");
        lbAddress.setFont(labelFont);
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbAddress, constraints);
        panel3.add(lbAddress);
        // setup Address input field in display area
        tfAddress3.setFont(labelFont);
        tfAddress3.setEditable(true);
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        layout.setConstraints(tfAddress3, constraints);
        panel3.add(tfAddress3);
        // setup City label in display area
        lbCity = new JLabel("City: ");
        lbCity.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.NONE;
        layout.setConstraints(lbCity, constraints);
        panel3.add(lbCity);
        // setup City input field in display area
        tfCity3.setFont(labelFont);
        tfCity3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfCity3, constraints);
        panel3.add(tfCity3);
        // setup State label in display area
        lbState = new JLabel("State: ");
        lbState.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbState, constraints);
        panel3.add(lbState);
        // setup State input field in display area
        tfState3.setFont(labelFont);
        tfState3.setEnabled(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfState3, constraints);
        panel3.add(tfState3);
        // setup Postcode label in display area
        lbPostcode = new JLabel("Postcode: ");
        lbPostcode.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbPostcode, constraints);
        panel3.add(lbPostcode);
        // setup Address input field in display area
        tfPostcode3.setFont(labelFont);
        tfPostcode3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfPostcode3, constraints);
        panel3.add(tfPostcode3);
        // setup Country label in display area
        lbCountry = new JLabel("Country: ");
        lbCountry.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbCountry, constraints);
        panel3.add(lbCountry);
        // setup Country input field in display area
        tfCountry3.setFont(labelFont);
        tfCountry3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfCountry3, constraints);
        panel3.add(tfCountry3);
        // setup Email Address label in display area
        lbEmailAddress = new JLabel ("Email Address: ");
        lbEmailAddress.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbEmailAddress, constraints);
        panel3.add(lbEmailAddress);
        // setup Email Address input field in display area
        tfEmailAddress3.setFont(labelFont);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfEmailAddress3, constraints);
        panel3.add(tfEmailAddress3);
        // setup Home Phone Number label in display area
        lbHomeNumber = new JLabel("Home Phone No.: ");
        lbHomeNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbHomeNumber, constraints);
        panel3.add(lbHomeNumber);
        // setup Home Phone Number input field in display area
        tfHomeNumber3.setFont(labelFont);
        tfHomeNumber3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfHomeNumber3, constraints);
        panel3.add(tfHomeNumber3);
        // setup Fax Number label in display area
        lbFaxNumber = new JLabel("Fax No.: ");
        lbFaxNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFaxNumber, constraints);
        panel3.add(lbFaxNumber);
        // setup Fax Number input field in display area
        tfFaxNumber3.setFont(labelFont);
        tfFaxNumber3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFaxNumber3, constraints);
        panel3.add(tfFaxNumber3);
      //-----------------------------End showpane3()---------------------------------->>
      //-----------------------------Start showPane4()-------------------------------->>
      void showPane4() {
    //    qtm = new QueryTableModel();
    //    JTable table = new JTable(qtm);
    //    String query = "SELECT FirstName, LastName, HomePhone, " +
    //                   "FROM Addresses ORDER By LastName";
    //    qtm.setQuery(query);
        JPanel demoPanel = new JPanel();
        demoPanel.setPreferredSize(new Dimension(400,500));
        demoPanel.setBackground(Color.pink);
        demoPanel.add(new JLabel("Demo Panel in place of table",
                                  SwingConstants.CENTER));
        JScrollPane scrollPane = new JScrollPane(demoPanel);
        panel4 = new JPanel();
    //    pane_number = 4;
        panel4.setLayout(layout);
        constraints.ipady = 0;
    //    labelFont = new Font("Arial", Font.PLAIN, 12);   defined above
        buttonFont = new Font("Arial", Font.PLAIN, 13);
       // set screen border
       panel4.setBorder(
         BorderFactory.createTitledBorder(
           BorderFactory.createEtchedBorder(), ""));
       // add panel to tabbed pane
       tpane.addTab(tab4, panel4);
       JLabel lbPrint = new JLabel("Print");
       lbPrint.setFont(labelFont);
       constraints.anchor = constraints.EAST;
       layout.setConstraints(lbPrint, constraints);
       panel4.add(lbPrint);
       JButton btPrint = new JButton("Print");
       btPrint.setFont(buttonFont);
    //   btPrint.addActionListener(new ButtonListener());
       btPrint.setMnemonic(KeyEvent.VK_P);
       constraints.anchor = constraints.WEST;
       constraints.gridwidth = constraints.REMAINDER;
       layout.setConstraints(btPrint, constraints);
       panel4.add(btPrint);
       constraints.weighty = 1.0;
       constraints.fill = constraints.BOTH;
       constraints.anchor = constraints.CENTER;
       layout.setConstraints(scrollPane, constraints);
       panel4.add(scrollPane);
      public static void main(String[] args) {
        new andy();
    }

  • Useful Code of the Day:  Hideable Tree Nodes

    Someone posted about how they could selectively hide tree nodes, and I already had this AbstractTreeModel class (which does some things DefaultTreeModel does and some it doesn't) and a concrete subclass for TreeNode objects, so I was thinking how one could do hideable nodes. So I came up with this solution.
    There's 4 classes here:
    - AbstractTreeModel is the base for the concrete TreeNodeTreeModel
    - TreeNodeTreeModel extends AbstractTreeModel to support TreeNodes (DefautlMutableTreeNode, etc.)
    - HideableMutableTreeNode which is a DefautlMutableTreeNode subclass which has a visible field (with is/set methods, of course).
    - HideableTreeModel is the hideable model which is a subclass of TreeNodeTreeModel.
    A HideableMutableTreeNode can be set invisible directly, but the tree still needs to be notified to update. So it's best to use the methods in HideableTreeModel which set a node's visibility which notify the tree of changes accordingly. Methods are also provided to check a full path's visibility or ensure a node including all parent nodes are visible.
    A HideableTreeModel can take any TreeNode class, it doesn't have to be all HideableMutableTreeNodes, but only HideableMutableTreeNodes can be made invisible, of course. Any other TreeNode type would just be considered visible.
    Hiding nodes works basically by making the tree think there's less nodes then there are. And to do this, the node counts and child index search just works by looping thru the parent's children. This has potential perfomance drawbacks of course, since one has to loop thru the node's children to get nodes every time. This could be alleviated by not supporting non-hideable nodes changing the internal maintenance of HideableMutableTreeNode contents. But I'll leave that to whoever really needs it. It shouldn't be a problem if there are are a relatively small set of child nodes in any given parent.
    Also, note that the root node in the model cannot be made invisible, cuz it'd be redundant since JTree can be set to hide the root node.
    // *** HideableTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>HideableTreeModel</code> is an <code>TreeNodeTreeModel</code>
    * implementation for <code>HideableMutableTreeNode</code> objects.  The
    * model can also take any other <code>javax.swing.tree.TreeNode</code>
    * objects. 
    public class HideableTreeModel extends TreeNodeTreeModel {
          * Creates a new <code>HideableTreeModel</code> object.
          * @param  root  the root node
         public HideableTreeModel(TreeNode root) {
              super(root);
          * Checks if the specified node is visible.  A node can only be
          * hidden if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this only test the visibility of the specified node, not
          * whether a parent node is visible.  Use <code>isPathToNodeVisible(Object)</code>
          * to check if the full path is visible. 
          * @param  node  the node
          * @param  true if the node is visible, else false
         public boolean isNodeVisible(Object node) {
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        return ((HideableMutableTreeNode)node).isVisible();
              return true;
          * Sets the specified node to be hidden.  A node can only be made hidden
          * if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility.  <br />
          * <br />
          * Note that this will not alter the visibility of any nodes in the
          * specified node's path to the root node.  Use
          * <code>ensurePathToNodeVisible(Object)</code> instead to make sure the
          * full path down to that node is visible.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility. 
          * @param  node  the node
          * @param  v     true for visible, false for hidden
          * @param  true if the node's visibility could actually change, else false
         public boolean setNodeVisible(Object node, boolean v) {
              // can't hide root
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        HideableMutableTreeNode n = (HideableMutableTreeNode)node;
                        // don't fix what ain't broke...
                        if(v != n.isVisible()) {
                             TreeNode parent = n.getParent();
                             if(v) {
                                  // need to get index after showing...
                                  n.setVisible(v);
                                  int index = getIndexOfChild(parent, n);
                                  super.nodeInserted(parent, n, index);
                             } else {
                                  // need to get index before hiding...
                                  int index = getIndexOfChild(parent, n);
                                  n.setVisible(v);
                                  super.nodeRemoved(parent, n, index);
                        return true;
              return false;
          * Checks if the specified node is visible and all nodes above it are
          * visible. 
          * @param  node  the node
          * @param  true if the path is visible, else false
         public boolean isPathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   if(!isNodeVisible(path)) {
                        return false;
              return true;
         * Sets the specified node and all nodes above it to be visible.
         * Note that this method will notify the tree to reflect any changes to
         * node visibility.
         * @param node the node
         public void ensurePathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   setNodeVisible(path[i], true);
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0, j = -1; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             j++;
                        if(j == index) {
                             return pc;
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              int count = 0;
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             count++;
              return count;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              int index = -1;
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   TreeNode c = (TreeNode)child;
                   if(isNodeVisible(c)) {
                        index = 0;
                        for(int i = 0; i < p.getChildCount(); i++) {
                             TreeNode pc = (TreeNode)p.getChildAt(i);
                             if(pc.equals(c)) {
                                  return index;
                             if(isNodeVisible(pc)) {
                                  index++;
              return index;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              HideableMutableTreeNode root = new HideableMutableTreeNode("root");
              root.add(new HideableMutableTreeNode("child_1"));
              final HideableMutableTreeNode c2 = new HideableMutableTreeNode("child_2");
              c2.setVisible(false);
              final HideableMutableTreeNode c2a = new HideableMutableTreeNode("child_2_A");
              c2.add(c2a);
              c2.add(new HideableMutableTreeNode("child_2_B"));
              root.add(c2);
              HideableMutableTreeNode c3 = new HideableMutableTreeNode("child_3");
              HideableMutableTreeNode cC = new HideableMutableTreeNode("child_3_C");
              cC.setVisible(false);
              c3.add(cC);
              c3.add(new HideableMutableTreeNode("child_3_D"));
              root.add(c3);
              root.add(new HideableMutableTreeNode("child_4"));
              root.add(new HideableMutableTreeNode("child_5"));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode("child_6");
              c6.add(new DefaultMutableTreeNode("child_6_A"));
              c6.add(new DefaultMutableTreeNode("child_6_B"));
              root.add(c6);
              final HideableTreeModel model = new HideableTreeModel(root);
              JTree tree = new JTree(model);
              f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
              JButton b = new JButton("toggle");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.setNodeVisible(c2, !model.isNodeVisible(c2));
                        //model.ensurePathToNodeVisible(c2a);
              f.getContentPane().add(b, BorderLayout.SOUTH);
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** HideableMutableTreeNode ***
    import javax.swing.*;
    import javax.swing.tree.*;
    * <code>HideableMutableTreeNode</code> is a <code>DefaultMutableTreeNode</code>
    * implementation that works with <code>HideableTreeModel</code>.
    public class HideableMutableTreeNode extends DefaultMutableTreeNode {
         * The node is visible flag.
         public boolean visible = true;
         * Creates a tree node that has no parent and no children, but which
         * allows children.
         public HideableMutableTreeNode() {
              super();
         * Creates a tree node with no parent, no children, but which allows
         * children, and initializes it with the specified user object.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         public HideableMutableTreeNode(Object userObject) {
              super(userObject);
         * Creates a tree node with no parent, no children, initialized with the
         * specified user object, and that allows children only if specified.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         * @param allowsChildren - if true, the node is allowed to have child
         * nodes -- otherwise, it is always a leaf node
         public HideableMutableTreeNode(Object userObject, boolean allowsChildren) {
              super(userObject, allowsChildren);
         * Checks if the node is visible.
         * @return true if the node is visible, else false
         public boolean isVisible() {
              return this.visible;
         * Sets if the node is visible.
         * @param v true if the node is visible, else false
         public void setVisible(boolean v) {
              this.visible = v;
    // *** TreeNodeTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>TreeNodeTreeModel</code> is an <code>AbstractTreeModel</code>
    * implementation for <code>javax.swing.tree.TreeNode</code> objects.
    public class TreeNodeTreeModel extends AbstractTreeModel {
         * Creates a new <code>TreeNodeTreeModel</code> object.
         * @param root the root node
         public TreeNodeTreeModel(TreeNode root) {
              super();
              setRoot(root);
         * Returns the parent of the child node.
         * @param node the child node
         * @return the parent or null if root
         public Object getParent(Object node) {
              if(node != getRoot() && (node instanceof TreeNode)) {
                   return ((TreeNode)node).getParent();
              return null;
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildAt(index);
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildCount();
              return 0;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   return ((TreeNode)parent).getIndex((TreeNode)child);
              return -1;
         * Returns true if node is a leaf.
         * @param node the node
         * @return true if the node is a leaf
         public boolean isLeaf(Object node) {
              if(node instanceof TreeNode) {
                   return ((TreeNode)node).isLeaf();
              return true;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
              root.add(new DefaultMutableTreeNode("child_1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("child_2");
              c2.add(new DefaultMutableTreeNode("child_2_A"));
              c2.add(new DefaultMutableTreeNode("child_2_B"));
              root.add(c2);
              root.add(new DefaultMutableTreeNode("child_3"));
              root.add(new DefaultMutableTreeNode("child_4"));
              JTree tree = new JTree(new TreeNodeTreeModel(root));
              f.getContentPane().add(new JScrollPane(tree));
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** AbstractTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public abstract class AbstractTreeModel implements TreeModel {
         * The list of tree model listeners.
         private Vector modelListeners = new Vector();
         * The root object of the tree.
         private Object root = null;
         * Basic no-op constructor.
         public AbstractTreeModel() {
         * Gets the root object of the tree.
         * @return the root object
         public Object getRoot() {
              return this.root;
         * Sets the root object of the tree.
         * @param r the root object
         protected void setRoot(Object r) {
              this.root = r;
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @return the path to the object or <CODE>null</CODE>
         public Object[] getPathToRoot(Object node) {
              return getPathToRoot(node, 0);
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @param i the current index
         * @return the path to the object or <CODE>null</CODE>
         private Object[] getPathToRoot(Object node, int i) {
              Object anode[];
              if(node == null) {
                   if(i == 0) {
                        return null;
                   anode = new Object[i];
              } else {
                   i++;
                   if(node == getRoot()) {
                        anode = new Object[i];
                   } else {
                        anode = getPathToRoot(getParent(node), i);
                   anode[anode.length - i] = node;
              return anode;
         * Gets the parent object of the specified object. This method is not
         * part of the <code>javax.swing.tree.TreeModel</code> interface, but is
         * required to support the <code>getPathToRoot(Object)</code> method,
         * which is widely used in this class. Therefore, it is important to
         * correctly implement this method.
         * @param obj the object
         * @parma the parent object or null if no parent or invalid object
         protected abstract Object getParent(Object obj);
         * Adds a listener for the <CODE>TreeModelEvent</CODE> posted after the
         * tree changes.
         * @param l the tree model listener
         public void addTreeModelListener(TreeModelListener l) {
              modelListeners.addElement(l);
         * Removes a listener previously added with addTreeModelListener().
         * @param l the tree model listener
         public void removeTreeModelListener(TreeModelListener l) {
              modelListeners.removeElement(l);
         * Forces the tree to reload. This is useful when many changes occur
         * under the root node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed. To maintain
         * the expanded nodes, see the <code>getExpandedPaths(JTree)</code>
         * and <code>expandPaths(JTree, ArrayList)</code> methods.
         * @see #getExpandedPaths(JTree)
         * @see #expandPaths(JTree, ArrayList)
         public void reload() {
              reload(getRoot());
         * Forces the tree to repaint. This is useful when many changes occur
         * under a specific node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed below the
         * updated node.
         * @param node the node that changed
         public void reload(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeStructureChanged(new TreeModelEvent(this, tp));
         * Messaged when the user has altered the value for the item identified
         * by <CODE>path</CODE> to <CODE>newValue</CODE>.
         * @param path the path to the changed object
         * @param newValue the new value
         public void valueForPathChanged(TreePath path, Object newValue) {
              nodeChanged(path.getLastPathComponent());
         * Notifies the tree that nodes were inserted. The index is looked up
         * automatically.
         * @param node the parent node
         * @param child the inserted child node
         public void nodeInserted(Object node, Object child) {
              nodeInserted(node, child, -1);
         * Notifies the tree that nodes were inserted.
         * @param node the parent node
         * @param child the inserted child node
         * @param index the index of the child
         public void nodeInserted(Object node, Object child, int index) {
              if(index < 0) {
                   index = getIndexOfChild(node, child);
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that nodes were removed. The index is required
         * since by this point, the object will no longer be in the tree.
         * @param node the parent node
         * @param child the removed child node
         * @param index the index of the child
         public void nodeRemoved(Object node, Object child, int index) {
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesRemoved(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that a node was changed.
         * @param node the changed node
         public void nodeChanged(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null));
         * Fires "tree nodes changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesChanged(event);
         * Fires "tree nodes inserted" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesInserted(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesInserted(event);
         * Fires "tree nodes removed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesRemoved(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesRemoved(event);
         * Fires "tree structure changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeStructureChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeStructureChanged(event);
         * Records the list of currently expanded paths in the specified tree.
         * This method is meant to be called before calling the
         * <code>reload()</code> methods to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public ArrayList getExpandedPaths(JTree tree) {
              ArrayList expandedPaths = new ArrayList();
              addExpandedPaths(tree, tree.getPathForRow(0), expandedPaths);
              return expandedPaths;
         * Adds the expanded descendants of the specifed path in the specified
         * tree to the internal expanded list.
         * @param tree the tree
         * @param path the path
         * @param pathlist the list of expanded paths
         private void addExpandedPaths(JTree tree, TreePath path, ArrayList pathlist) {
              Enumeration enum = tree.getExpandedDescendants(path);
              while(enum.hasMoreElements()) {
                   TreePath tp = (TreePath)enum.nextElement();
                   pathlist.add(tp);
                   addExpandedPaths(tree, tp, pathlist);
         * Re-expands the expanded paths in the specified tree. This method is
         * meant to be called before calling the <code>reload()</code> methods
         * to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public void expandPaths(JTree tree, ArrayList pathlist) {
              for(int i = 0; i < pathlist.size(); i++) {
                   tree.expandPath((TreePath)pathlist.get(i));

    Hey
    I'm not trying to show anyone up here, but having just built a tree model for displaying an XML document in a tree, I thought this seemed like a neat exercise.
    I implemented this very differently from the @OP. I only have one class, HiddenNodeTreeModel. All the hidden node data is stored in the model itself in my class. The advantage of what I've created is it will work with any TreeModel. The disadvantage is that I think it's not going to be very scalable - the additional computing to get the number of child nodes and to adjust indexes is heavy. So if you need a scalable solution definitely don't use this.
    Anyway here you go
    HiddenNodeTreeModel.java
    ======================
    package tjacobs.ui.tree;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import tjacobs.ui.WindowUtilities;
    public class HiddenNodeTreeModel implements TreeModel {
         TreeModel mModel;
         ArrayList<Object> mHidden = new ArrayList<Object>();
         public HiddenNodeTreeModel (TreeModel model) {
              mModel = model;
         public void addTreeModelListener(TreeModelListener arg0) {
              mModel.addTreeModelListener(arg0);
         private ArrayList<Integer> getHiddenChildren(Object parent) {
              ArrayList<Integer> spots = new ArrayList<Integer>();
              Iterator _i = mHidden.iterator();
              while (_i.hasNext()) {
                   Object hidden = _i.next();
                   int idx = mModel.getIndexOfChild(parent, hidden);
                   if (idx != -1) {
                        spots.add(idx);
              return spots;
         public Object getChild(Object arg0, int index) {
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        index++;
              return mModel.getChild(arg0, index);
         public int getChildCount(Object arg0) {
              ArrayList list = getHiddenChildren(arg0);
              System.out.println("size = " + list.size());
              return mModel.getChildCount(arg0) - list.size();
         public int getIndexOfChild(Object arg0, Object arg1) {
              int index = mModel.getIndexOfChild(arg0, arg1);
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              int toSub = 0;
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        toSub++;
              return index - toSub;
         public Object getRoot() {
              // TODO Auto-generated method stub
              return mModel.getRoot();
         public boolean isLeaf(Object arg0) {
              // TODO Auto-generated method stub
              return mModel.isLeaf(arg0);
         public void removeTreeModelListener(TreeModelListener arg0) {
              mModel.removeTreeModelListener(arg0);
         public void valueForPathChanged(TreePath arg0, Object arg1) {
              mModel.valueForPathChanged(arg0, arg1);
         public void hideNode(Object node) {
              if (node instanceof TreePath) {
                   node = ((TreePath)node).getLastPathComponent();
              mHidden.add(node);
         public void showNode(Object node) {
              mHidden.remove(node);
         public void showAll() {
              mHidden.clear();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              DefaultMutableTreeNode A = new DefaultMutableTreeNode("A");
              DefaultMutableTreeNode B = new DefaultMutableTreeNode("B");
              DefaultMutableTreeNode C = new DefaultMutableTreeNode("C");
              DefaultMutableTreeNode D = new DefaultMutableTreeNode("D");
              DefaultMutableTreeNode E = new DefaultMutableTreeNode("E");
              DefaultMutableTreeNode F = new DefaultMutableTreeNode("F");
              A.add(B);
              B.add(C);
              B.add(D);
              B.add(E);
              E.add(F);
              DefaultTreeModel model = new DefaultTreeModel(A);
              final HiddenNodeTreeModel hmodel = new HiddenNodeTreeModel(model);
              final JTree tree = new JTree(hmodel);
              JFrame jf = new JFrame("HiddenNodeTreeModel Test");
              jf.add(tree);
              JMenuBar bar = new JMenuBar();
              jf.setJMenuBar(bar);
              JMenu menu = new JMenu("Options");
              bar.add(menu);
              final JMenuItem hide = new JMenuItem("Hide");
              final JMenuItem show = new JMenuItem("ShowAll");
              menu.add(hide);
              menu.add(show);
              ActionListener al = new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        if (ae.getSource() == hide) {
                             hmodel.hideNode(tree.getSelectionPath());
                             tree.updateUI();
                        else {
                             hmodel.showAll();
                             tree.updateUI();
              hide.addActionListener(al);
              show.addActionListener(al);
              jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf.setBounds(100,100,100,100);
              jf.setVisible(true);
    }

  • Using Thread.currentthread.sleep but not delaying appropriately

    Ok, here it goes. Im currently using the thread.sleep method to delay the changing of the text within some labels. I have 3 labels which represent some arrays. I then sort the arrays. Im trying to throw a delay in so that the user can see the changes happen to the array. Although, when I call the wait.millisec(1000) in (the sleep function I threw into its own wait class) it seems that the waiting all happens at the end. I dont see it during the loop to show the arrangement changes within the arrays. I stepped through the code using the debugger, but it doesnt seem to help.
    Look in the buttonListener within the FourX class.
    * SortTest.java                                   Author:Tim Dudek
       This trivial program tests the insertion sort and selection sort
       subroutines.  The data is then shown graphically.
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SortTest {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class FourX extends JPanel {
         static final long serialVersionUID = 1L; //eclipse echo problem
         private JLabel lblO, lblI, lblS;
         private JButton sort;
         public FourX(){//JLabel lblOrig,JLabel lblSS, JLabel lblIS){
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              SortTest.lblSS = new JLabel ("");
              SortTest.lblOrig = new JLabel ("");
              SortTest.lblIS = new JLabel ("");
              lblO = new JLabel("Orginal", JTextField.LEFT);
              lblI = new JLabel("Insertion Sort", JTextField.LEFT);
              lblS = new JLabel("Selection Sort", JTextField.LEFT);
              sort = new JButton("Sort");     
              sort.addActionListener(new buttonListener());
              SortTest.lblSS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblSS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblSS.setBorder(BorderFactory.createLineBorder (Color.RED, 3));
              SortTest.lblIS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblIS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblIS.setBorder(BorderFactory.createLineBorder (Color.BLUE, 3));
              SortTest.lblOrig.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblOrig.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblOrig.setBorder(BorderFactory.createLineBorder (Color.BLACK, 3));
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblO);
              add(SortTest.lblOrig);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblS);
              add(SortTest.lblSS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblI);
              add(SortTest.lblIS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(sort);
         private class buttonListener implements ActionListener{
              public void actionPerformed (ActionEvent event){
              // sort A into increasing order, using selection sort
                   for (int lastPlace = SortTest.A.length-1; lastPlace > 0; lastPlace--) {
                        Wait.milliSec(50);
                   //Find the largest item among A[0], A[1], ... A[lastPlace],
              // and move it into position lastPlace by swapping it with
              // the number that is currently in position lastPlace
                        int maxLoc = 0; // location of largest item seen so far
                   for (int j = 1; j <= lastPlace; j++) {
                        if (SortTest.A[j] > SortTest.A[maxLoc])
                   maxLoc = j; // Now, location j contains the largest item seen
                   int temp = SortTest.A[maxLoc]; // swap largest item with A[lastPlace]
                   SortTest.A[maxLoc] = SortTest.A[lastPlace];
                   SortTest.A[lastPlace] = temp;
                   Wait.milliSec(100);//<------------ waiting???>
                   SortTest.lblSS.setText("");
                   for (int i = 0; i < SortTest.A.length; i++){
                        SortTest.lblSS.setText(SortTest.lblSS.getText() + " "     + SortTest.A[i]);
                   Wait.oneSec();//<------------ waiting???>
                   // sort the array A into increasing order
                   int itemsSorted; // number of items that have been sorted so far
                   for (itemsSorted = 1; itemsSorted < SortTest.B.length; itemsSorted++) {
                        // assume that items A[0], A[1], ... A[itemsSorted-1] have
                        // already been sorted, and insert A[itemsSorted] into the list.
                        int temp = SortTest.B[itemsSorted]; // the item to be inserted
                        int loc = itemsSorted - 1;
                        while (loc >= 0 && SortTest.B[loc] > temp) {
                             SortTest.B[loc + 1] = SortTest.B[loc];
                             loc = loc - 1;
                        SortTest.B[loc + 1] = temp;
                        Wait.milliSec(100);//<------------ waiting???>                    SortTest.lblIS.setText("");
                        for (int i = 0; i < SortTest.B.length; i++){
                             SortTest.lblIS.setText(SortTest.lblIS.getText() + " "     + SortTest.B[i]);
    public class Wait {
         public static void oneSec() {
              try {
                   Thread.currentThread().sleep(1000);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public static void milliSec(long s) {
              try {
                   Thread.currentThread().sleep(s);
              catch (InterruptedException e) {
                   e.printStackTrace();

    Wow, ok. this is extrodinarily confusing. I read the tutorials, but they're not easy to follow.
    So, what I did was at the entry point:
    public class SortTest implements Runnable {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            (new Thread(new SortTest())).start();
       public void run(){
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    Ok, as I understand, this creates the initial thread to build the gui. Now you suggest that when the user hits "sort" that a second thread be created to handle the sorting routine.  From what I understand I can only inherit from one class in java.  My buttonListener already implements ActionListener. I obviously cant implement ActionListener and Runnable.  Do you have a suggestion? Maybe a link to an example?
    I'm pretty lost. 
    Tim                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Caret not painted in JTextPane

    Hi!
    If I insert a JTextField in JTextPane and set the caret at the position of the JTextField, the Caret is not visible. It seems it is behind the JTextField. Can anybody help me what I could do so that the caret is always visible for the user so that he/she can always know the position of the caret.
    Thanks!
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(Font f, String text,
                   StyledDocument doc) {
              MutableAttributeSet a = new SimpleAttributeSet();
              StyleConstants.setFontSize(a, f.getSize());
              StyleConstants.setFontFamily(a, f.getFamily());
              try {
                   doc.insertString(doc.getLength(), text, a);
              catch (BadLocationException x) {
         private void insertTextFieldInTextPane(Font f, String text,
                   JTextPane tp, int pos) {
              JTextField tf = new JTextField(text, text.length()) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tf.setFont(f);
              FontMetrics fm = tf.getFontMetrics(f);
              int maxAscent = fm.getMaxAscent();
             int height = (int)tf.getPreferredSize().getHeight();
              int borderHeight = tf.getBorder().getBorderInsets(tf).top;
              int aboveBaseline = maxAscent + borderHeight;
              // if you comment the next line out you can see a part of the caret
              float alignmentY = (float)(aboveBaseline)/((float)(height));
              tf.setAlignmentY(alignmentY);
              tp.setCaretPosition(pos);
              tp.insertComponent(tf);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              Font f = new Font("SansSerif", Font.PLAIN, 24);
              this.insertStringInTextPane(f, "* ", doc);
              this.insertTextFieldInTextPane(f, "********", tp, doc.getLength());
              this.insertStringInTextPane(f, " ********", doc);
              tp.setEditable(true);
              tp.setCaretPosition(2);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocationByPlatform(true);
              this.setSize(400,400);
              this.setVisible(true);
         public static void main(String[] args) {
              new TextPaneTest2();
    }

    camickr, thanks for your answer. I polished your solution with LineBorder and setOpaque by using a CompoundBorder:
    tf.setBorder( new CompoundBorder(new LineBorder(new Color(0, 0, 0, 0), 2), tf.getBorder()));In this case the original Look&Feel of JTextField is honoured and the Caret is clearly before the JTextField and not on the border. If it is painted on the border the user might have some problems to recognize if the caret is before textField or in textfield.
    Thank you very much!
    Message was edited by:
    the12hunters

Maybe you are looking for

  • SYSTEM_NO_ROLL dump when trying to precalculate data with RSRD_BROADCAST_PR

    Dear all, At my present customer we are facing a problem when doing a precalculate of data with RSRD_BROADCAST_PROCESSOR. The dump message is: Runtime Errors                                                       SYSTEM_NO_ROLL                     Dat

  • Windows Vista to 7 iTunes

    I cleanly installed Windows 7 from Vista, and now have a Windows.old folder. How do I get my iPhone and iPod Nano data back into iTunes? I re-downloaded itunes and it is currently blank.

  • Activate GOS toolbar in WAM04 transaction

    Hi Experts, Can you tell me how can we activate the Generic Object Services toolbar for transaction WAM04 (disposal documents) in EHS Waste Management? Or write a functional specification for that? Thanks

  • No audio in my new Imac

    Hi everybody, I have a problem with the sound of my Imac. I haven't sound! In the audio-midi configuration there aren't any sound card or devices recognised... Audio haute définition Intel : This is the audio configuration that I have: Identifiant du

  • Missing Loupe View File Info

    I use the File Info feature a lot in Loupe View. However recently it does not show despite selecting it in the View>Loupe Info Menu. Control+I also fails to work. It happened before recent upgrade so do not link it with that software change. In the p