EditingComponent in TreeCellEditor 1.2 to 1.5

I have inherited some code and am faced with making a few changes and making sure it works with 1.5. It currently works with 1.2. I have a custom DefaultTreeCellEditor as shown below in part. In 1.5 editingComponent is null, so of course the call to addKeyListener fails. Whereas in 1.2 it is not. Looking at the source for DefaultTreeCellEditor I see that editingComponent gets set in DefaultTreeCellEditor.getTreeCellEditorComponent. So it appears that getTreeCellEditorComponent is not being called in 1.5. This Bug, http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4280388, mentions getTreeCellEditorComponent, but I have not been able to figure out what I need to do, or stop doing, in order to have getTreeCellEditorComponent called for me.
Any help would be appreciated.
class SetupTreeCellEditor extends DefaultTreeCellEditor implements SetupEditorResources
  private static CellFocusListener  cellFocusHandler;
  private static CellKeyListener    cellKeyHandler;
  private static boolean            isEditingStopped = false;
  private static DefinitionCell     definitionCell;
  private static DefinitionNode     editingNode;
  private static String             oldCellName;
  private static String             newCellName;
  SetupTreeCellEditor(JTree tree, DefaultTreeCellRenderer cellRenderer)
    super(tree, cellRenderer);
    cellFocusHandler = new CellFocusListener();
    cellKeyHandler = new CellKeyListener();
  public boolean isCellEditable( EventObject event )
    DefinitionNode node = (DefinitionNode)tree.getLastSelectedPathComponent();
    if ( node == null )
      node = (DefinitionNode)tree.getModel().getRoot();
    return (node.isEditableNode() ? super.isCellEditable(event) : false);
  protected void prepareForEditing()
    super.prepareForEditing();
    editingNode = (DefinitionNode)tree.getLastSelectedPathComponent();
    definitionCell = editingNode.getDefinitionCell();
    oldCellName = definitionCell.getCellName();
    editingComponent.addKeyListener(cellKeyHandler);
    editingComponent.addFocusListener(cellFocusHandler);
    isEditingStopped = false;
.......snip........

This post http://forum.java.sun.com/thread.jspa?forumID=57&threadID=404172 indicates that getTreeCellEditorComponent will not be called unitl isCellEditable returns true. But isCellEditiable is what calls prepareForEditing.
The effort of getting a cell into edit mode, that is the clicks it takes to get there, runs through this code several times until edit conditions are right. One such condition is the existance of a valid editingComponent. So a if (editingComponent != null) wrapper was necessary to solve my problem.
The larger question remains though. What changed from 1.2 to 1.5 that made this necessary? And perhaps further, is prepareForEditing really the right place to add liteners to the editingComponent. A few more things to think about.... getTreeCellEditorComponent doesn't return the editingComponent rather it returns an instance of EditorContainer which contains editingComponent. And, both getTreeCellEditorComponent and isCellEditiable call prepareForEditing. That doesn't seem right, alas I haven't scoured the details.

