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

Similar Messages

  • 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.

  • How do you select a single image with the keyboard?

    I can use the "/" key to deselecting the current photo but how do I select the current photo with the keyboard? Usually the space bar is used for this but that displays the image. Is the only way to select the current photo by using the mouse?

    OK, now that the question has been clarified....
    Pressing and holding the Shift key as you move through the grid with the arrow keys will individually multi-select them, but that breaks down if you want non-contiguous selections, i.e. lifting off the shift key to skip a photo will cause all previous selections to be lost when you use the arrow key to advance. I think the only way for non-contiguous selection is ctrl-click.

  • How to select a single entry with latest date just LE system date?

    Hi all,
    Suppose there are 5 entries with first day (ertag) in table prow:
    01.05.2005
    01.06.2005
    01.07.2005
    01.08.2005
    01.09.2005
    Suppose system date (sy-datum) is 25.07.2005, I want a SQL that should select the third entry (01.07.2005).
    FYI:
    This SQL only selects the first entry:
    Select single * from PROW into corresponding fields of ITAB where ERTAG LE SY-DATUM.
    Could anyone help ? Thx.

    another option.
    data: first_day type sy-datum ,
          periv type T009B-PERIV ,
          poper type T009B-Poper ,
          year type T009B-BDATJ .
    data: iprow type standard table of prow .
    move: 'K4' to periv ,
          sy-datum+4(2) to poper ,
          sy-datum+0(4) to year .
    CALL FUNCTION 'FIRST_DAY_IN_PERIOD_GET'
      EXPORTING
        i_gjahr              = year
    *    I_MONMIT             = 00
        i_periv              = periv
        i_poper              = poper
    IMPORTING
       E_DATE               = first_day
    EXCEPTIONS
       INPUT_FALSE          = 1
       T009_NOTFOUND        = 2
       T009B_NOTFOUND       = 3
       OTHERS               = 4
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    select * from prow into table iprow where ertag between first_day and sy-datum .
    Regards
    Raja

  • Single click folder name to expand folder in folder view?

    As with prior versions, in [Windows] Explorer's main window, you can enable hovering to select and single clicking to expand the folder (but that is a pain in the rear when working with files). Windows XP folder view nicely allowed single clicking the folder name to expand the folder. Was that removed from Windows 7? Looks like the only way to expand a folder in folder view is to either click on the small plus sign or to double click on the folder name.  Or is there a switch somewhere I am missing? Thanks.

    "...Things are worse than that now... When you single click on a folder name in the folder list, the folder contents show in the right hand file window, as usual. But, when you use an arrow key to move to a folder name in the folder list, the folder
    contents no longer show in the right hand file window...."
    The option  seems to be disabled. It is in Explorer>tools>folder options>navigation pane>"automatically expand to current folder" (win7 v6.1
    Excluding this extremely useful feature really cripples Win7Explorer. I was spoiled by w9x and XP explorers. I am new to MS forums. Is there a moderated microsoft forum where this question can be posted, in the hope that a patch is produced?
    I asked this in 2007 and I was answered <<WE DON'T GIVE A SH*T OF WHAT YOU WANT>>
    See here:
    http://connect.microsoft.com/WindowsServerFeedback/feedback/details/313066/explorer-should-expand-folder-tree-the-windows-xp-way

  • How to clear vendor open items with customer open items in APP?

    Hi Experts,
    Our vendor is our customer - in this scenario how to clear vedor open items against customer open items. I have defined vedor is customer means I have given customer number in vendor master record, selected chek box 'clear with customer'.  Still problem is not solved, hence I am requesting you to help me in this regard.
    Thank you very much,
    Regards,
    Ganesh.

    Hi
    In FBCJ after payment you have clear manually vendor balance in F-44.
    If you want SPL GL in FBCJ then write a Substitution .
    1. step 001 - Special G/L Substitution
    2. Prerequisite - Transaction code = 'FBCJ'
    3. Substitution posting key -- Exit (need help from abap) exit name
                                              G/L Exit (need help from abap) exit name
                                              Special G/L Ind Exit (need help from abap) exit name
    you can't do this without ABAP help
    Best Of Luck
    Tanmoy

  • I cannot select a single character

    I'm running Pages 5.2.2 on MacOS 10.9.4 on a 2011 MacBook Pro. The problem is I cannot select a single character with my Magic Mouse. If I try to drag over a single letter to select it, the cursor is positioned either before or after the letter. I can select and format groups of two or more characters, but not just one. It works with the trackpad though. I can select single characters with the mouse in other apps such as Word.

    While we all have MacBooks in this forum most of us don’t run Mountain Lion. There's a Mountain Lion Support Community where everybody has Mountain Lion. You should also post this question there to increase your chances of getting an answer. https://discussions.apple.com/community/mac_os/os_x_mountain_lion

  • Single Click Acts Like Double Click

    A coworkers is having problems with his mouse (so I thought I'd post the problem, see if anyone knows what might be happening). He'll single click with his mouse, but sometimes (not always), it will act as though he's double clicked. Anyone have any suggestions as to what the problem might be?

    He's got a dual 1.2 (I think) GHz G4 tower. He's using some third party mouse (with two buttons and a scroll wheel). He's running Panther (he might upgrade to Tiger today).
    He (Brian, I'm gonna stop sayin' "he") ...Brian, switched with a "normal" Apple mouse for a few minutes and said it wasn't happening. But he can't get used to the big single click (which I prefer myself). Well, looks like we've found the culprit. I'll suggest changing USB ports, see if that does anything different.

  • Selecting a page with a single-click instead of double-click

    Is there anyway to make InDesign CS5.5 move my file to the page I have selected in the pages panel without having to double-click the page in the pages panel?
    I keep forgetting that the page selected in the panel may or may not be the page I'm currently editing & this is very frustrating.

    Page that you're currently on is highlighted in reverse (black background white text)
    If you're select a page in the pages panel it highlights blue to indicate it's selected. This allows you to move the page if you need to, or select over dozen other options for that page, numbering, sections, override, move, duplicate, apply master page to, delete, rotate view, colour label, page transiitions, hide master items and spread flattening!
    You double click a page to move to that page. If it was only a single click then it would be quite frustrating to be hopping all over the document when all you want to do is renumber/resection/dupe or over a dozen different options mentioned above.
    CTRL/CMD J will bring up the Go To Page dialog box.
    Navigate with the page numbers as peter suggested.
    There's a reason it works like that - because it works best.

  • Why does selecting a web link open 2 windows, one with the link and the other the home page? This is a single click of the mouse.

    When I single click on a weblink (usually in an email, Firefox starts up and opens two windows; one with the selected web page and one with my home page. If Firefox is running, it opens a new tab which is what normally occurs. It is only when it is not open that I now get the 2 windows. I have an imac running OSX 10.6.3
    == This happened ==
    Every time Firefox opened
    == In the past couple of weeks.

    Hi,
    The rolling over from radius servers only occurs on the same wlan and only when the controller deems the radius server being dead. However, if you get rejected from one WLAN but then you reassociate to another WLAN there is no mechanism in place in rejecting the attempt because they previously failed on a seperate wlan. This happens all the time with users connecting on incorrect wlans.
    The failover feature is for when you have multiple servers (usually for redundancy) on the same WLAN. So when user is rejected but radius server 1 the process stops there and the request isnt sent to radius server 2.
    Hope that helps!
    Tarik Admani
    *Please rate helpful posts*

  • Spark List muiltiple select-Single Click

    I have a list (tileLayout) with a custom item renderer. AllowMultipleSelection is set to true.
    Is there a way for me to allow thr user to select more than one item without having to hold down CTRL? I'd like a single click to select/de-select the items.
    Any Help appreciated

    I haven't given it much thought, but you would probably have to do something involving a few things.
    1. event.preventDefault on the List when something is clicked
    2.  Listen for clicks, get the clicked item, put in the selectedItems array of the list.
    3. Check to see if item was already in  selectedItems list, if so remove to deselect it
    Like I said, I didn't give this much thought, especially on the event.preventDefault but that is where I would start.  But there probably is a simpler solution out there.

  • In XP single-click mode, hovering overwrites filenames in select downl loc

    My grandmother has arthritis, there's no way she can use double click mode. She gets pictures in the mail and she wants to save them to relevant folders. when she enters a subfolder with a bunch of other pictures, in just 1 second of not moving the mouse, the file name in the select download location window is overwritten because hovering for one second is treated like a single click. Is there any way around this problem?

    "...Things are worse than that now... When you single click on a folder name in the folder list, the folder contents show in the right hand file window, as usual. But, when you use an arrow key to move to a folder name in the folder list, the folder
    contents no longer show in the right hand file window...."
    The option  seems to be disabled. It is in Explorer>tools>folder options>navigation pane>"automatically expand to current folder" (win7 v6.1
    Excluding this extremely useful feature really cripples Win7Explorer. I was spoiled by w9x and XP explorers. I am new to MS forums. Is there a moderated microsoft forum where this question can be posted, in the hope that a patch is produced?
    I asked this in 2007 and I was answered <<WE DON'T GIVE A SH*T OF WHAT YOU WANT>>
    See here:
    http://connect.microsoft.com/WindowsServerFeedback/feedback/details/313066/explorer-should-expand-folder-tree-the-windows-xp-way

  • Single click to show selected file in editor when in "edit view"?

    Anyone know if there is an option to set single click to show selected file in editor when in "edit view"?  Instead of having to double click?

    I would also like to be able to "right-click > edit source file" in multi-track view WHEN A CLIP IS GROUPED.
    Currently, when a clip is grouped with another clip, if you select a portion of that clip to edit, then right-click it, IT WILL NOT ALLOW YOU TO "EDIT SOURCE FILE" until you have ungrouped then re-selected it, which is cumbersome.
    Not only do you have to do that, but upon returning to MT VIEW you have to remember to re-group that clip with the other clips, not being able to right-click and edit the source file of grouped clips adds unnecassary trouble and confusion to the interface, and for what?

  • When I select a single object in a layer and try to move it with the mouse, everything goes with...

    I've been having this problem where I can't use the move tool with the mouse properly. I'll go and select a single item on a layer and then try to move it with the mouse (move tool). I've done this before and still do it all the time on Photoshop on my other machines. However, on my laptop it won't work. I grab the single object I want to move and the second I move it, it defaults to moving every single layer in my file. The only way to get around it is to use the arrows, but that's becoming laborious and frustrating.
    Any ideas?

    I know what you mean! This happened to me as well!
    And one thing that I found useful is, if you want to directly select a layer without selecting from the layers pallete and without having autoselect enabled, just hold Ctrl and click on in directly in the image. This saved me a lot of time!

  • Files get open with single click sometimes

    I recently started having this problem. When I browse through different image/video files, some of the files get open with one click only. This is really very annoying. I am event thinking to migrate back to Windows because of this problem.
    How to reproduce the issue:
    -> Open a folder that contains many images/video files
    -> Click on anyone of them to select it
    -> Now click outside the window. So, the finder goes out of the focus (but should stay visible)
    -> Now, inside finder click any other image/video just once, it will open up automatically with just single click

    If you have access to a mouse, try using it. If everything is okay using the mouse, then it is likely trackpad related. Other troubleshooting.
    Try setting up another admin user account to see if the same problem continues. If Back-to-My Mac is selected in System Preferences, the Guest account will not work. The intent is to see if it is specific to one account or a system wide problem. This account can be deleted later.
    Isolating an issue by using another user account
    If the problem is still there, try booting into the Safe Mode.  Shut down the computer and then power it back up. Immediately after hearing the startup chime, hold down the shift key and continue to hold it until the gray Apple icon and a progress bar appear. The boot up is significantly slower than normal. This will reset some caches, forces a directory check, and disables all startup and login items, among other things. If the system operates normally, there may be 3rd party applications which are causing a problem. Try deleting/disabling the third party applications after a restart by using the application unistaller. For each disable/delete, you will need to restart if you don't do them all at once.
    Safe Mode
    Safe Mode - About
    General information.
    Isolating issues in Mac OS X
    Troubleshooting Permission Issues
    Step by Step to Fix Your Mac

Maybe you are looking for