Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.gui > #1428

Re: Default JTree Icons

From "Ed Tidwell" <ed.tidwell@THRWHITE.remove-dii-this>
Subject Re: Default JTree Icons
Message-ID <461bdeb9$0$17147$4c368faf@roadrunner.com> (permalink)
Newsgroups comp.lang.java.gui
References <1175902600.951614.234410@d57g2000hsg.googlegroups.com>
Date 2011-04-27 15:33 +0000
Organization TDS.net

Show all headers | View raw


  To: comp.lang.java.gui
Daniel Pitts wrote:
> On Apr 6, 12:16 pm, "Jason Cavett" <jason.cav...@gmail.com> wrote:
>> I have a JTree whose icons I have changed through my own tree cell
>> renderer (which extends DefaultTreeCellRenderer).  I overrode the
>> method: Component getTreeCellRendererComponent.
>>
>> For the most part, the renderer works.  The icons are changed based on
>> whether they're a leaf or an open/closed parent...except in one
>> situation.
>>
>> My tree has the ability to be edited by right clicking on the tree and
>> choosing the "Rename" option from a drop down menu.  This allows the
>> user to change the name of the node directly in the tree.  When the
>> tree enters an "editable" state - it gets the default L&F icon (a gray
>> dot or the open/closed folder).  I cannot, for the life of me, figure
>> out how to set my own icon during the editing process.  It doesn't
>> seem like it should be any different to me, but, I seem to be wrong.
>>
>> Any help/advice would be much appreciated.  Thanks.
> 
> I think you need to change the TreeCellEditor as well.
> 

You can still have a problem when in the 'edit' mode if you do custom 
editing.  The reason is the default 'offset' for the JTextfield edit box 
doesn't get set correctly.  This was in 1.4 and I haven't checked to 
mess with 1.5 or 1.6.

Feel free to use this JTree code snippets.  It should help get down the 
right path.

public class RollupTree extends JTree implements Mediatable {

    // used for auto scrolling with mouse Drag action
    Insets autoscrollInsets = new Insets(20, 20, 20, 20);

    // mediatable key for hash lookup
    public static final String KEY = "Admin RollupTree";

    // USED by renderers for JTable and JTree to render names
    public static final Color NEW = Color.BLUE; //new Color(64, 128, 
128); // blue green
    public static final Color DIRTY = Color.MAGENTA;
    public static final Color DELETED = Color.RED;

    // allow way to build this comoponent without registering with mediator
    private boolean _mediated = true;

    /**
     * Create the default Rollup Tree that is registered and mediated with
     * the Admin Rollup Mediator.
     *
     * Call RollupTree(false) to create an instance that does not hook into
     * the Rollup Mediator.
     */
    public RollupTree() {
       this(true);
    }

    /**
     * Create a plain jane legal entity tree with no bells or whistles
     * @param mediated boolean
     */
    public RollupTree(final boolean mediated) {
       // legal as of JDK 1.4
       // creates an empty JTree
       super((TreeNode)null);
       _mediated = mediated;
       setShowsRootHandles(true);
       init();
       // add so we can mediate this control
       if (_mediated) {
          AdminRollupMediator.add(this);
       }
    }

    private void init() {
       // allow them to directly edit nodes
       setEditable(true);

       // allow drag and drop
       new DefaultTreeTransferHandler(this, DnDConstants.ACTION_MOVE);

       // turn on tooltips
       ToolTipManager.sharedInstance().registerComponent(this);

       // used by two setters so create reference
       RollupTreeCellRenderer renderer = new RollupTreeCellRenderer();

       // customizing the icons for the tree
       // setting the folder icons
       // renderer.setOpenIcon(IconLoader.getIcon("Open.gif"));
       // renderer.setClosedIcon(IconLoader.getIcon("Folder.gif"));
       renderer.setLeafIcon(null); // drop the icon

       // add renderer to highlight Inventory nodes with Red or Blue text
       setCellRenderer(renderer);

       // set the editor
       setCellEditor(new RollupTreeEditor(this, renderer));

       // set UI to over ride editing event method
       setUI(new CustomUI());

       // add tree selection listener
       addTreeSelectionListener(new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent e) {
             AdminRollupMediator.getInstance().treeSelection(e.getPath());
          }
       });

       // add mouse listeners
       addMouseListeners(this);
    }





class RollupTreeCellRenderer extends DefaultTreeCellRenderer {

