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

Similar Messages

  • Useful Code of the Day:  Splash Screen & Busy Application

    So you are making an Swing application. So what are two common things to do in it?
    1) Display a splash screen.
    2) Block user input when busy.
    Enter AppFrame! It's a JFrame subclass which has a glass pane overlay option to block input (setBusy()). While "busy", it displays the system wait cursor.
    It also supports display of a splash screen. There's a default splash screen if you don't provide a component to be the splash screen, and an initializer runner which takes a Runnable object. The Runnable object can then modify the splash screen component, for example to update a progress bar or text. See the main method for example usage.
    It also has a method to center a component on another component (useful for dialogs) or center the component on the screen.
    NOTE on setBusy: I do recall issues with the setBusy option to block input. I recall it having a problem on some Unix systems, but I can't remember the details offhand (sorry).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * <CODE>AppFrame</CODE> is a <CODE>javax.swing.JFrame</CODE> subclass that
    * provides some convenient methods for applications.  This class implements
    * all the same constructors as <CODE>JFrame</CODE>, plus a few others. 
    * Methods exist to show the frame centered on the screen, display a splash
    * screen, run an initializer thread and set the frame as "busy" to block 
    * user input. 
    public class AppFrame extends JFrame implements KeyListener, MouseListener {
          * The splash screen window. 
         private JWindow splash = null;
          * The busy state of the frame. 
         private boolean busy = false;
          * The glass pane used when busy. 
         private Component glassPane = null;
          * The original glass pane, which is reset when not busy. 
         private Component defaultGlassPane = null;
          * Creates a new <CODE>AppFrame</CODE>. 
         public AppFrame() {
              super();
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified
          * <CODE>GraphicsConfiguration</CODE>. 
          * @param  gc  the GraphicsConfiguration of a screen device
         public AppFrame(GraphicsConfiguration gc) {
              super(gc);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title. 
          * @param  title  the title
         public AppFrame(String title) {
              super(title);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * <CODE>GraphicsConfiguration</CODE>. 
          * @param  title  the title
          * @param  gc     the GraphicsConfiguration of a screen device
         public AppFrame(String title, GraphicsConfiguration gc) {
              super(title, gc);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * icon image. 
          * @param  title  the title
          * @param  icon   the image icon
         public AppFrame(String title, Image icon) {
              super(title);
              setIconImage(icon);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * icon image. 
          * @param  title  the title
          * @param  icon  the image icon
         public AppFrame(String title, ImageIcon icon) {
              this(title, icon.getImage());
          * Initializes internal frame settings. 
         protected void init() {
              // set default close operation (which will likely be changed later)
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              // set up the glass pane
              glassPane = new JPanel();
              ((JPanel)glassPane).setOpaque(false);
              glassPane.addKeyListener(this);
              glassPane.addMouseListener(this);
          * Displays a new <CODE>JWindow</CODE> as a splash screen using the
          * specified component as the content.  The default size of the
          * component will be used to size the splash screen.  See the
          * <CODE>showSplash(Component, int, int)</CODE> method description for
          * more details. 
          * @param  c  the splash screen contents
          * @return  the window object
          * @see  #showSplash(Component, int, int)
          * @see  #hideSplash()
         public JWindow showSplash(Component c) {
              return showSplash(c, -1, -1);
          * Displays a new <CODE>JWindow</CODE> as a splash screen using the
          * specified component as the content.  The component should have all
          * the content it needs to display, like borders, images, text, etc. 
          * The splash screen is centered on monitor.  If width and height are
          * <CODE><= 0</CODE>, the default size of the component will be used
          * to size the splash screen. 
          * <P>
          * The window object is returned to allow the application to manipulate
          * it, (such as move it or resize it, etc.).  However, <B>do not</B>
          * dispose the window directly.  Instead, use <CODE>hideSplash()</CODE>
          * to allow internal cleanup. 
          * <P>
          * If the component is <CODE>null</CODE>, a default component with the
          * frame title and icon will be created. 
          * <P>
          * The splash screen window will be passed the same
          * <CODE>GraphicsConfiguration</CODE> as this frame uses. 
          * @param  c  the splash screen contents
          * @param  w  the splash screen width
          * @param  h  the splash screen height
          * @return  the window object
          * @see  #showSplash(Component)
          * @see  #hideSplash()
         public JWindow showSplash(Component c, int w, int h) {
              // if a splash window was already created...
              if(splash != null) {
                   // if it's showing, leave it; else null it
                   if(splash.isShowing()) {
                        return splash;
                   } else {
                        splash = null;
              // if the component is null, then create a generic splash screen
              // based on the frame title and icon
              if(c == null) {
                   JPanel p = new JPanel();
                   p.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createRaisedBevelBorder(),
                        BorderFactory.createEmptyBorder(10, 10, 10, 10)
                   JLabel l = new JLabel("Loading application...");
                   if(getTitle() != null) {
                        l.setText("Loading " + getTitle() + "...");
                   if(getIconImage() != null) {
                        l.setIcon(new ImageIcon(getIconImage()));
                   p.add(l);
                   c = p;
              splash = new JWindow(this, getGraphicsConfiguration());
              splash.getContentPane().add(c);
              splash.pack();
              // set the splash screen size
              if(w > 0 && h > 0) {
                   splash.setSize(w, h);
              } else {
                   splash.setSize(c.getPreferredSize().width, c.getPreferredSize().height);
              centerComponent(splash);
              splash.show();
              return splash;
          * Disposes the splash window. 
          * @see  #showSplash(Component, int, int)
          * @see  #showSplash(Component)
         public void hideSplash() {
              if(splash != null) {
                   splash.dispose();
                   splash = null;
          * Runs an initializer <CODE>Runnable</CODE> object in a new thread. 
          * The initializer object should handle application initialization
          * steps.  A typical use would be:
          * <OL>
          *   <LI>Create the frame.
          *   <LI>Create the splash screen component.
          *   <LI>Call <CODE>showSplash()</CODE> to display splash screen.
          *   <LI>Run the initializer, in which: 
          *   <UL>
          *     <LI>Build the UI contents of the frame.
          *     <LI>Perform other initialization (load settings, data, etc.).
          *     <LI>Pack and show the frame.
          *     <LI>Call <CODE>hideSplash()</CODE>.
          *   </UL>
          * </OL>
          * <P>
          * <B>NOTE:</B>  Since this will be done in a new thread that is
          * external to the event thread, any updates to the splash screen that
          * might be done should be triggered through with
          * <CODE>SwingUtilities.invokeAndWait(Runnable)</CODE>. 
          * @param  r  the <CODE>Runnable</CODE> initializer
         public void runInitializer(Runnable r) {
              Thread t = new Thread(r);
              t.start();
          * Shows the frame centered on the screen. 
         public void showCentered() {
              centerComponent(this);
              this.show();
          * Checks the busy state.
          * @return  <CODE>true</CODE> if the frame is disabled;
          *          <CODE>false</CODE> if the frame is enabled
          * @see  #setBusy(boolean)
         public boolean isBusy() {
              return this.busy;
          * Sets the busy state.  When busy, the glasspane is shown which will
          * consume all mouse and keyboard events, and a wait cursor is
          * set for the frame. 
          * @param  busy  if <CODE>true</CODE>, disables frame;
          *               if <CODE>false</CODE>, enables frame
          * @see  #getBusy()
         public void setBusy(boolean busy) {
              // only set if changing
              if(this.busy != busy) {
                   this.busy = busy;
                   // If busy, keep current glass pane to put back when not
                   // busy.  This is done in case the application is using
                   // it's own glass pane for something special. 
                   if(busy) {
                        defaultGlassPane = getGlassPane();
                        setGlassPane(glassPane);
                   } else {
                        setGlassPane(defaultGlassPane);
                        defaultGlassPane = null;
                   glassPane.setVisible(busy);
                   glassPane.setCursor(busy ?
                        Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) :
                        Cursor.getDefaultCursor()
                   setCursor(glassPane.getCursor());
          * Handle key typed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyTyped(KeyEvent ke) {
              ke.consume();
          * Handle key released events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyReleased(KeyEvent ke) {
              ke.consume();
          * Handle key pressed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyPressed(KeyEvent ke) {
              ke.consume();
          * Handle mouse clicked events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseClicked(MouseEvent me) {
              me.consume();
          * Handle mouse entered events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseEntered(MouseEvent me) {
              me.consume();
          * Handle mouse exited events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseExited(MouseEvent me) {
              me.consume();
          * Handle mouse pressed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mousePressed(MouseEvent me) {
              me.consume();
          * Handle mouse released events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseReleased(MouseEvent me) {
              me.consume();
          * Centers the component <CODE>c</CODE> on the screen. 
          * @param  c  the component to center
          * @see  #centerComponent(Component, Component)
         public static void centerComponent(Component c) {
              centerComponent(c, null);
          * Centers the component <CODE>c</CODE> on component <CODE>p</CODE>. 
          * If <CODE>p</CODE> is null, the component <CODE>c</CODE> will be
          * centered on the screen. 
          * @param  c  the component to center
          * @param  p  the parent component to center on or null for screen
          * @see  #centerComponent(Component)
         public static void centerComponent(Component c, Component p) {
              if(c != null) {
                   Dimension d = (p != null ? p.getSize() :
                        Toolkit.getDefaultToolkit().getScreenSize()
                   c.setLocation(
                        Math.max(0, (d.getSize().width/2)  - (c.getSize().width/2)),
                        Math.max(0, (d.getSize().height/2) - (c.getSize().height/2))
          * Main method.  Used for testing.
          * @param  args  the arguments
         public static void main(String[] args) {
              final AppFrame f = new AppFrame("Test Application",
                   new ImageIcon("center.gif"));
              f.showSplash(null);
              f.runInitializer(new Runnable() {
                   public void run() {
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        f.getContentPane().add(new JButton("this is a frame"));
                        f.pack();
                        f.setSize(300, 400);
                        try {
                             Thread.currentThread().sleep(3000);
                        } catch(Exception e) {}
                        f.showCentered();
                        f.setBusy(true);
                        try {
                             Thread.currentThread().sleep(100);
                        } catch(Exception e) {}
                        f.hideSplash();
                        try {
                             Thread.currentThread().sleep(3000);
                        } catch(Exception e) {}
                        f.setBusy(false);
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    Hi
    Thanks fo this piece of code. This one really help me
    Deepa

  • Useful Code of the Day:  Multipart Form File Upload

    So, you want to upload files to your web server, do ya? Well, I've seen this topic posted a few times in the last month or so and many of the response I've seen here haven't included definitive answers. Of course, the actual problems vary, but ultimately, a bunch of people want to do file upload from an applet or application to an existing file upload script (CGI, PHP, JSP, etc.) on a web server. And invariably, there are problems with formatting the HTTP request to get things working.
    Well, I had a need to do the same thing. I realize there are other solutions out there, such as some sample code that comes with Jakarta Commons Upload. But since we all like reusable code, and we also all seem to like reinventing wheels, here's my go at it: MultiPartFormOutputStream!
    MultiPartFormOutputStream is a specialized OutputStream-like class. You create your URLConnection to the server (a static method included can do this for a URL for you, as some of the settings, doInput and doOutput specifically, seem to confuse people). Then get the OutputStream from it and create a boundary string (a static method to create one is provided as well) and pass them to the constructor. Now you have a MultiPartFormOutputStream which you can use to write form fields like text fields, checkboxes, etc., as well as write file data (from Files, InputStreams or raw bytes).
    There are some convenience methods for writing primative type values as well as strings, but any higher level objects (aside from Files or InputStreams) aren't supported. (You can always serialize and pass the raw bytes.)
    Sample usage code is below. Also, any recommendations for improvement are requested. The code was tested with the Jakarta Struts.
    import java.io.*;
    import java.net.*;
    * <code>MultiPartFormOutputStream</code> is used to write
    * "multipart/form-data" to a <code>java.net.URLConnection</code> for
    * POSTing.  This is primarily for file uploading to HTTP servers. 
    * @since  JDK1.3
    public class MultiPartFormOutputStream {
          * The line end characters. 
         private static final String NEWLINE = "\r\n";
          * The boundary prefix. 
         private static final String PREFIX = "--";
          * The output stream to write to. 
         private DataOutputStream out = null;
          * The multipart boundary string. 
         private String boundary = null;
          * Creates a new <code>MultiPartFormOutputStream</code> object using
          * the specified output stream and boundary.  The boundary is required
          * to be created before using this method, as described in the
          * description for the <code>getContentType(String)</code> method. 
          * The boundary is only checked for <code>null</code> or empty string,
          * but it is recommended to be at least 6 characters.  (Or use the
          * static createBoundary() method to create one.)
          * @param  os        the output stream
          * @param  boundary  the boundary
          * @see  #createBoundary()
          * @see  #getContentType(String)
         public MultiPartFormOutputStream(OutputStream os, String boundary) {
              if(os == null) {
                   throw new IllegalArgumentException("Output stream is required.");
              if(boundary == null || boundary.length() == 0) {
                   throw new IllegalArgumentException("Boundary stream is required.");
              this.out = new DataOutputStream(os);
              this.boundary = boundary;
          * Writes an boolean field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, boolean value)
                   throws java.io.IOException {
              writeField(name, new Boolean(value).toString());
          * Writes an double field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, double value)
                   throws java.io.IOException {
              writeField(name, Double.toString(value));
          * Writes an float field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, float value)
                   throws java.io.IOException {
              writeField(name, Float.toString(value));
          * Writes an long field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, long value)
                   throws java.io.IOException {
              writeField(name, Long.toString(value));
          * Writes an int field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, int value)
                   throws java.io.IOException {
              writeField(name, Integer.toString(value));
          * Writes an short field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, short value)
                   throws java.io.IOException {
              writeField(name, Short.toString(value));
          * Writes an char field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, char value)
                   throws java.io.IOException {
              writeField(name, new Character(value).toString());
          * Writes an string field value.  If the value is null, an empty string
          * is sent (""). 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, String value)
                   throws java.io.IOException {
              if(name == null) {
                   throw new IllegalArgumentException("Name cannot be null or empty.");
              if(value == null) {
                   value = "";
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"\r\n
              \r\n
              <value>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
              out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              out.writeBytes(value);
              out.writeBytes(NEWLINE);
              out.flush();
          * Writes a file's contents.  If the file is null, does not exists, or
          * is a directory, a <code>java.lang.IllegalArgumentException</code>
          * will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  file      the file (the file must exist)
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType, File file)
                   throws java.io.IOException {
              if(file == null) {
                   throw new IllegalArgumentException("File cannot be null.");
              if(!file.exists()) {
                   throw new IllegalArgumentException("File does not exist.");
              if(file.isDirectory()) {
                   throw new IllegalArgumentException("File cannot be a directory.");
              writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
          * Writes a input stream's contents.  If the input stream is null, a
          * <code>java.lang.IllegalArgumentException</code> will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  fileName  the file name (required)
          * @param  is        the input stream
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType,
                   String fileName, InputStream is)
                   throws java.io.IOException {
              if(is == null) {
                   throw new IllegalArgumentException("Input stream cannot be null.");
              if(fileName == null || fileName.length() == 0) {
                   throw new IllegalArgumentException("File name cannot be null or empty.");
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
              Content-Type: <mime-type>\r\n
              \r\n
              <file-data>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name +
                   "\"; filename=\"" + fileName + "\"");
              out.writeBytes(NEWLINE);
              if(mimeType != null) {
                   out.writeBytes("Content-Type: " + mimeType);
                   out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              byte[] data = new byte[1024];
              int r = 0;
              while((r = is.read(data, 0, data.length)) != -1) {
                   out.write(data, 0, r);
              // close input stream, but ignore any possible exception for it
              try {
                   is.close();
              } catch(Exception e) {}
              out.writeBytes(NEWLINE);
              out.flush();
          * Writes the given bytes.  The bytes are assumed to be the contents
          * of a file, and will be sent as such.  If the data is null, a
          * <code>java.lang.IllegalArgumentException</code> will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  fileName  the file name (required)
          * @param  data      the file data
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType,
                   String fileName, byte[] data)
                   throws java.io.IOException {
              if(data == null) {
                   throw new IllegalArgumentException("Data cannot be null.");
              if(fileName == null || fileName.length() == 0) {
                   throw new IllegalArgumentException("File name cannot be null or empty.");
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
              Content-Type: <mime-type>\r\n
              \r\n
              <file-data>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name +
                   "\"; filename=\"" + fileName + "\"");
              out.writeBytes(NEWLINE);
              if(mimeType != null) {
                   out.writeBytes("Content-Type: " + mimeType);
                   out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              out.write(data, 0, data.length);
              out.writeBytes(NEWLINE);
              out.flush();
          * Flushes the stream.  Actually, this method does nothing, as the only
          * write methods are highly specialized and automatically flush. 
          * @throws  java.io.IOException  on input/output errors
         public void flush() throws java.io.IOException {
              // out.flush();
          * Closes the stream.  <br />
          * <br />
          * <b>NOTE:</b> This method <b>MUST</b> be called to finalize the
          * multipart stream.
          * @throws  java.io.IOException  on input/output errors
         public void close() throws java.io.IOException {
              // write final boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(PREFIX);
              out.writeBytes(NEWLINE);
              out.flush();
              out.close();
          * Gets the multipart boundary string being used by this stream. 
          * @return  the boundary
         public String getBoundary() {
              return this.boundary;
          * Creates a new <code>java.net.URLConnection</code> object from the
          * specified <code>java.net.URL</code>.  This is a convenience method
          * which will set the <code>doInput</code>, <code>doOutput</code>,
          * <code>useCaches</code> and <code>defaultUseCaches</code> fields to
          * the appropriate settings in the correct order. 
          * @return  a <code>java.net.URLConnection</code> object for the URL
          * @throws  java.io.IOException  on input/output errors
         public static URLConnection createConnection(URL url)
                   throws java.io.IOException {
              URLConnection urlConn = url.openConnection();
              if(urlConn instanceof HttpURLConnection) {
                   HttpURLConnection httpConn = (HttpURLConnection)urlConn;
                   httpConn.setRequestMethod("POST");
              urlConn.setDoInput(true);
              urlConn.setDoOutput(true);
              urlConn.setUseCaches(false);
              urlConn.setDefaultUseCaches(false);
              return urlConn;
          * Creates a multipart boundary string by concatenating 20 hyphens (-)
          * and the hexadecimal (base-16) representation of the current time in
          * milliseconds. 
          * @return  a multipart boundary string
          * @see  #getContentType(String)
         public static String createBoundary() {
              return "--------------------" +
                   Long.toString(System.currentTimeMillis(), 16);
          * Gets the content type string suitable for the
          * <code>java.net.URLConnection</code> which includes the multipart
          * boundary string.  <br />
          * <br />
          * This method is static because, due to the nature of the
          * <code>java.net.URLConnection</code> class, once the output stream
          * for the connection is acquired, it's too late to set the content
          * type (or any other request parameter).  So one has to create a
          * multipart boundary string first before using this class, such as
          * with the <code>createBoundary()</code> method. 
          * @param  boundary  the boundary string
          * @return  the content type string
          * @see  #createBoundary()
         public static String getContentType(String boundary) {
              return "multipart/form-data; boundary=" + boundary;
    }Usage: (try/catch left out to shorten the post a bit)
    URL url = new URL("http://www.domain.com/webems/upload.do");
    // create a boundary string
    String boundary = MultiPartFormOutputStream.createBoundary();
    URLConnection urlConn = MultiPartFormOutputStream.createConnection(url);
    urlConn.setRequestProperty("Accept", "*/*");
    urlConn.setRequestProperty("Content-Type",
         MultiPartFormOutputStream.getContentType(boundary));
    // set some other request headers...
    urlConn.setRequestProperty("Connection", "Keep-Alive");
    urlConn.setRequestProperty("Cache-Control", "no-cache");
    // no need to connect cuz getOutputStream() does it
    MultiPartFormOutputStream out =
         new MultiPartFormOutputStream(urlConn.getOutputStream(), boundary);
    // write a text field element
    out.writeField("myText", "text field text");
    // upload a file
    out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
    // can also write bytes directly
    //out.writeFile("myFile", "text/plain", "C:\\test.txt",
    //     "This is some file text.".getBytes("ASCII"));
    out.close();
    // read response from server
    BufferedReader in = new BufferedReader(
         new InputStreamReader(urlConn.getInputStream()));
    String line = "";
    while((line = in.readLine()) != null) {
          System.out.println(line);
    in.close();------
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    I have a weird problem here. I'm using the Java POST (slightly altered for my purposes) mechanism but the receiving script doesn't receive any form variables (neither files nor regular form fields). If I try using the same receiving script with a regular upload form, it works. Because I've been pulling my hair out, I even went so far as to analyze the ip-packets. I can see that the file is actually sent through the Java POST mecahnism. Anybody any ideas. Here's the ip-packet of the failing upload:
    ----- Hypertext Transfer Protocol -----
    HTTP: POST /fotoxs/upload.cfm HTTP/1.1
    HTTP: Connection: Keep-Alive
    HTTP: Content-Type: multipart/form-data; boundary=-----------------------------fb2649be18
    HTTP: User-Agent: Mozilla/4.7 [en] (WinNT; U)
    HTTP: Accept-Language: en-us
    HTTP: Accept-Encoding: gzip, deflate
    HTTP: Accept: image/gif, image/jpeg, image/pjpeg, */*
    HTTP: CACHE-CONTROL: no-cache
    HTTP: Host: newmarc
    HTTP: Content-Length: 15511
    ----- Hypertext Transfer Protocol -----
    HTTP: -----------------------------fb2649be18
    HTTP: Content-Disposition: form-data; name="uploadFile"; filename="out.jpg"
    HTTP: Content-Type: image/jpeg
    HTTP: Data
    ....[data packets]
    The one that works (from the regular post) is as follows:
    ----- Hypertext Transfer Protocol -----
    HTTP: POST /fotoxs/upload.cfm HTTP/1.1
    HTTP: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-gsarcade-launch, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
    HTTP: Referer: http://localhost:8500/fotoxs/test.cfm
    HTTP: Accept-Language: nl
    HTTP: Content-Type: multipart/form-data; boundary=---------------------------7d41961f201c0
    HTTP: Accept-Encoding: gzip, deflate
    HTTP: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
    HTTP: Host: newmarc
    HTTP: Content-Length: 59022
    HTTP: Connection: Keep-Alive
    HTTP: Cache-Control: no-cache
    ----- Hypertext Transfer Protocol -----
    HTTP: -----------------------------7d41961f201c0
    HTTP: Content-Disposition: form-data; name="FiletoUpload"; filename="D:\My Documents\My Pictures\fotomarc.jpg"
    HTTP: Content-Type: image/pjpeg
    HTTP: Data
    ----- Hypertext Transfer Protocol -----
    HTTP: HTTP/1.1 100 Continue
    HTTP: Server: Microsoft-IIS/5.0
    HTTP: Date: Sun, 07 Mar 2004 17:14:41 GMT
    ....[data packets]
    One detail worth mentioning is that I don't read a file from harddisk, I'm streaming it directly to the connection outputstream from an image compression utility. But I can see the data in the ip-packets, and even if that somehow didn't work right, it doesn't explaing the fact that the receiving scripts reports no form fields whatsoever.
    Thanks,
    Marc

  • Useful Code of the Day:  Button fires events while held

    Have you ever been making a GUI application with Swing and used some JButtons? Fun, right? Have you ever wanted to have the button fire action events while the button was being held down? Well, if you just stick a plain JButton in your application and press and hold the mouse button on it, you'll see it doesn't do anything except sit there looking pressed in. Insolent button!
    RepeatButton (code below, couldn't think of a better name) is a JButton subclass which contains a timer that is set when the mouse button presses the button, and after a slight initial delay (configurable), fires action events to all registered action listeners repeatedly (with another configurable delay between events) until either the mouse is released or the mouse moves out of the button (it starts up again if the mouse moves back over without releasing the mouse button) or the button is disabled. The event modifiers are passed on as well, so you know if the shift or control buttons (or whatever) are being pressed at the same time.
    There is also a method to disable the repeated action firing while holding. This, in effect, turns the button into a normal JButton, if needed.
    There is a main method for testing which will show a button in a frame and print out the action command for each action event fired.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * <code>RepeatButton</code> is a <code>JButton</code> which contains a timer
    * for firing events while the button is held down.  There is a default
    * initial delay of 300ms before the first event is fired and a 60ms delay
    * between subsequent events.  When the user holds the button down and moves
    * the mouse out from over the button, the timer stops, but if the user moves
    * the mouse back over the button without having released the mouse button,
    * the timer starts up again at the same delay rate.  If the enabled state is
    * changed while the timer is active, it will be stopped.
    * NOTE:  The normal button behavior is that the action event is fired after
    * the button is released.  It may be important to konw then that this is
    * still the case.  So in effect, listeners will get 1 more event then what
    * the internal timer fires.  It's not a "bug", per se, just something to be
    * aware of.  There seems to be no way to suppress the final event from
    * firing anyway, except to process all ActionListeners internally.  But
    * realistically, it probably doesn't matter. 
    public class RepeatButton extends JButton
              implements ActionListener, MouseListener {
          * The pressed state for this button.
         private boolean pressed = false;
          * Flag to indicate that the button should fire events when held. 
          * If false, the button is effectively a plain old JButton, but
          * there may be times when this feature might wish to be disabled. 
         private boolean repeatEnabled = true;
          * The hold-down timer for this button.
         private Timer timer = null;
          * The pressed state for this button.
         private int delay = 60;
          * The pressed state for this button.
         private int initialDelay = 300;
          * Holder of the modifiers used when the mouse pressed the button. 
          * This is used for subsequently fired action events.  This may change
          * after mouse pressed if the user moves the mouse out, releases a key
          * and then moves the mouse back in. 
         private int modifiers = 0;
          * Creates a button with no set text or icon.
         public RepeatButton() {
              super();
              init();
          * Creates a button where properties are taken from the Action supplied.
          * @param  a  the button action
         public RepeatButton(Action a) {
              super(a);
              init();
          * Creates a button with an icon.
          * @param  icon  the button icon
         public RepeatButton(Icon icon) {
              super(icon);
              init();
          * Creates a button with text.
          * @param  text  the button text
         public RepeatButton(String text) {
              super(text);
              init();
          * Creates a button with initial text and an icon.
          * @param  text  the button text
          * @param  icon  the button icon
         public RepeatButton(String text, Icon icon) {
              super(text, icon);
              init();
          * Initializes the button.
         private void init() {
              this.addMouseListener(this);
              // initialize timers for button holding...
              this.timer = new Timer(this.delay, this);
              this.timer.setRepeats(true);
          * Gets the delay for the timer of this button. 
          * @return  the delay
         public int getDelay() {
              return this.delay;
          * Set the delay for the timer of this button. 
          * @param  d  the delay
         public void setDelay(int d) {
              this.delay = d;
          * Gets the initial delay for the timer of this button. 
          * @return  the initial delay
         public int getInitialDelay() {
              return this.initialDelay;
          * Sets the initial delay for the timer of this button. 
          * @param  d  the initial delay
         public void setInitialDelay(int d) {
              this.initialDelay = d;
          * Checks if the button should fire events when held.  If false, the
          * button is effectively a plain old JButton, but there may be times
          * when this feature might wish to be disabled. 
          * @return  if true, the button should fire events when held
         public boolean isRepeatEnabled() {
              return this.repeatEnabled;
          * Sets if the button should fire events when held.  If false, the
          * button is effectively a plain old JButton, but there may be times
          * when this feature might wish to be disabled.  If false, it will
          * also stop the timer if it's running.
          * @param  en  if true, the button should fire events when held
         public void setRepeatEnabled(boolean en) {
              if(!en) {
                   this.pressed = false;
                   if(timer.isRunning()) {
                        timer.stop();
              this.repeatEnabled = en;
          * Sets the enabled state of this button.  Overridden to stop the timer
          * if it's running.
          * @param  en  if true, enables the button
         public void setEnabled(boolean en) {
              if(en != super.isEnabled()) {
                   this.pressed = false;
                   if(timer.isRunning()) {
                        timer.stop();
              super.setEnabled(en);
          * Handle action events.
          * @param  ae  the action event
         public void actionPerformed(ActionEvent ae) {
              // process events only from this components
              if(ae.getSource() == this.timer) {
                   ActionEvent event = new ActionEvent(
                        this, ActionEvent.ACTION_PERFORMED,
                        super.getActionCommand(), this.modifiers);
                   super.fireActionPerformed(event);
              // testing code...
              else if(testing && ae.getSource() == this) {
                   System.out.println(ae.getActionCommand());
          * Handle mouse clicked events.
          * @param  me  the mouse event
         public void mouseClicked(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   this.pressed = false;
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Handle mouse pressed events.
          * @param  me  the mouse event
         public void mousePressed(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
                   this.pressed = true;
                   if(!this.timer.isRunning()) {
                        this.modifiers = me.getModifiers();
                        this.timer.setInitialDelay(this.initialDelay);
                        this.timer.start();
          * Handle mouse released events.
          * @param  me  the mouse event
         public void mouseReleased(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   this.pressed = false;
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Handle mouse entered events.
          * @param  me  the mouse event
         public void mouseEntered(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
                   if(this.pressed && !this.timer.isRunning()) {
                        this.modifiers = me.getModifiers();
                        this.timer.setInitialDelay(this.delay);
                        this.timer.start();
          * Handle mouse exited events.
          * @param  me  the mouse event
         public void mouseExited(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Testing flag.  Set in main method.
         private static boolean testing = false;
          * Main method, for testing.  Creates a frame with both styles of menu.
          * @param  args  the command-line arguments
         public static void main(String[] args) {
              testing = true;
              JFrame f = new JFrame("RepeatButton Test");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel();
              RepeatButton b = new RepeatButton("hold me");
              b.setActionCommand("test");
              b.addActionListener(b);
              p.add(b);
              f.getContentPane().add(p);
              f.pack();
              f.show();
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    This makes word completion possible for JTextArea:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.util.*;
    * This class provides word completion for JTextArea.
    public class WordCompleteArea extends JTextArea {
        private boolean isTextComplete = true;
        public WordCompleteArea (Document doc, String text,
                                      int rows, int columns, KeyStroke expandKey) {
            super (doc, text, rows, columns);
            String s = "word-complete";
            Action wordComplete = new AbstractAction () {
                public void actionPerformed (ActionEvent e) {
                    wordComplete ();
            getInputMap ().put (expandKey, s);
            getActionMap ().put (s, wordComplete);
        public WordCompleteArea (Document doc, String text, int rows, int columns) {
            this (doc, text, rows, columns,
                            KeyStroke.getKeyStroke ("ctrl pressed SPACE"));
        public WordCompleteArea (Document doc) {
            this (doc, null, 0, 0);
        public WordCompleteArea (String text, int rows, int columns) {
            this (new PlainDocument (), text, rows, columns);
        public WordCompleteArea (int rows, int columns) {
            this (null, rows, columns);
        public WordCompleteArea (String text) {
            this (text, 0, 0);
        public WordCompleteArea () {
            this (0, 0);
         * Define if text already written in the JTextArea will be used
         * for expansion.
        public void setTextComplete (boolean b) {
            isTextComplete = b;
         * Find out if text already written in the JTextArea will be used
         * for expansion.
        public boolean isTextComplete () {
            return isTextComplete;
        private String tokenDelimiters = "\t\r\n ,;()[]{}%+/-*<>=&|!\"\'.@#";
         * Get delimiters that form a word.
        public String getTokenDelimiters () {
            return tokenDelimiters;
         * Set delimiters that form a word.
        public void setTokenDelimiters (String s) {
            tokenDelimiters = s;
        // Additional words used for expansion.
        private LinkedList wordCompleteList = new LinkedList ();
         * Add words that will be used as expansion.
        public void addCompleteWords (java.util.List words) {
            wordCompleteList.add (words);
         * Add a word that will be used as expansion.
        public void addCompleteWord (String word) {
            wordCompleteList.add (word);
        private String lastExpanded = null;
        private String lastExpansion = null;
        private Set dontAccept = new HashSet ();
        protected void wordComplete () {
            int caret = getCaretPosition ();
            if (caret == 0)
                return;
            String text = getText ();
            if (caret != text.length () && isCompletionLetter (text.charAt (caret)))
                return;
            StringBuffer sb = new StringBuffer ();
            int index = caret - 1;
            char ch;
            while (index >= 0 && isCompletionLetter ((ch = text.charAt (index)))) {
                sb.append (ch);
                index--;
            if (sb.length () == 0)
                return;
            sb.reverse ();
            String word = sb.toString ();
            String toExpand = word;
            if (toExpand.equals (lastExpansion)) {
                dontAccept.add (lastExpansion);
                toExpand = lastExpanded;
            } else {
                dontAccept.clear ();
            String s = findExpansion (toExpand, caret);
            if (s != null) {
                lastExpanded = toExpand;
                lastExpansion = s;
                replaceRange (s, caret - word.length (), caret);
            } else {
                dontAccept.clear ();
                lastExpanded = null;
                lastExpansion = null;
                int diff = word.length () - toExpand.length ();
                replaceRange ("", caret - diff, caret);
        private boolean isCompletionLetter (char ch) {
            return tokenDelimiters.indexOf (ch) < 0;
        protected String findExpansion (String word, int caret) {
            StringTokenizer st;
            if (isTextComplete) {
                st = new StringTokenizer (getText (), getTokenDelimiters ());
                while (st.hasMoreTokens ()) {
                    String s = st.nextToken ();
                    if (    s.startsWith (word)
                            && s.length () != word.length ()
                            && !dontAccept.contains (s)      ) {
                        return s;
            for (Iterator it = wordCompleteList.iterator (); it.hasNext (); ) {
                st = new StringTokenizer
                                ((String) it.next (), getTokenDelimiters ());
                while (st.hasMoreTokens ()) {
                    String s = st.nextToken ();
                    if (    s.startsWith (word)
                            && s.length () != word.length ()
                            && !dontAccept.contains (s)      ) {
                        return s;
            return null;
        // TEST
        public static void main (String[] args) {
            WordCompleteArea a = new WordCompleteArea ();
            JFrame window = new JFrame ();
            window.getContentPane ().add (a, BorderLayout.CENTER);
            window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            window.setSize (300, 300);
            window.setVisible (true);
    }

  • Urgent! the name of tree node can't show  completely

    I create a tree dynamicly using data from database;when i want to add a new node to the tree.it will be added at the right place imediately but it's name will not show completely.
    for example, i want to add a new node which name is "department",but the name on the tree it shown will be "departm...", i don't know what cause the 3 dot followed and how to remove the dot.
    Can anybody tell me why? Thanks a lot

    I use a IconNode which extend DefaultMutableTreeNode to create the node.
    following is the IconNode:
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    * @version 1.1 06/19/99
    public class IconNode extends DefaultMutableTreeNode {
    protected Icon icon;
    protected String iconName;
    protected boolean isActive=false;
    public IconNode() {
    this(null);
    public IconNode(Object userObject) {
    this(userObject, true, null);
    public IconNode(Object userObject, boolean allowsChildren
    , Icon icon) {
    super(userObject, allowsChildren);
    this.icon = icon;
    public void setIcon(Icon icon) {
    this.icon = icon;
    public Icon getIcon() {
    return icon;
    public boolean isActive(){
    return this.isActive;
    public void setActive(boolean flag){
    this.isActive=flag;
    public String getIconName() {
    if (iconName != null) {
    return iconName;
    else {
    String str = userObject.toString();
    int index = str.lastIndexOf(".");
    if (index != -1) {
    return str.substring(++index);
    else {
    return str;
    public void setIconName(String name) {
    iconName = name;
    following is the operation of adding node:
    private IconNode addObject(Object child) {
    IconNode parentNode = null;
    TreePath parentPath = appQueueTree.getSelectionPath();
    if (parentPath == null) {
    parentNode = rootNode;
    else {
    parentNode = (IconNode)
    (parentPath.getLastPathComponent());
    return addObject(parentNode, child, true);
    private IconNode addObject(IconNode parent,
    Object child,
    boolean shouldBeVisible) {
    IconNode childNode = new IconNode(child);
    // TreeNodeData is a value object contains the data of node.
    TreeNodeData temp=(TreeNodeData)child;
    int flag=temp.getNodeType();// get the type of node
    //to set the right icon of node
    switch(flag){
    case 1://childNode.setIcon();
    break;
    case 2:childNode.setIcon(leafIcon);
    break;
    case 3:childNode.setIcon(connectedDepartmentIcon);
    if (parent == null) {
    parent = rootNode;
    treeModel.insertNodeInto(childNode, parent,
    parent.getChildCount());
    //Make sure the user can see the lovely new node.
    if (shouldBeVisible) {
    //to scroll the tree path to node newly be added.
    appQueueTree.scrollPathToVisible(new TreePath(childNode.getPath()));
    return childNode;

  • Click on the searched  hierachical tree node

    Hi,
    when i search the hierarchical tree for a string then all the matching nodes come selected.Then when i click on any of the search result nodes it does not work and otherwise i have to click on a non selected node and then click on the desired node .
    For example i have created a tree for material used for manufacturing purpose.i want to display the related suppliers names in an adjacent grid by clicking on the node in the tree. how can i do that directly after getting the search node.??

    Bibekananda wrote:
    Hi,
    when i search the hierarchical tree for a string then all the matching nodes come selected.Then when i click on any of the search result nodes it does not work and otherwise i have to click on a non selected node and then click on the desired node .
    For example i have created a tree for material used for manufacturing purpose.i want to display the related suppliers names in an adjacent grid by clicking on the node in the tree. how can i do that directly after getting the search node.??hi
    i hope i get you
    i think you have a form contain a block for tree and another block build on a database table and you want to execute query on the block when you select a node
    and you have a search item to seach for a node and want to go to the block record when you clock on search without go to the node and select
    try this in search button or when-validate-item of the search key
    -- create a pkg specifiaction called tree_pkg and define the follwing variable
    --node ftree.node;
    PROCEDURE select_node IS
         node ftree.node;
         htree item;
         node_label varchar2(3000);
    node_val varchar2(3000);
         state varchar2(3000);
    begin
         htree := find_item('BLOCK.TREE_ITEM');
         node := Ftree.Find_Tree_Node(htree, '');
    ftree.set_tree_selection(htree,node,ftree.select_on) ;
    WHILE NOT Ftree.ID_NULL(node) LOOP
         state := Ftree.Get_Tree_Node_Property(htree, node, Ftree.NODE_STATE);
    node_label := Ftree.Get_Tree_Node_Property(htree, node, Ftree.NODE_label);
    node_val := Ftree.Get_Tree_Node_Property(htree, node, Ftree.NODE_value);
    if upper(node_label) like <your search item> then
    ftree.set_tree_selection(htree,node,ftree.select_on) ;
    tree_pkg.node := node;
    exit;
    end if;
    node := Ftree.Find_Tree_Node(htree, '', ftree.find_NEXT,Ftree.NODE_LABEL,'', node);
    END LOOP;
    ---- now you have the node number that result from search
    node_val := Ftree.Get_Tree_Node_Property(htree, tree_pkg.node, Ftree.NODE_value);
    -- then use this value in execute query on the supplier block
    END;
    try and respond

  • Create Timer Jobs dynamically using code (on the fly)

    What I am trying to accomplish here is different from the usual "Create and deploy a new custom timer job". So please co operate.
    Scenario : I have around 200 lists in my site. Each list gets its data from a third part web service (cutom code / not BCS). The data retrieval happens via Timer Jobs. The Timer Jobs call the web service, gets the fresh data and updates the
    list items. This is currently working fine with multiple lists and 1 timer job to refresh the data.
    Problem : Now the issue I am facing is, each of the lists have its own Refresh Frequency. Say List 1 to 30 needs to be refreshed every 5 mins. List 31 to 60 every 10 mins, etc. I am currently handling this by having a RefreshLastRun timestamp.
    This works fine in most of the scenarios - unless the Web service returns large data, in which case it takes more than 5 to 10 mins for the Update to complete on 4 to 5 lists. At the same time, the other lists - they were supposed to be updated 5 mins ago,
    but are still waiting to get updated because the timer job is busy updating another list, and the refresh is in Que. This is a completely unaccepatable solution to my client because the list with lower frequency duration (5 mins) is of a higher priority than
    the lists getting refreshed every 10 mins.
    My Question is : How do I create a new Timer Job for each list? Whenever I add a new list (through code), I want to create a Timer Job at the same time, which will take care of refreshing the data in this and this list only. This way, I will
    have a independent Timer Job for each list and dont have to depend on 1 timer job to take all the load. With this approach I will have 200 timer jobs running. Which is OK with my client. So I create one class inhereting from SPJobDefinition class, and
    use it repeatedly to create unlimted timer jobs?
    I hope I am able to convey the message. My Timer Jobs are working fine. I dont need suggestions on how to get the timer job working etc. My question is, how do I create a new Job Definition dynamically through code (no deployment).
    Hanif

    I'm afraid this leads to a path where you create a single timer job (or windows service) that uses parallel programming (tpl) to handle all the lists. However, that places a huge burden on you to manage schedules, monitoring etc., something the timer job
    framework handles for you.
    Kind regards,
    Margriet Bruggeman
    Lois & Clark IT Services
    web site: http://www.loisandclark.eu
    blog: http://www.sharepointdragons.com

  • Purchased Lightroom 5 (Student/Teacher version) - got my Redemption Code  and Serial Number but when I use codes provided the system will not finish loading. Have PC running Windows 7.  What is wrong?

    Help . . . Have the Redemption code and Serial Number as supplied on-line but can not install system using these numbers.

    Redemption Code Help
    http://helpx.adobe.com/x-productkb/global/redemption-code-help.html

  • WHEN-TREE-NODE-SELECTED

    Hello alllll
    i have a master-detail block besides a tree block
    All i wanna do Simply and logically is to select a tree node then a Master-Detail records related to this tree node is to be retrieved...
    _i have the following code in the WHEN-TREE-NODE-SELECTED Trigger as follow:_
    DECLARE
      htree ITEM;
       node_value VARCHAR2(100);
    BEGIN
    IF :SYSTEM.TRIGGER_NODE_SELECTED = 'TRUE' THEN
    -- Find the tree itself.
    htree := FIND_ITEM ('BL_TREE.IT_TREE');
    -- Find the value of the node clicked on.
    NODE_VALUE := FTREE.GET_TREE_NODE_PROPERTY( htree, :SYSTEM.TRIGGER_NODE ,  Ftree.NODE_LABEL );
       GO_BLOCK ('STP_COMPANIES');  
    EXECUTE_QUERY;
        END IF;
    END;The above code retrieved data as a whole
    but i want 2 filter the data selected from the tree node as i said 2 be displayed as filtered by the tree selection.
    so i used the following code as follow:
    GO_BLOCK ('GL_COST_CENTERS');  
       set_block_property('GL_COST_CENTERS', DEFAULT_WHERE, 'COMPANY_ID ='||
       ftree.get_tree_node_property('BL_TREE.IT_TREE', :SYSTEM.TRIGGER_NODE, FTREE.NODE_VALUE));
    EXECUTE_QUERY;Any help will be appreciated...
    Thanks in Advance..
    Regards,
    Abdetu...

    Hello thanks for reply,
    STP_COMPANIES your detail block? no it's the master
    gets the "Label" of the tree node not the value of the selected nodei tried both but nothing retrieved...!
    i thought that the value is the serial of the node and the lable is the text displayed on the tree node no ?
    Is this code in the same When-Tree-Node-Selected trigger or a different trigger?yes WHEN-TREE-NODE-SELECTED as my post titled...
    is GL_COST_CENTERS the master block? no it's the detail ; every company --- has many <- cost centers
    are the tables related? yes
    just query the master table and the detail table will automatically be filter through the relationship?i did and it works filtering through the company_id, But what i wanna do is 2 filter the data displayed in the two block Master-Detail according 2 the selection of the tree
    Say i selected the ....
                               + Assets node
                               |
                               |------ - Furnitures    's node is selected so alll the related details of the furniture is displayed in the Master-BLock
                               |         |
                               |         +----chairs
                               |         |
                               |         +----tables
                               |        
                               +----- LAnds
                               |So the Tree is used 2 Query or retrieved the selected node's data accordingly...
    hope i well explained my issue ..!
    is it possible 2 do that ?!
    Thanks Again..
    Regards,
    Abdetu...

  • How to hide the default arrow icon of af:tree node

    Hi All,
    I am using Oracle JDeveloper 11g R2.
    I want to hide the arrow icon which is displayed by default with af:tree node. The use case is to display custom icons for all the nodes. The problem is that when I am customizing icons of tree node, it is showing arrow as well as the icon with each node. Which doesn't seems fine. Can any one help/guide on how to hide the default af:tree node arrow icon.
    Thanks in advance.
    Regards
    Bilal
    Edited by: Bilal on 29-May-2012 01:32

    Hi,
    Use Css to change the icon style:
    af|treeTable::expanded-icon {
    content: url("/adf/1.gif");//content : none;
    outline: none ;
    af|treeTable::collapsed-icon {
    content: url("/adf/2.gif");//content : none;
    outline: none ;
    af|treeTable::leaf-icon {
    content: url("/adf/3.gif");//content : none;
    outline: none ;
    Regards,
    Raj Gopal K

  • Invalid b-tree node and the disk can't be repaired.  Is it worth the reformat or is the hard drive trashed?  This is a Mac mini, I've had it since 2010 and already had to replace the hard drive once.

    Swapped out the monitor on my Mac mini tonight and it wouldn't start back up.  Managed to boot off the install disk and run disk utility, which gave the invalid b tree node error.  Wasn't able to repair the disk, suggested a reformat.  Is this worth my time?  Or is the disk toasted?  I got it in 2010, it's out of warranty and has already had the hard drive replaced once.  Thanks!
    -laura

    If you want to save the data from the drive, Phoenix might be able to copy (clone) it off on another volume. You can check it out at:
    http://scsc-online.com/Phoenix.html
    Phoenix does a file copying cloning, not block copy cloning, so a new index is generated on the drive when the copy is being made. If none of the files got lost, meaning just the index is screwed up, I would think this would work.
    Regarding the hard drive an index problem isn't a hard drive problem. That hard drive may be in perfect working order, especially since it's fairly new.

  • How to cut, copy and paste a tree node in JTree?????

    Hi, Java GUI guru. Thank you for your help in advance.
    I am working on a File Explorer project with JTree. There are cut, copy and paste item menus in my menu bar. I need three EventAction methods or classes to implements the three tasks. I tried to use Clipboard to copy and paste tree node. But I can not copy any tree node from my tree.
    Are there any body has sample source code about cut, copy, and paste for tree? If possible, would you mind send me your sample source code to [email protected]
    I would appreciate you very very much for your help!!!!
    X.G.

    Hi, Paul Clapham:
    Thank you for your quick answer.
    I store the node in a DefaultMutableTreeNode variable, and assign it to another DefaultMutableTreeNode variable. I set up two classes (CopyNode and PasteNode). Here they are as follows:
    //CopyNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class CopyNode implements ActionListener{
    private TreeList jtree;
    String treeNodeName;
    TreePath currentSelection;
    DefaultMutableTreeNode currentNode;
    public CopyNode(TreeList t){
    jtree = t;
    public void actionPerformed(ActionEvent e){
    currentSelection = jtree.tree.getSelectionPath();
    if(currentSelection != null){
    currentNode = (DefaultMutableTreeNode)(currentSelection.getLastPathComponent());
    treeNodeName = currentNode.toString();
    //PasteNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class PasteNode extends DefaultMutableTreeNode{
    private TreeList jtree;
    CopyNode copyNode;
    public PasteNode(TreeList t){
    jtree = t;
    copyNode = new CopyNode(t);
    public DefaultMutableTreeNode addObject(Object child){
    DefaultMutableTreeNode parentNode = null;
    TreePath parentPath = jtree.tree.getSelectionPath();
    if(parentPath == null){
    parentNode = jtree.root;
    else{
    parentNode = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
    return addObject(parentNode, child, true);
    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible){
    DefaultMutableTreeNode childNode = copyNode.currentNode;
    if(parent == null){
    parent = jtree.root;
    jtree.treemodel.insertNodeInto(childNode, parent, parent.getChildCount());
    if(shouldBeVisible){
    jtree.tree.scrollPathToVisible(new TreePath(childNode.getPath()));
    return childNode;
    I used these two classes objects in "actionPerformed(ActionEvent e)" methods in my tree:
    //invoke copyNode
    copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(copyNode);
    //invoke pasteNode
    pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    pasteName.addObject(copyName.treeNodeName);
    When I run the drive code, making a copy some node from my tree list, I got bunch of error messages.
    Can you figour out what is wrong in my two classes? If you have sample code, would you mind mail me for reference.
    Thank you very much in advance.
    X.G.

  • Tree and Tree Node Components - Threadinar7

    Hi All,
    This is the seventh in the "Threadinar" series , please see Threadinar6 at
    http://forum.sun.com/jive/thread.jspa?threadID=100601 for details
    In this Threadinar we will focus on the
    "Tree" and "Tree Node" Components
    Let us begin our discussion with the Tree Component.
    Tree Component
    You can drag the Tree component from the Palette's Basic category to the Visual Designer to create a hierarchical tree structure with nodes that can be expanded and collapsed, like the nodes in the Outline window. When the user clicks a node, the row will be highlighted. A tree is often used as a navigation mechanism.
    A tree contains Tree Node components, which act like hyperlinks. You can use a Tree Node to navigate to another page by setting its url property. You can also use a Tree Node to submit the current page. If the the Tree Node's action property is bound to an action event handler, selecting the node automatically submits the page. If the Tree Node's actionListener property is bound to an action listener, opening or closing the node automatically submits the page. You set Tree Node properties in the Tree Node Component Properties window.
    * If you use this component to navigate between pages of a portlet, do not use the url property to link to a page. Instead, use the Navigation editor to set up your links to pages.
    * Events related to tree node selection do not work correctly in portlets because the component uses cookies to pass the selected node id back and forth, and cookies are not correctly handled by the portlet container. You cannot handle tree node selection events in portlet projects.
    Initially when you drop a tree on a page, it has one root node labeled Tree and one subnode labeled Tree Node 1. You can add more nodes by dragging them to the tree and dropping them either on the root node to create top level nodes or on existing nodes to create subnodes of those nodes. You can also right-click the Tree or any Tree Node and choose Add Tree Node to add a subnode to the node.
    Additionally, you can work with the component in the Outline window, where the component and its child components are available as nodes. You can move a node from level to level easily in the Outline window, so you might want to work there if you are rearranging nodes. You can also add and delete tree nodes in the Outline window, just as in the Visual Designer.
    The Tree component has properties that, among other things, enable you change the root node's displayed text, change the appearance of the text, specify if expanding or collapsing a node requires a trip to the server, and specify whether node selection should automatically open or close the tree. To set the Tree's properties, select the Tree component in your page and use the Tree Component Properties window.
    The following Tutorial ("Using Tree Component") is very useful to learn using Tree components
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/sitemaptree.html
    See Also the Technical Article - "Working with the Tree Component and Tree Node Actions"
    http://developers.sun.com/prodtech/javatools/jscreator/reference/techart/2/tree_component.html
    Tree Node Component
    You can drag the Tree Node component from the Palette's Basic category to a Tree component or another tree node in the Visual Designer to create a node in a hierarchical tree structure, similar to the tree you see in the Outline window.
    The tree node is created as a subnode of the node on which you drop it. If you drop the node on the tree component itself, a new node is created as a child of the root node. You can see the hierarchical structure clearly in the Outline window, where you can also easily move nodes around and reparent them.
    You can also add a tree node either to a Tree component or to a Tree Node component by right-clicking the component and choosing Add Tree Node.
    A Tree Node component by default is a container for an image and can be used to navigate to another page, submit the current page, or simply open or close the node if the node has child nodes.
    * If you select the Tree Node component's node Tree Node icon in the Outline window, you can edit its properties in the Tree Node Properties window. You can set things like whether or not the Tree Node is expanded by default, the tooltip for the Tree Node, the label for the tree node, and the Tree Node's identifier in your web application.
    * You can use a Tree Node to navigate to another page by setting its url property. You can also use a Tree Node to submit the current page. If the the Tree Node's action property is bound to an action event handler, selecting the node automatically submits the page. If the Tree Node's actionListener property is bound to an action listener, opening or closing the node automatically submits the page.
    - Note: If you use this component to navigate between pages of a portlet, do not use the url property to link to a page. Instead, use the Navigation editor to set up your links to pages. In addition, events related to tree node selection do not work correctly in portlets because the component uses cookies to pass the selected node id back and forth, and cookies are not correctly handled by the portlet container. You cannot handle tree node selection events in portlet projects.
    * If you select the image in the Tree Node, you can see that its icon property is set to TREE_DOCUMENT. If you right-click the image on the page and choose Set Image, you can either change the icon to another one or choose your own image in the Image Customizer dialog box. For more information on working with an image in a tree node, see Image component.
    - Note: The image used in a tree node works best if it is 16x16 or smaller. Larger images can work, but might appear overlapped in the Visual Designer. You can right-click the component and choose Preview in Browser feature to check the appearance of the images.
    Please share your comments, experiences, additional information, questions, feedback, etc. on these components.
    ------------------------------------------------------------------------------- --------------------

    One challenge I had experience was to make the tree
    always expanded on all pages (I placed my tree menu
    in a page fragment so I can just import it in my
    pages).Did you solve this problem. It would be interesting to know what you did.
    To expand a node you call setExpanded on the node. Here is some code from a tutorial that a coworker of mine is working on.
    In the prerender method:
           Integer expandedPersonId = getRequestBean1().getPersonId();
             // If expandedPersonId is null, then we are not coming back
            // from the Trip page. In that case we do not want any trip
            // nodes to be pre-selected (highlighted) due to browser cookies.
            if (expandedPersonId==null) {
                try {
                    HttpServletRequest req =(HttpServletRequest)
                    getExternalContext().getRequest();
                    Cookie[] cookies = req.getCookies();
                    //Check if cookies are set
                    if (cookies != null) {
                        for (int loop =0; loop < cookies.length; loop++) {
                            if (cookies[loop].getName().equals
                                    ("form1:displayTree-hi")) {
                                cookies[loop].setMaxAge(0);
                                HttpServletResponse response =(HttpServletResponse)
                                getExternalContext().getResponse();
                                response.addCookie(cookies[loop]);
                } catch (Exception e) {
                    error("Failure trying to clear highlighting of selected node:" +
                            e.getMessage());
            }                  ... (in a loop for tree nodes)...
                      personNode.setExpanded(newPersonId.equals
                                    (expandedPersonId));In the action method for the nodes:
           // Get the client id of the currently selected tree node
            String clientId = displayTree.getCookieSelectedTreeNode();
            // Extract component id from the client id
            String nodeId = clientId.substring(clientId.lastIndexOf(":")+1);
            // Find the tree node component with the given id
            TreeNode selectedNode =
                    (TreeNode) this.getForm1().findComponentById(nodeId);
            try {
                // Node's id property is composed of "trip" plus the trip id
                // Extract the trip id and save it for the next page
                Integer tripId = Integer.valueOf(selectedNode.getId().substring(4));
                getRequestBean1().setTripId(tripId);
            } catch (Exception e) {
                error("Can't convert node id to Integer: " +
                        selectedNode.getId().substring(4));
                return null;
    It would also be great if I can set the tree
    readonly where the user cannot toggle the expand
    property of the tree (hope this can be added to the
    tree functionality).

  • Hierarchical tree node problem

    Hi all --
    Today's problem is (drum roll)............
    My application uses a heirarichal tree where each tree node contains the name of a form within this system. The user can navigate from form to form by clicking the appropriatetly name tree node. This seems to work - sometimes. Some users click on a node for one form, but get transferred to another named form(usually the one above or below the one actually activated). I've also found out that this happens ONLY when the user has their screen resolution set to 800 x 600. This application was developed at screen resolution 1024 x 768 and it woks fine. Anybody know why??

    Here is the code for both the tree node selected and tree node activated triggers
    Tree Node Seleceted code:
    :CONTROL.Node_Activated := null ;
    :CONTROL.Node_Selected := Ftree.Get_Tree_Node_Property('CONTROL_TREE.MENU', :SYSTEM.TRIGGER_NODE, Ftree.NODE_VALUE) ;
    ===========================================================
    Tree Node Activated code:
    Declare
    LN$I Pls_integer ;
    Begin
    :CONTROL.Node_Selected := null;
    :CONTROL.Node_Activated := Ftree.Get_Tree_Node_Property('CONTROL_TREE.MENU', :SYSTEM.TRIGGER_NODE, Ftree.NODE_VALUE) ;
    If :CONTROL.Node_Activated IS NOT NULL Then
    if :GLOBAL.curr_proc_id <> :control.node_activated or :control.node_activated
    is null then                          
    CALL_FORM(:CONTROL.Node_Activated);     
    else
    Set_Alert_Property( 'AL_FORM_OPENED', ALERT_MESSAGE_TEXT,
    :CONTROL.Node_Activated || ' is already opened. Please check your current or previously opened library.' );
    LN$I := Show_Alert( 'AL_FORM_OPENED' ) ;
    end if;          
    end if ;
    end ;

  • Setting Dialog, Tree Node and Menu Font in JDeveloper 11.1.1.4/11.1.1.5

    Hi,
    I'm near sighted and thus dependent on being able to choose larger fonts. For the code editor, this poses no problem. For the widgets in the views surrounding the editor (containing tree nodes) and dialogs (with the Preferences dialog being one example), the font is very small at high screen resolutions (I don't want to resort to a lower resolution since I would like the fonts to appear as detailed as possible).
    Is there any way to override the menu, tree node, and dialog font via command line switches and/or property/config files during JDeveloper startup in a platform independent way?
    If it can't be done platform independently, what are the necessary steps on Linux (probably for the GTK lib) and Windows?
    Thanks in advance!
    Kind regards,
    Holger

    I previously developed under full screen option and my PC resolution was 1600x1200. But when the application was ran on other screens it was displaying with some page contents being cut out. It was due to other machines running on lower resoultion. I will need now redesign the pages to run on user defined lower resolution of 1280x1024. How do I setup Jdeveloper design tab to show for 1280x1024.
    Thanks
    Edited by: user5108636 on Feb 14, 2011 5:23 PM

Maybe you are looking for