Similar Messages

  • How to start TreeCellEditor apart from default behaviors

    Hi,
    I'm trying to find the way to start TreeCellEditor apart from default behaviors which are triple mouse click, click-pause-click and F2 (in Windows).
    The only way I found for starting editor in tree is JTree.startEditingAtPath. However the problem is I designed to separate the action(model) from the tree (view). So In my action class, it knows only TreeModel but not JTree.
    How could I set my action class to tell the JTree to start editor? Is there any approach to do so but do not break my design?
    Thanks in advance.

    I had to do a custom JTree to get my editor to work the way you wanted.
    I needed mine to allow a double mouse click. Then when in edit mode have the text default to a 'select all'.
    All of the 'Rollup' items are custom objects but this should give you an idea of what to do.
    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();
                // set Icon if node a trader
                RollupNode node = (RollupNode) rollupTree.getSelectionPath().getLastPathComponent();
                if (node.isTrader()) {
                    editor.setEditorIcon(IconLoader.getIcon("Trader.png"));
                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;
        }I also did a custom default editor which looks like:
    class RollupTreeEditor extends DefaultTreeCellEditor
        public RollupTreeEditor(final JTree tree, final RollupTreeCellRenderer renderer) {
            super(tree, renderer);
         * 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;
    }Then in my custom JTree I set these up like...
            // 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());A nice touch is to add a mouse listener so if the user clicks out of the editor it cancels the edit mode. So here is the simple call:
            tree.addMouseListener(new MouseAdapter()
                public void mouseClicked(MouseEvent e) {
                    // get handle to tree
                    RollupTree tree = (RollupTree) e.getSource();
                    // exit editor if in edit mode
                    tree.getCellEditor().stopCellEditing();
                public void mouseReleased(MouseEvent e) {
                    if (e.isPopupTrigger()) {
                        menu.show(e.getComponent(), e.getX(), e.getY());
            });Does this help answer your question?

  • JTree Selection Behavior with Custom TreeCellEditor

    I've recently had the need to build a custom TreeCellEditor with a JTree that allows single path selection. I've toyed around with it but don't understand it. When a node is clicked, the editor takes over rendering/handling the cell, and a TreeSelectionEvent is fired from the tree, but the isSelected boolean value passed to the TreeCellEditor is initially false. Then on a second click of the same path in the tree, no TreeSelectionEvent is fired, but the isSelected boolean value is true. It's as if the tree selection is occuring after the editor renders the cell. I would like the cell to appear selected on the first click. Can anyone shed some light on why this is happening and how I can fix it?
    I included some code to demonstrate the problem below (though no actual editing takes place; the test code is only to demonstrate how the cells only appear selected with a yellow background after the second click of the same cell; note also that the valueChanged only executes on the first click). This test was run on Windows with Java 1.5.
    public class TestTreeCellEditor extends JLabel implements TreeCellEditor {
         private String st;
         public TestTreeCellEditor() {
              setOpaque(true);
         public Component getTreeCellEditorComponent(JTree tree, Object value,
                   boolean isSelected, boolean expanded, boolean leaf, int row) {
              this.st = value.toString();
              setBackground(isSelected? Color.YELLOW : Color.WHITE);
              setText(st);
              return this;
         public void addCellEditorListener(CellEditorListener l) {
              // not important for test
         public void cancelCellEditing() {
              this.st = null;
         public Object getCellEditorValue() {
              return st;
         public boolean isCellEditable(EventObject anEvent) {
              return true;
         public void removeCellEditorListener(CellEditorListener l) {
              // not important for test
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
         public boolean stopCellEditing() {
              return true;
    public class TestTreeCellEditorFrame extends JFrame implements TreeSelectionListener {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        launchGUI();
         private static void launchGUI() {
              TestTreeCellEditorFrame frame = new TestTreeCellEditorFrame();
              JPanel treePanel = new JPanel();
              DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node");
              DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("Child 1");
              rootNode.add(childNode);
              childNode = new DefaultMutableTreeNode("Child 2");
              rootNode.add(childNode);
              JTree testTree = new JTree(rootNode);
              testTree.addTreeSelectionListener(frame);
              testTree.setCellEditor(new TestTreeCellEditor());
              testTree.setEditable(true);
              testTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              treePanel.add(testTree);
              frame.setContentPane(treePanel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(600,400);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public void valueChanged(TreeSelectionEvent event) {
              TreePath path = event.getNewLeadSelectionPath();
              if (path != null) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                   System.out.println("TreeSelectionEvent on " + node.getUserObject().toString());
    }

    Since my last post, I decided that I do want to be able to edit a cell that is not selected. In particular, when using a tree with checkboxes. What I'm doing for the time being, which works well enough, is to highlight the cell based on the isSelected value in combination with calling tree.stopEditing() in a TreeSelectionListener valueChanged method. This is somewhat of a hack solution, and has the side effect of a cell not appearing selected until the mouseReleased event. I'm still looking for a better solution, but for now it works well enough.

  • TreeCellEditor and isCellEditable method

    I'm confused about how to handle tree cell edits. See the example program below. As you click around the tree, note that the isCellEditable method is called on the cell you are leaving, and not on the cell you are going to. This causes the cell you are going to to be rendered with the editor of the cell you are coming from. There is something I'm missing. What is it?
    What I thought would happen:
    1) isCellEditable called on cell you are going to
    2) if isCellEditable returns true, the editor is used to render the cell, otherwise the renderer is used.
    What is happening:
    1) isCellEditable called on the cell you are coming from. (perhaps this test is done to see if valueForPathChanged should be called on the model?)
    2) ????
    Example code:
    public class TestTreeCellEditor extends AbstractCellEditor implements TreeCellEditor {
         private JLabel label = new JLabel();
         @Override
         public Component getTreeCellEditorComponent(JTree tree, Object value,
                   boolean isSelected, boolean expanded, boolean leaf, int row) {
              label.setText(((DefaultMutableTreeNode) value).getUserObject().toString());
              return label;
         @Override
         public Object getCellEditorValue() {
              return label.getText();
         @Override
         public boolean isCellEditable(EventObject e) {
              TreePath path = ((JTree) e.getSource()).getSelectionPath();
              if (path != null) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                   String nodeText = node.getUserObject().toString();
                   System.out.println("Testing node with text \"" + nodeText + "\"");
                   return nodeText.indexOf("NOT") < 0;
              return false;
    public class TestTreeEditBehavior {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        launchUI();
         private static void launchUI() {
              JFrame frame = new JFrame("Test Tree Edit Behavior");
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("NOT Editable");
              root.add(new DefaultMutableTreeNode("I'm editable."));
              root.add(new DefaultMutableTreeNode("Me too!  I can be edited."));
              DefaultTreeModel model = new DefaultTreeModel(root);
              JTree tree = new JTree(model);
              tree.setCellEditor(new TestTreeCellEditor());
              tree.setEditable(true);
              JPanel panel = new JPanel();
              panel.add(tree);
              frame.setContentPane(panel);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }What I expect to happen and what actually happens are obviously not the same. What am I supposed to be doing?

    Okay...here is how it looks to me:
    What happens when you need to write your own custom TreeCellEditor?
    TreeCellEditor requires the following methods:
        public abstract Component getTreeCellEditorComponent(JTree jtree, Object obj, boolean flag, boolean flag1, boolean flag2, int i);
        public abstract Object getCellEditorValue();
        public abstract boolean isCellEditable(EventObject eventobject);
        public abstract boolean shouldSelectCell(EventObject eventobject);
        public abstract boolean stopCellEditing();
        public abstract void cancelCellEditing();
        public abstract void addCellEditorListener(CellEditorListener celleditorlistener);
        public abstract void removeCellEditorListener(CellEditorListener celleditorlistener);However, you can probably get away with AbstractCellEditor handling most of the work. With AbstractCellEditor extended, you then only need to implement two methods:
        public abstract Component getTreeCellEditorComponent(JTree jtree, Object obj, boolean flag, boolean flag1, boolean flag2, int i);
        public abstract Object getCellEditorValue();However, you may still want to override some of the methods AbstractCellEditor handles for you. For example, AbstractCellEditor always returns true from the isCellEditable method. If you cells are not always editable, you will want to override this method.
    You will note, however, using AbstractCellEditor you lose certain things provided by the DefaultTreeCellEditor. For example, fields are edited automatically on selection (if editable) rather than using the more complex behavior of the DefaultTreeCellEditor (triple-click or click-pause-click), and icons for the tree will be missing. You can reimplement this behavior on your own, but there is a potentially better approach. One of the DefaultTreeCellEditor constructors takes a TreeCellEditor as an argument. Pass your custom TreeCellEditor to this constructor, and you get the DefaultTreeCellEditor behaviors back (assuming you didn't already override them).
    More about isCellEditable
    When you ask whether or not a cell is editable, you are really asking two questions:
    1) Is the cell editable?
    2) Should the editor be activated given the user actions? (e.g. double-click, triple-click, etc)
    Your cell editor should answer question 1 (AbstractCellEditor always returns true). The DefaultTreeCellEditor answers question 2. If you do not use the DefaultTreeCellEditor, then you should also answer question 2.
    An odd happenstance of the DefaultTreeCellEditor is it's click-pause-click behavior to activate the editor. When this happens, the second click causes isCellEditable to be called again with a null EventObject (at least with Java 1.6.0_20-b02). If we assume this is the only time the EventObject will be null, you should probably just return true when the EventObject is null. Unless you wanted to specifically disable the click-pause-click behavior, in which case you could return false. But either way, make sure you check the EventObject for a null value.

  • Selection on single-click with custom TreeCellEditor

    Hi,
    In a JTree with a custom treecell editor (contains checkbox, label with icon) that overrides abstractcelleditor, selection of nodes does not highlight the selection on a single click. The selection is highlighted on a double click. clicking on the checkbox works fine. any ideas? the treecellrenderer works fine. So if i remove the custom editor and only have the renderer (for checkbox, label and icon) selections are highlighted properly.
    Thanks!

    Ok, came up with a solution - it makes keyboard navigation and mouse-based multiple selection work. Here's the fixed code:
    creating the tree :
    JTree tree = new JTree( root  );
    tree.setUI( new MyTreeUI() );
    tree.setCellRenderer( new OverlayTreeCellRenderer() );
    tree.setCellEditor( new OverlayTreeCellRenderer() );
    tree.setEditable(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setInvokesStopCellEditing( true );
    scrollPane.setViewportView( tree );
    add( scrollPane );the renderer / editor:
      protected static class OverlayTreeCellRenderer extends JPanel implements TreeCellRenderer, TreeCellEditor
        protected Color selBdrColor = UIManager.getColor( "Tree.selectionBorderColor" );
        protected Color selFG = UIManager.getColor( "Tree.selectionForeground" );
        protected Color selBG = UIManager.getColor( "Tree.selectionBackground" );
        protected Color txtFG = UIManager.getColor( "Tree.textForeground" );
        protected Color txtBG = UIManager.getColor( "Tree.textBackground" );
        protected JCheckBox visibleCheckBox = new JCheckBox();
        protected JLabel overlayName = new JLabel();
        protected JCheckBox showLabelCheckBox = new JCheckBox();
        protected LinkedList<CellEditorListener> listeners = new LinkedList<CellEditorListener>();
        protected final ActionListener checkBoxListener = new ActionListener() {
          public void actionPerformed ( ActionEvent ae )
            if ( stopCellEditing() )
              fireEditingStopped();
        protected final MouseListener labelListener = new MouseAdapter() {       
          public void mouseReleased ( MouseEvent e )
            if ( stopCellEditing() )
              fireEditingStopped();
         * Constructor.
        public OverlayTreeCellRenderer ()
          setLayout( new BoxLayout( this, BoxLayout.LINE_AXIS ) );
          visibleCheckBox.setOpaque( false );
          showLabelCheckBox.setOpaque( false );
          add( visibleCheckBox );
          add( overlayName );
          add( showLabelCheckBox );
          setBackground( txtBG );
          setForeground( txtFG );     
          visibleCheckBox.addActionListener( checkBoxListener );
          showLabelCheckBox.addActionListener( checkBoxListener );
          overlayName.addMouseListener( labelListener );
         * Returns the renderer
        public Component getTreeCellRendererComponent ( JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row,
            boolean hasFocus )
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;           
          OverlayDescriptor data = (OverlayDescriptor) node.getUserObject();
          overlayName.setText( data.overlayName );
          visibleCheckBox.setSelected( data.visible );
          showLabelCheckBox.setSelected( data.label );   
          if ( selected )
            setBackground( selBG );
            setForeground( selFG );
          else
            setBackground( txtBG );
            setForeground( txtFG );
          return this;
        // ------------------------------------------------- Cell Editor
        // Returns the editor
        public Component getTreeCellEditorComponent ( JTree tree, Object value,
            boolean isSelected, boolean expanded, boolean leaf, int row )
          return getTreeCellRendererComponent( tree, value, true, expanded, leaf, row, true );
        // Implement the CellEditor methods.
        public void cancelCellEditing ()
        // Stop editing only if the user entered a valid value.
        public boolean stopCellEditing ()
          requestFocusInWindow();
          return true;
        // This method is called when editing is completed.
        // It must return the new value to be stored in the cell.
        public Object getCellEditorValue ()
          return new OverlayDescriptor( overlayName.getText(), showLabelCheckBox.isSelected(), visibleCheckBox.isSelected() );
        // Start editing when the mouse button is clicked.
        public boolean isCellEditable ( EventObject eo )
          return true;
        public boolean shouldSelectCell ( EventObject eo )
          return true;
        // Add support for listeners.
        public void addCellEditorListener ( CellEditorListener cel )
          listeners.add( cel );
        public void removeCellEditorListener ( CellEditorListener cel )
          listeners.remove( cel );
        protected void fireEditingStopped ()
          if ( listeners.size() > 0 )
            ChangeEvent ce = new ChangeEvent( this );
            for ( CellEditorListener l : listeners )
              l.editingStopped( ce );
      }subclass of BasicTreeUI:
       * Fix multiple-selection handling in BasicTreeUI which doesn't appear to work
       * when the tree has a custom editor.
      protected static class MyTreeUI extends BasicTreeUI {   
        protected boolean startEditing ( TreePath path, MouseEvent event )
           * BasicTreeUI startEditing(..) method doesn't handle multiple selection
           * well. This circumvents that for when Ctrl or Shift is held down by
           * first saving the current selection, and then restoring it after calling
           * super.startEditing(..).
          ArrayList<TreePath> selectedPaths = null;
          if ( tree.getSelectionCount() > 0 && event.isControlDown() )
            selectedPaths = new ArrayList<TreePath>( tree.getSelectionCount() + 1 );
            for ( TreePath p : tree.getSelectionPaths() )
              selectedPaths.add( p );
            if ( !tree.isPathSelected( path ) )
              selectedPaths.add( path );
            else
              selectedPaths.remove( path );
          else if ( tree.getSelectionCount() > 0 && event.isShiftDown() )
            int endRow = tree.getRowForPath( path );
            int startRow = tree.getAnchorSelectionPath() == null ? endRow : tree
                .getRowForPath( tree.getAnchorSelectionPath() );
            if ( startRow > endRow )
              int temp = endRow;
              endRow = startRow;
              startRow = temp;
            selectedPaths = new ArrayList<TreePath>( endRow - startRow + 1 );
            for ( int row = startRow; row <= endRow; row++ )
              selectedPaths.add( tree.getPathForRow( row ) );
          boolean val = super.startEditing( path, event );
          if ( selectedPaths != null )
            tree.setSelectionPaths( selectedPaths.toArray( new TreePath[0] ) );
          return val;
      };

  • Modifying my TreeCellRenderer to use as a TreeCellEditor

    Hi
    I would like to know what I need to do different from my TreeCellRenderer when I am creating a TreeCellEditor.
    I want to be able to edit JTables that are leaf nodes of a JTree.
    Here is my TreeCellRenderer code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.event.*;
    import java.lang.*;
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer
    JTable table = null;
    public MyTreeCellRenderer( JTable table)
    super();
    this.table = table;
    updateUI();
    public Component getTreeCellRendererComponent(JTree tree, Object value,boolean selected, boolean expanded,boolean leaf, int row,boolean hasFocus)
    super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
    if ( leaf )
    Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
    if ( userObject instanceof JTable ) {
    JTable pnlLeaf = (JTable)userObject;
    pnlLeaf.repaint();
    pnlLeaf.validate();
    return pnlLeaf;
    return this;
    }

    Can anyone help here?
    Thanks

  • TreeCellEditor with Checkbox

    hi
    i'm tryin to create a treecelleditor to check or uncheck my treenode.
    it works fine at all, but i want to activate the editor only then, when the user clicks into a specific region (the region where the checkbox is).
    i've tried this like following:
            public boolean isCellEditable(EventObject anEvent) {
                boolean editable = false;
                if(anEvent instanceof MouseEvent) {
                    MouseEvent me = (MouseEvent)anEvent;
                    if(me.getClickCount() == 1) {
                        Point p = SwingUtilities.convertPoint((Component)me.getSource(), me.getPoint(), this);
                        System.out.println(p);
                        System.out.println(this.getX() + "," + this.getY());
                        System.out.println(this.getWidth() + "," + this.getHeight());
                        if((p.getX() >= checkBox.getX()) && (p.getX() <= (checkBox.getX()+checkBox.getWidth()))
                        && (p.getY() >= checkBox.getY()) && (p.getY() <= (checkBox.getY()+checkBox.getHeight()))) {
                            editable = true;
                return editable;
            }now, the problem seems to be that the editor is not yet initialised in its size and location when isCellEditable is called... so SwingUtilities has no chance to calculate the new mousecursor position.
    does anybody have an idea how to solve this problem?
    thx & greetz
    swissManu

    Do you have one checkbox or one on each line ?
    What I do when I want to know if something is clicked on a Tree line is to:
    Register to receive the mouseClicked() on the tree.
    When the mouse is clicked you receive a message.
    Determine the line clicked on.
    Check to see if it has your checkbox in it.
    If it has and the x position of the mouse clicked is close enough then check box is selected or de-selected.
    I have this working for multiple different types of lines with icons for buttons and differing actions depending on the instanceof of the object on the line and the X pos received.

  • Strange behaviour TreeCellEditor#stopCellEditing

    Hi,
    I want to check the input of the user when editing nodes in a JTree.
    Therefore I wrote my own TreeCellEditor extends DefaultTreeCellEditor and
    have overwritten method stopCellEditing. When I enter an invalid value, I
    can not stop editing by clicking outside the node. This works fine. BUT,
    when I press ENTER, the editing is finished.
    What do I have to do to fix this?
    Thanks a lot,
    Jens
    Jens Kutschke
    http://www.j-dimension.com

    Sarah, to help the knowlegable users here please advise which model G5 iMac you have & include this info in your system info preference by clicking on the "My Settings" link in the right hand column.-->
    This way, you won't have to keep repeating yourself and the knowlegable users will be able to provide you with the correct trouble shooting information/solutions if the problem is your computer.
    Also, it will be helpful if you will advise which version of Word, Photoshop you have, which email program & the type of printer you are using.
    Thank you.

  • TreeCellEditor using a JFileChooser

    Hey,
    I have a problem with a JTree. In my tree I'd like some nodes to be editable
    (others not) in a way, that if someone tripple-clicks the cells, a JFileChooser pops up. I implemented it like, the cell editor starts a JFileChooser and returns a JTextField containing the filepath resulting from the JFileChooser.
    My problem is, that I always have to confirm the JTextField again after I already chose the file via JFileChooser. I'd like the JTextField to simply accept the file and stop any editing process on that cell. Unfortunately a call to stopCellEditing() - even tree.stopEditing() didn't work. Is there a possibility to have the JTextField confirmed or is there another way to use the JFileChooser for cell editing in a JTree?
    The TreeCellEditor is derrived from DefaultTreeCellEditor. LeafFileChooser extends Node, my class for nodes. My problem mainly is in this method:
    class TestSettingsCellEditor extends DefaultTreeCellEditor {
         private JTextField tf;
         private String szFcTermination;
         private Component comSelected;
         public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
              cancelCellEditing();
              Node node = (Node) value;
              if(node instanceof LeafComboBox){
              }else if(node instanceof LeafFileChooser){
                   JFileChooser fc = FileIO.getFileChooser(".xml");
                   tf = new JTextField(20);
                   tf.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             stopCellEditing();
                   File file = fc.getSelectedFile();
                   if((file == null)
                             || (!file.getAbsolutePath().endsWith(".xml"))
                             || (!file.exists())){
                        tf.setText("N/A");
                   }else{
                        tf.setText(file.getAbsolutePath());
                   this.stopCellEditing();  // XXX
    // XXX doesn't work - the cell displays a JTextField that needs additionally be confirmed!?
                   this.comSelected = tf;
                   return tf;
              return null;          
         public Object getCellEditorValue() {
              if(comSelected.equals(this.box)){
              }else if(comSelected.equals(this.tf)){
                   return tf.getText();
              return null;
         public boolean isCellEditable(EventObject anEvent) {
              if(anEvent instanceof MouseEvent){
                   return (((MouseEvent)anEvent).getClickCount() > 2);
              }else{
                   return true; // XXX actually, should this be false?
    // in the tree model (extends TreeModel) the value will be accepted as follows:
         public void valueForPathChanged(TreePath path, Object newValue) {
              Node node = (Node) path.getLastPathComponent();
              if(node instanceof LeafComboBox){
              }else if(node instanceof LeafFileChooser){
                   String sz = newValue.toString();
                   node.setContent(sz);
              }

    hi
    i seem to be having a problem opening the selected file using the following code.
    the selected file needs to be opened on a new frame.
    please help.
    if (cmd.equals("Open.."))
                                       fc.addChoosableFileFilter(new ImageFilter());
         int returnVal = fc.showOpenDialog(Proj.this);
         // Determine which button was clicked to close the dialog
         switch ( returnVal) {
         case JFileChooser.APPROVE_OPTION:
              {                              File fl = fc.getSelectedFile();
              //String file =("test.gif");
              ImageIcon icon = new ImageIcon(f1);
              JLabel label = new JLabel();
              label.setIcon( new ImageIcon(icon) );
              Frame1 frame = new Frame1(TITLE,drawPanel);          frame.setVisible(true);
              deskTop.add(frame);
              drawPanel.add(label);
         // Approve (Open or Save) was clicked
    break;
         case JFileChooser.CANCEL_OPTION:
    // Cancel or the close-dialog icon was clicked
    break;
    // case JFileChooser.ERROR_OPTION:
    // The selection process did not complete successfully
    // break;
                             }

  • Trying to use TreeCellEditor in JTree

    Hi,
    I'm having problems with TreeCellEditor. There are no really good examples of tree editing that I can find. The only good examples I can find use a JTree with String objects in its nodes. In my case I don't have String objects, but my own custom objects.
    As I understand you call stopCellEditing() when the user has finished with what they are doing and have pressed ENTER. In my stopCellEditing() I get a reference to my DefaultMutableTreeNode which I set up in the getTreeCellEditorComponent method. In my stopCellEditing() method I then change the node object by calling editedNode.setUserObject(myNewNodeObject);
    It just doesn't work. The value of node is never changed.
    Olly
    public class CalculationTreeEditor implements TreeCellEditor
    private EditorTextField emptyNodeEditor;
    private DefaultMutableTreeNode editedNode;
    public CalculationTreeEditor()
    emptyNodeEditor = new EditorTextField();
    * @see javax.swing.tree.TreeCellEditor#getTreeCellEditorComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int)
    public Component getTreeCellEditorComponent(JTree tree, Object value,
                                                 boolean isSelected,
                                                 boolean expanded,
                                                 boolean leaf,
                                                 int row)
    editedNode = (DefaultMutableTreeNode)value;
    Object userObject = editedNode.getUserObject();
    System.out.println("user object class is = " + userObject.getClass());
    emptyNodeEditor.setText("");
    return emptyNodeEditor;
    public Object getCellEditorValue()
    //this
    System.out.println("--------- get cell editor value");
    System.out.println("editedNode.getUserObject() = " + editedNode.getUserObject());
    return editedNode.getUserObject();
    * CalculationTree checks to see whether node is editable
    * or not. Not here.
    public boolean isCellEditable(EventObject anEvent)
    return true;
    public boolean shouldSelectCell(EventObject event)
    System.out.println("--------- should select cell");
    return emptyNodeEditor.shouldSelectCell(event);
    public boolean stopCellEditing()
    System.out.println("--------- cell editing has stopped");
    Integer i = (Integer)emptyNodeEditor.getCellEditorValue();
    ValueNode vn = new ValueNode(i);
    System.out.println("the editor value is : " + i);
    editedNode.setUserObject(vn);
    // ValueNode valueNode = new ValueNode();
    return emptyNodeEditor.stopCellEditing();
    public void cancelCellEditing()
    System.out.println("--------- cell editing has cancelled");
    emptyNodeEditor.cancelCellEditing();
    public void addCellEditorListener(CellEditorListener l)
    System.out.println("--------- adding cell editor listener");
    emptyNodeEditor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l)
    System.out.println("--------- removing cell editor listener");
    emptyNodeEditor.removeCellEditorListener(l);

    Here's a minimal TreeCell editor. Maybe it will helpimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.EventObject;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        JTree jt = new JTree();
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setEditable(true);
        jt.setCellEditor(new MyEditor());
        setSize(400, 400);
        setVisible(true);
      public static void main(String[] args) { new Test3(); }
    class MyEditor extends JTextField implements TreeCellEditor {
      public Object getCellEditorValue() { return this.getText(); }
      public boolean isCellEditable(EventObject evt) {
        if (evt instanceof MouseEvent &&
            ((MouseEvent)evt).getClickCount()==1) return true;
        else return false;
      public Component getTreeCellEditorComponent(JTree tree, Object value,
                                                  boolean isSelected,
                                                  boolean expanded, boolean leaf,
                                                  int row) {
        setText(value.toString());
        return this;
      public void cancelCellEditing() {}
      public void addCellEditorListener(CellEditorListener l) {}
      public void removeCellEditorListener(CellEditorListener l) {}
      public boolean shouldSelectCell(EventObject anEvent) { return true; }
      public boolean stopCellEditing() { return false; }
    }

  • Adding multiple row editor to TreeCellEditor

    Hey all,
    I need to have a text field, check box and a combo box all as part of an inline editor for a tree node. When the user hits NEW to insert a new tree node, or edit an existing one, I want the editor to appear with two rows. The top row is the text field and check box. The second row is the combo box.
    Is this possible? I just tried it and I see my combo box appear, but it appears the height of the editing area is fixed, so only my combo box shows up and the text field is no longer visible?
    Here is my code:
    public class AdminTreeCellEditor extends DefaultTreeCellEditor
      private final JCheckBox activeBox = new JCheckBox("Active");
      private final JComboBox revenueCategoryBox = new JComboBox();
      private final JLabel iconLabel = new JLabel();
      private final JPanel editorPanel = new JPanel(new BorderLayout());
      private Icon editIcon = null;
      public AdminTreeCellEditor(JTree tree)
        super(tree, (DefaultTreeCellRenderer) tree.getCellRenderer());
        editorPanel.add(activeBox, BorderLayout.EAST);
        editorPanel.setOpaque(false);
        activeBox.setOpaque(false);
        editIcon = new ImageIcon(getClass().getResource("/edit.gif"));
      public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
        Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              SortableTreeNode dmtn = (SortableTreeNode)value;
        if (dmtn.getUserObject() instanceof CorporateItem)
          CorporateItem ci = (CorporateItem)dmtn.getUserObject();
          activeBox.setSelected(ci.isActive());
        else
          activeBox.setSelected(true);
        editorPanel.add(c, BorderLayout.WEST);
        if (dmtn.getUserObject() instanceof CorporateSpecial)
          editorPanel.add(revenueCategoryBox, BorderLayout.SOUTH);
        JTextField jtf = (JTextField)editingComponent;
        jtf.setSelectionStart(0);
        jtf.setSelectionEnd(jtf.getText().length());
        jtf.requestFocus();
        // set icon to renderers icon
        editingIcon = editIcon;
        return editorPanel;
      public boolean isCellEditable(EventObject event)
        boolean retValue = super.isCellEditable(event);
        if (retValue)
          SortableTreeNode dmtn = (SortableTreeNode) tree.getSelectionPath().getLastPathComponent();
          if (dmtn.getUserObject() instanceof LowItem)
            retValue = false;
      return retValue;
    }In the above, if the user object is a CorporateSpecial, I add the combo box to the editor panel. So, it seems to work, accept that the height of the tree node editing area doesn't expand enough to show two rows of items. Is there some call I need to make on the tree for the editing path to set it's height? Can this be done? I am trying to avoid doing a pop-up dialog for editing... I like the idea of the inline node editing.
    Thanks.

    Got that. Turns out that you have to set the Tree.setRowHeight(0) in order to avoid using a fixed cell height. It uses the cell renderer (or editor) to figure out the preferred size of the cell. Problem is, even though I did this, it appears I still have to set the row height in the getTreeCellEditorComponent() method directly, as the one time setting on the tree seems to get overridden somehow. Not sure how. Anyway, it does work. I have a two row editor showing up now, which is very slick! Inline expansion to show a 2 row editor, then when done it goes away. Nice.

  • My TreeCellEditor takes 100% CPU-power

    Hi,
    I have a custom TreeCellEditor on a JTree which displays a JComponent with (a JCheckBox and a JLabel). When I click once on a label ( on a checkbox, everything is normal ), the nodes is selected and the TreeCellEditor is invoked. But when I open the Windows Task Manager, I see that the thread is using 100% processer power. This stops as soon as I click on a JCheckBox or when I expand or collapse another node in the tree.
    I've put tracing code in all my methods, but none of them seem to cause an infinite loop... Any ideas...?
    Thanx!

    I really don't have the time to search the relevant peaces of code, but maybe you can help me find the problem myself. When I override the paint() method in my component and I dump the stack before calling the super.paint(), I can see that the repaintmanager considers the component as a 'dirty region' and repaints it, over and over and over...
    Do you, or anybody else, know when the repaintmanager considers a component as 'dirty' ?

  • Cant get current node from TreeCellEditor isCellEditable().

    I have a custom TreeCellEditor but I do not want to allow the user to edit the root node.
    I was hoping to use isCellEditable() but I can not seem to get the node that is being edited from the EventObject.
    I can get the JTree, (from event.getSource(), but there is no way to get the node that is being tested. I have tried using:
    tree.getEditingPath()
    tree.getLastPathComponent()
    tree.getSelectionPath()But they all return null at the time isCellEditable() is called.
    Does anyone know of a way to get the node that is being tested?
    Thanks,
    Jerome.

    well, that method is meant to be generic such that it decides if editing is possible for the type of event.
    JTable has a separate isCellEditable method, but so does TableModel, so typically, you have a custom table model that implements the method there to return, and in that you know what cell.
    For JTree, I don't know why there's no similar method in the TreeModel interface. There is in JTree, but I really think that should be a function of the model, not the view.
    For JTable, I believe it's only there as a pass-thru, calling the table model's method underneath to get the value.

  • Icon was changed to default icon when editting a node on JTree

    I have a tree with icon on nodes. However, when I edit the node, the icon is changed to default icon.
    I don't known how to write the treeCellEditor to fix that one.
    The following is my code:
    package description.ui;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.ToolTipManager;
    import javax.swing.WindowConstants;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class Tree extends javax.swing.JPanel {
         private JTree tree;
         private JScrollPane jScrollPane1;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new Tree());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.show();
         public Tree() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   BorderLayout thisLayout = new BorderLayout();
                   this.setLayout(thisLayout);
                   setPreferredSize(new Dimension(400, 300));
                    jScrollPane1 = new JScrollPane();
                    this.add(jScrollPane1, BorderLayout.CENTER);
                        DefaultMutableTreeNode rootNode = createNode();
                        tree = new JTree(rootNode);
                        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                        jScrollPane1.setViewportView(tree);
                        ToolTipManager.sharedInstance().registerComponent(tree);
                        MyCellRenderer cellRenderer = new MyCellRenderer();
                        tree.setCellRenderer(cellRenderer);
                        tree.setEditable(true);
                        tree.setCellEditor(new DefaultTreeCellEditor(tree, cellRenderer));
                        //tree.setCellEditor(new MyCellEditor(tree, cellRenderer));
              } catch (Exception e) {
                   e.printStackTrace();
         private void btRemoveActionPerformed(ActionEvent evt) {
             TreePath path = tree.getSelectionPath();
             DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
             ((DefaultTreeModel)tree.getModel()).removeNodeFromParent(selectedNode);
         private DefaultMutableTreeNode createNode() {
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Doc");
             DefaultMutableTreeNode ch1 = createChuongNode(rootNode, "Ch1");
             DefaultMutableTreeNode ch2 = createChuongNode(rootNode, "Ch2");
             createTextLeafNode(ch1, "title");
             return rootNode;
         private DefaultMutableTreeNode createChuongNode(DefaultMutableTreeNode parent, String name) {
             DefaultMutableTreeNode node = new DefaultMutableTreeNode(new ChapterNodeData(name));
             parent.add(node);
             return node;
         private DefaultMutableTreeNode createTextLeafNode(DefaultMutableTreeNode parent, String name) {
             DefaultMutableTreeNode node = new DefaultMutableTreeNode(new TitleNodeData(name));
             parent.add(node);
             return node;
          private class MyCellRenderer extends DefaultTreeCellRenderer {
                 ImageIcon titleIcon;
                 ImageIcon chapterIcon;
                 public MyCellRenderer() {
                     titleIcon = new ImageIcon(getClass().getClassLoader()
                            .getResource("description/ui/icons/Text16.gif"));
                     chapterIcon = new ImageIcon(getClass().getClassLoader()
                            .getResource("description/ui/icons/Element16.gif"));
                 public Component getTreeCellRendererComponent(
                                     JTree tree,
                                     Object value,
                                     boolean sel,
                                     boolean expanded,
                                     boolean leaf,
                                     int row,
                                     boolean hasFocus) {
                     super.getTreeCellRendererComponent(
                                     tree, value, sel,
                                     expanded, leaf, row,
                                     hasFocus);
                     if (isChapterNode(value)) {
                         setIcon(chapterIcon);
                         setToolTipText("chapter");
                     } else if (isTextLeafNode(value)) {
                         setIcon(titleIcon);
                         setToolTipText("title");
                     return this;
                 protected boolean isChapterNode(Object node) {
                     return ((DefaultMutableTreeNode)node).getUserObject() instanceof ChapterNodeData;
                 protected boolean isTextLeafNode(Object node) {
                     return ((DefaultMutableTreeNode)node).getUserObject() instanceof TitleNodeData;
          private class MyCellEditor extends DefaultTreeCellEditor {
                 ImageIcon titleIcon;
                 ImageIcon chapterIcon;
              public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
                  super(tree, renderer);
                  titleIcon = new ImageIcon(getClass().getClassLoader()
                         .getResource("description/ui/icons/Text16.gif"));
                  titleIcon = new ImageIcon(getClass().getClassLoader()
                         .getResource("description/ui/icons/Element16.gif"));
              public Component getTreeCellEditorComponent(
                           JTree tree,
                           Object value,
                           boolean isSelected,
                           boolean expanded,
                           boolean leaf,
                           int row) {
                  super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
                  return this.editingComponent;
          abstract class NodeData{
              String name;
              public NodeData(String name) {
                  this.name = name;
              public String getName() {
                  return name;
              public void setName(String name) {
                  this.name = name;
              public String toString() {
                  return name;
          class ChapterNodeData extends NodeData {
              public ChapterNodeData(String s) {
                  super(s);
          class TitleNodeData extends NodeData {
              public TitleNodeData(String attr) {
                  super(attr);
    }

    Arungeeth wrote:
    I know the name of the node... but i cant able to find that nodeHere is some sample code for searching and selecting a node:
        TreeModel model = jtemp.getModel();
        if (model != null) {
            Object root = model.getRoot();
            search(model, root, "Peter");//search for the name 'Peter'
            System.out.println(jtemp.getSelectionPath().getLastPathComponent());
        } else {
            System.out.println("Tree is empty.");
    private void search(TreeModel model, Object o, String argSearch) {
        int cc;
        cc = model.getChildCount(o);
        for (int i = 0; i < cc; i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(o, i);
            if (model.isLeaf(child)) {
                TreeNode[] ar = child.getPath();
                String currentValue = Arrays.toString(ar);
                if (currentValue.contains(argSearch)) {
                    jtemp.setSelectionPath(new TreePath(ar));
            } else {
                search(model, child, argSearch);
    }

  • JTree stop cell editing on lost focus and scrollPathToVIsible behavior

    how can you make a Jtree that uses a DefaultTreeCellEditor stop editing when it loses focus to a component other than the
    cell editor's DefaultTextField component ?
    i had to use a custom TreeCellEditor and attach my focus listener to the DefaultTextField object and attach it also to the JTree object
              DefaultTreeCellEditor celEditor = new DefaultTreeCellEditor(containerTree,renderer)
                   @Override
                   public Component getTreeCellEditorComponent(JTree tree, Object value,
                                     boolean isSelected,
                             boolean expanded,
                             boolean leaf, int row) {
                        Component comp = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
                        boolean found= false;
                        for(FocusListener f:editingComponent.getFocusListeners())
                             if(focusListener.equals(f))
                                  found=true;
                                  break;
                        if(!found)
                             editingComponent.addFocusListener(focusListener);
                        return comp;
    myTree.addFocusListener(focusListener);in JTable there's a property that you switch on/off which does exactly that, is there anything alike for JTree ?
    one more thing,after adding a new TreeNode to the JTree,i'm calling scrollPathToVisible(<path to the new node>),but for all the nodes i add except the first, the user object is not displayed,am i missing something? here's my code
              ActionListener actionListener = new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        DefaultTreeModel model = (DefaultTreeModel)containerTree.getModel();
                        int nodeCount=containerTree.getModel().getChildCount(root);
                        if(ae.getSource().equals(menuAdd))
                             DefaultMutableTreeNode newNode=new DefaultMutableTreeNode();
                             if(currentNode>0 && currentNode+1<nodeCount)
                                  model.insertNodeInto(newNode, root, currentNode+1);
                                  newNode.setUserObject("container #"+(currentNode+1));
                             else
                                  model.insertNodeInto(newNode, root, root.getChildCount());
                                  newNode.setUserObject("container #"+nodeCount);
                             TreePath path = new TreePath(newNode.getPath());
                                            // only works properly for 1st node,for the rest i have to
                                            // click on the new node to get the proper display
                             containerTree.scrollPathToVisible(path);
                        else if(nodeCount>=0 && currentNode!=0)
                             model.removeNodeFromParent((DefaultMutableTreeNode)model.getChild(root, currentNode-1));
              };

    i solved the second issue by selecting the new node and starting to edit it

Maybe you are looking for

  • "Warning" sign on On Demand

    Does anybody know what the warning signs mean on an On Demand tv episode? Does that mean it is going to be off soon? And does anybody know how often hbo series are switched out for the next series? Like Sex and the City season 3  has been On Demand f

  • External database Authentication Issue

    Hello Experts I have omplemented external database authentication in my PC and somehow its not working Do we have to configure the details in NQSconfig file in the security section for implementing External Database Authentication .

  • Error message in HUPAST

    Folks, I've a packed inbound delivery which I want to unpack in HUPAST. When trying to unpack I get the following error: "No item record exists for the handling unit to be unpacked" To which item record is being referred?

  • No paperless fax with windows 8.1

       With reference to:    PC: HP Pavilian PC 500-016 (H5Q30AA#ABA)    OS: Windows 8.1    Printer: HP Officejet 6600 (wireless network)    Please note that there is no problem sending a paperless FAX from any other computer. Paperless fax does not work

  • Destination Storage Unit in FM L_TO_CREATE_MOVE_SU

    Hi everyboday, I'm using the FM L_TO_CREATE_MOVE_SU  in order to create transfer order for moving storage units. I need to set the "Destination Storage Unit" but I cant find these field in he FM. I just have the  i_lenum field which is the "Origin St