    /**
     * Configures the renderer based on the passed in components.
     * The value is set from messaging the tree with
     * <code>convertValueToText</code>, which ultimately invokes
     * <code>toString</code> on <code>value</code>.
     * The foreground color is set based on the selection and the icon
     * is set based on leaf and expanded.
     *
     * @param tree JTree
     * @param value Object
     * @param sel boolean
     * @param expanded boolean
     * @param leaf boolean
     * @param row int
     * @param hasFocus boolean
     * @return Component
     */
    public Component getTreeCellRendererComponent(JTree tree, Object 
value, boolean sel, boolean expanded, boolean leaf,
                                                  int row, boolean 
hasFocus) {

       // call super for default behavior
       super.getTreeCellRendererComponent(tree, value, sel, expanded, 
leaf, row, hasFocus);

       // cast to our wrapper Node class
       RollupNode node = (RollupNode) value;

       // get the value and if signed off change change the text to bold
       String stringValue = tree.convertValueToText(value, sel, 
expanded, leaf, row, hasFocus);
       if (node.isSignedOff()) {
          setText("<html> <b> " + stringValue + "</b> *");
       } else {
          setText(stringValue);
       }

       if (node.isTrader()) {
          setIcon(IconLoader.getIcon("Trader.png"));
       }

       if (node.isRoot()) {
          setIcon(null);
       }

       if (node.isLegalEntity()) {
          setToolTipText("Legal Entity ID = [" + node.getId() + "]");
       } else {
          // default tooltip for nodes in the Rollup Tree
          if (node.isSignedOff()) {
             if (node.isInventory()) {
                setToolTipText("ID = [" + node.getId() + "] " + 
node.getInventory().getSignedOffComment());
             } else {
                setToolTipText("ID = [" + node.getId() + "] has been 
signed off on.");
             }
          } else {
             setToolTipText("ID = [" + node.getId() + "]");
          }

       }

       // set colors if node is NOT selected
       if (node.isDeleted()) {
          setToolTipText("Deleted " + node.getTypeName());
          if (!sel) {
             setForeground(RollupTree.DELETED);
          }
       } else if (node.isNew()) {
          setToolTipText("New " + node.getTypeName());
          if (!sel) {
             setForeground(RollupTree.NEW);
          }
       } else if (node.isDirty()) {
          setToolTipText("Modified " + node.getTypeName());
          if (!sel) {
             setForeground(RollupTree.DIRTY);
          }
       }
       return this;

    }


} // Renderer


class RollupTreeEditor extends DefaultTreeCellEditor {
    public RollupTreeEditor(final JTree tree, final 
RollupTreeCellRenderer renderer) {
       super(tree, renderer);
    }


    protected void determineOffset(JTree tree, Object value, boolean 
isSelected, boolean expanded, boolean leaf, int row) {

       if (renderer != null) {
          RollupNode node = (RollupNode) value;
          if (node.isRoot()) {
             editingIcon = null; // no icon for ROOT node
          } else if (node.isDesk() || node.isLegalEntity()) {
             if (expanded) {
                editingIcon = UIManager.getIcon("Tree.openIcon");
             } else {
                editingIcon = UIManager.getIcon("Tree.closedIcon");
             }
          } else if (node.isTrader()) {
             editingIcon = IconLoader.getIcon("Trader.png");
          } else {
             // leaf nodes are null
             editingIcon = null;
          }

          if (editingIcon != null) {
             offset = renderer.getIconTextGap() + 
editingIcon.getIconWidth();
          } else {
             offset = renderer.getIconTextGap();
          }

       } else { // else renderer == null
          editingIcon = null;
          offset = 0;
       }
    }

    /**
     * Allow people to toggle the icon when in edit mode
     *
     * @param editor Icon
     */
    public void setEditorIcon(Icon editor) {
       editingIcon = editor;
    }

    /**
     * If the <code>realEditor</code> returns true to this
     * message, <code>prepareForEditing</code>
     * is messaged and true is returned.
     * @param event EventObject
     * @return boolean
     */
    public boolean isCellEditable(EventObject event) {

       if (event instanceof MouseEvent) {
          // double click for edit
          if (((MouseEvent) event).getClickCount() == 2) {
             return true;
          }
       }
       return false;
    }

    public DefaultTextField getEditor() {
       return (DefaultTextField)this.editingComponent;
    }
}


class CustomUI extends BasicTreeUI {
    protected boolean startEditing(TreePath path, MouseEvent event) {
       // default to standard behavior
       boolean result = super.startEditing(path, event);

       // start editing this node?
       if (result) {
          // start peeling the object to get a handle to the editor
          RollupTree rollupTree = (RollupTree) event.getSource();
          RollupTreeEditor editor = (RollupTreeEditor) 
rollupTree.getCellEditor();

          JTextField textField = editor.getEditor();
          // they want to default so that the edit text
          // is in selected mode when they first start to edit the field
          textField.selectAll();
       }

       return result;
    }
}

---
 * Synchronet * The Whitehouse BBS --- whitehouse.hulds.com --- check it out free usenet!
--- Synchronet 3.15a-Win32 NewsLink 1.92
Time Warp of the Future BBS - telnet://time.synchro.net:24

Back to comp.lang.java.gui | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Default JTree Icons "Jason Cavett" <jason.cavett@THRWHITE.remove-dii-this> - 2011-04-27 15:33 +0000
  Re: Default JTree Icons "Daniel Pitts" <daniel.pitts@THRWHITE.remove-dii-this> - 2011-04-27 15:33 +0000
    Re: Default JTree Icons "Ed Tidwell" <ed.tidwell@THRWHITE.remove-dii-this> - 2011-04-27 15:33 +0000

csiph-web