Focus Problem with JTree and Menus

Hi all,
I have a problem with focus when editing a JTree and selecting a menu. The problem occurs when the user single clicks on a node, invoking the countdown to edit. If the user quickly clicks on a menu item, the focus will go to the menu item, but then when the countdown finishes, the node now has keyboard focus.
Below is code to reproduce the problem. Click on the node, hover for a little bit, then quickly click on the menu item.
How would I go about fixing the problem? Thanks!
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class MyTree extends JTree {
     public MyTree(DefaultTreeModel treemodel) {
          setModel(treemodel);
          setRootVisible(true);
     public static void main(String[] args) {
          JFrame frame = new JFrame();
          JMenuBar bar = new JMenuBar();
          JMenu menu = new JMenu("Test");
          JMenuItem item = new JMenuItem("Item");
          menu.add(item);
          bar.add(menu);
          frame.setJMenuBar(bar);
          Container contentPane = frame.getContentPane();
          contentPane.setLayout(new GridLayout(1, 2));
          DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("Root");
          root1.add(new DefaultMutableTreeNode("Root2"));
          DefaultTreeModel model = new DefaultTreeModel(root1);
          MyTree tree1 = new MyTree(model);
          tree1.setEditable(true);
          tree1.setCellEditor(
               new ComponentTreeCellEditor(
                    tree1,
                    new ComponentTreeCellRenderer()));
          tree1.setRowHeight(0);
          contentPane.add(tree1);
          frame.pack();
          frame.show();
import java.awt.FlowLayout;
import java.util.EventObject;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
public class ComponentTreeCellEditor
     extends DefaultTreeCellEditor
     implements TreeCellEditor {
     private String m_oldValue;
     private TreeCellRenderer m_renderer = null;
     private DefaultTreeModel m_model = null;
     private JPanel m_display = null;
     private JTextField m_field = null;
     private JTree m_tree = null;
     public ComponentTreeCellEditor(
          JTree tree,
          DefaultTreeCellRenderer renderer) {
          super(tree, renderer);
          m_renderer = renderer;
          m_model = (DefaultTreeModel) tree.getModel();
          m_tree = tree;
          m_display = new JPanel(new FlowLayout(FlowLayout.LEFT));
          m_field = new JTextField();
          m_display.add(new JLabel("My Label "));
          m_display.add(m_field);
     public java.awt.Component getTreeCellEditorComponent(
          JTree tree,
          Object value,
          boolean isSelected,
          boolean expanded,
          boolean leaf,
          int row) {
          m_field.setText(value.toString());
          return m_display;
     public Object getCellEditorValue() {
          return m_field.getText();
      * The edited cell should always be selected.
      * @param anEvent the event that fired this function.
      * @return true, always.
     public boolean shouldSelectCell(EventObject anEvent) {
          return true;
      * Only edit immediately if the event is null.
      * @param event the event being studied
      * @return true if event is null, false otherwise.
     protected boolean canEditImmediately(EventObject event) {
          return (event == null);
}

You can provide a cell renderer to the JTree to paint the checkBox.
The following code checks or unchecks the box with each click also:
_tree.setCellRenderer(new DefaultTreeCellRenderer()
  private JCheckBox checkBox = null;
  public Component getTreeCellRendererComponent(JTree tree,
                                                Object value,
                                                boolean selected,
                                                boolean expanded,
                                                boolean leaf,
                                                int row,
                                                boolean hasFocus)
    // Each node will be drawn as a check box
    if (checkBox == null)
      checkBox  = new JCheckBox();
      checkBox .setBackground(tree.getBackground());
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
    checkBox.setText(node.getUserObject().toString());
    checkBox.setSelected(selected);
    return checkBox;
});

Similar Messages

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Problem with Jtree and a checkbox

    Hello,
    I have a problem with my tree implementation.
    I create a tree and i want to add a checkbox in each node.
    this is my code :
    DefaultMutableTreeNode root;
    root = new DefaultMutableTreeNode(new JCheckBox());
    DefaultTreeModel model = new DefaultTreeModel(root);
    _tree = new JTree(model);
    eastpane.add(tree);
    THe problem is that my checkbox doesn't appear. And a message appears
    instead of my checkbox.
    But my tree appears.
    Can anyone help me .
    Thanks

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Problem with firefox and menus

    I have an intermittent problem in Firefox with menus.  I click on a menu or a drop down button and, as soon as I move my mouse over the menu, it disappears.  The only way to select something on the menu is to leave my mouse where it is and use the arrow keys and enter to select an item.
    Not sure if it's relevant, but I'm using fluxbox as my window manager.

    There has been a bugreport about this, I can't find it right now, but this seems to be a bigger issue. I had this behavior with i3. The behavior was a bit different than you described, but it also affected the menus, so it's related. And yes, this made me very angry as well

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • Problem with dreamweaver and Flash

    Hi, maybe someone can help me, i have any problem with
    dreamweaver and flash, i have a page and i have a menu and
    sub-menu, and the same page i have a category en flash 550 x 700 (
    photography and more... ) but when the menu to unfold
    the menu to see under flash and it cant see ( sorry my
    english is bad.... i hope you can understand me, and help me.. )
    i dont now why always flash ever stay up, or first, and
    another information under flash... this a problem... if you have
    menus...
    thanks.... have nice day.....

    This is a drawback of using flash or any other active
    content. By default, all active content including flash will
    display over every other content and thats why your menu stays
    under the flash movie. Some people make the flash background
    transparent to show content under the flash movie, but that will
    not work for menu items.
    I would suggest that you make the menu such that it does not
    overlap with the flash movie.

  • Significant Computer Window Focus Problem With Verizon Access Manager 7.7.1.0 (2707e)

    With the newly released Verizon Access Manager 7.7.1.0 (2707e) there is a significant computer focus problem with it.
    What I mean by this is that if I am using ANY application on my computer with the Verizon Access Manager minimized to the Windows System Tray, something will go on with the Verizon Access Manager and it steals the window focus - I am unable to work in the other application unless I click on the application to use it again.  
    An example of this would be my typing to post a message in this forum.  Something occurs in the Verizon Access Manager and my typing is rendered useless unless I click with my mouse on the browser window to be able to use it again.
    I'm highly suspecting whenever networks are coming and going in the Access Manager is when the problem occurs.
     This problem did not exist in the previous version of the Access Manager I was using.
    This is extremely annoying - please issue a fix for this ASAP!

    I have found by not minimzing the Verizon Access Manager 7.7.1.0 (2707e) the focus problem does not occur - it appears to be a problem when the app is minimzed to the system tray.

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Problem with installing and running some applications or drivers

    When installing and installing some items, towards the end of the installation I get this message:
    /System/Library/Extensions/comcy_driver_USBDevice.kext
    *was installed improperly and cannot be used. Please try reinstalling it or contact product's vendor for update*
    The end result is that some things do not seem to work properly, such as my HP printer. Would anybody have any ideas on how to fix this problem?

    Thank you for your response. Originally, I had a problem with Airport and ended up reinstalling Snow Leopard. Since then, when downloading upgrades etc, such as HP printer drivers, iTunes etc., towards the end of the download when its running the script, I get this message: /System/Library/Extensions/comcy_driver_USBDevice.kext
    +was installed improperly and cannot be used. Please try reinstalling it or contact product's vendor for update+
    Sometimes, the download hangs and is unable to complete. The main problem I've encountered so far with an application is when I use the printer to scan an image via Preview, it's blank: there's nothing there.

  • Problems with outlook and address book contacts: my outlook contacts had around 3,000 entries. Outlook duplicated by itself and now outlook and address book have each over 340,000. What should I do?

    Problems with outlook and address book contacts: my outlook contacts had around 3,000 entries. Outlook duplicated entries and have now 340,000. I reinstalled microsoft office and, thus, outlook, and reinstalled mac OS X system and applications. While I managed to delete outlook contacts so that I can re-sync with my blackberry, the contacts at Mac Address Book were not deleted and still have over 340,000 entries. I do not mind deleting all contacts since I have back up, but I have not been able to delete them. Also, when I go at Address Book and try to delete or merge duplicated entries, the system takes forever and never ends because of such large amount of entries. Worse, when I do so I run out of RAM memory.
    My Macbook pro is just 2 months old.
    What should I do? Is there a way to delete my Mac Address Book without having the problem above?
    Many thanks
    Regis

    zlatan24 wrote:
    For solving out troubles connected with corrupted or lost address book you may use address book recovery. It owns various features such as restoring wab files, it working under any Windows OS. The utility has modern and easy to use interface due to almost every experienced users.
    If it is a windows problem it's not going to run on the OP's MacBook Pro

  • Problems with Safari and Firefox (HTTP?)

    Problems with Safari and Firefox (HTTP?)
    On a laptop G4, 10.5.8 and Safari 5.02 I experience the following:
    On the account of my oldest daughter everything works fine, i.e. wireless internet works and no problems with mail or safari.
    On the same laptop, on the account of my other daughter, the wireless is OK, she can mail etc. But safari nor firefox works. It says: can’t find server (whatever site) and in the activity window it looks if safari tries to open files (in the safari preferences-folder) in stead of http. Same applies to Firefox, so maybe it has more to do with HTTP in general?
    What goes wrong? What to do? I tried the following on the host terminal (tips from Apple)
    defaults write com.apple.safari WebKitDNSPrefetchingEnabled -boolean false
    and
    defaults delete com.apple.safari WebKitDNSPrefetchingEnabled
    but that did not help,
    Nanne

    I'm still wondering why it happens now at this moment in time...
    PC does seem to be a bit odd & inconsistent, the few times I've tested with it, at least so far as we content filtering goes; and if I remember rightly, you're not the first to report previously ok settings suddenly preventing some or all internet until pc is switched off altogether.
    It may work when re-enabled

  • Haven't been able to use pages for a while.  Keep getting following message.  Have tried reinstalling iWork, but no luck.  Same problems with Keynote and Numbers/Users/scottmcdonald/Desktop/Screen Shot 2012-03-14 at 9.39.52 PM.png

    Haven't been able to use pages for a while.  Keep getting following message.  Have tried reinstalling iWork, but no luck.  Same problems with Keynote and Numbers/

    Have you moved Pages from its installed location? Or just dragged a copy to your current system?
    It can't find some of its resources apparently.
    Peter

  • Problem with DMGs and error: "No Mountable File Systems"

    Problem with DMGs and error: "No Mountable File Systems"
    The files are not corrupt. The problem is occurring with all DMGs that are apparently formatted in MS-DOS FAT16. No the file will not mount with Disk utility or any other disk mounter programs I have found.
    This is now the second time this occurred and now effects my MBP and my iMac. First time i spent days with Apple support and the only solution was ultimately back up the data, reformat the HD, start over from scratch and reload everything. That lasted about a month before the problem resurfaced and is now an issue on both iMac and MBP.
    I tried to identify all the programs I installed immediately before the error, as I am convinced it is the result of a software conflict.
    Recent programs includes:
    1) upgrading from Parallels 5.5 to 6.0 on both machines.
    2) using an HP secure II usb drive and setting up a secure disk.
    3) installing new itunes 10
    4) new update to Flip For Mac.
    The files affected are downloaded dmgs, including personal brain and google earth, both which are formatted in FAT16.
    Any help or thoughts? Apple has now spent hours trying and they say i now have to reformat and wipe and start over. That is unacceptable and based on pasted experience the problem is likely to repeat itself. having to wipe and rebuild a HD ever month is not an solution. i need to fid the root problem.
    In the meantime, anyone got a real solution on how to extract the data for a DMG using a different method?
    Message was edited by: remaia

    Where you able to find the solution, i am having the same problem, all was fine till i install some programs only same one i saw did we both did was flip4mac i uninstalled it but the problem is still there, i also restored and erased the hardrive but im not up to doing that all over again. If you found anything out let me know i would greatly appreciate it

  • Problem with Send and Receive Emal In SAP System

    Hi gurus!
    I have a following quote:
    Dear !
    I have a problem with send and receive email in SAP system following :
    I want to test send and receive email in local network at my company. I
    had two server
    Server 1 : I setup Exchange Mail Server 2007 with domain controller is
    fes.com
    Server 2 : I setup SAP ERP ECC 6.0
    On Server 1 : I created 2 account ( u1Afes.com and u2Afes.com ) and then I tested send and receive email between u1 and u2 in local network through Microsoft Outlook 2007 -> OK
    and then
    On Server 2: I had configured send and receive email on SAP system
    through tcode SBWP, SCOT and SOST as Note 455140 - "Configuration of
    e-mail, fax, paging or SMS using SMTP"
    for example :
    I logged in SAP system with user Basis01 (with email u1Afes.com ) -> then,using tcode SBWP -> new message -> send to u2Afes.com with Internet Mail type and then status message with green light -> sending ok
    and then I have used Microsoft Outlook 2007, I logged with account u2 ->check email -> Ok. I saw message which send from u1
    Finally, My problem is how can receive mail in SAP system without using Microsoft Outlook
    For example:
    Login system SAP with Basis01 account (with  u1Afes.com ) -> tcode SBWP ->New Message -> send to u2Afes.com
    and then
    Login system SAP with Basis02 account (with u2Afes.com ) -> tcode ??? ->
    To receive email from Basis01 (with u1Afes.com )
    Please help me now
    Thanks
    I replace "@" with "A" because of banning email of this forum.
    This quote is about sending email in local network. And we can't receive any email from the outside email address. Addition if I wanna send email to internal email in Internet (we've just tried with email address in local network) What should I config in SAP and Exchange ?
    By the way, Is SAP Server IP added to Relay Agent for sending or receiving mail ?
    Regards
    An NLP
    Edited by: An NLP on Apr 6, 2010 7:03 PM

    Hi,
    This problem is a classic problem of mail routing via Exchange. Exchange like most mail servers use the domain part of the email address as a means to route mails. So I will make an assumption that your main company mail addrss is "User @ fes.com".
    So when you send a mail to the "User @ fes.com mail" address the mail is delivered to your Outlook mail address as this is the default route for company.
    (Q) So how do you get your Exchange server to relay the mail into the sending SAP system?
    (A) The easiest way would be to setup and unique mail domain for your SAP system. I always recommend "user @ client.sid.company.com" which in your case would be "u1 @ 100.PRD.fes.com". You can then instruct Exchange to send any emails addressed to 100.PRD.fes.com domain to your SAP system. Also using this format of address you can configure multiple mail connections into multiple SAP systems.
    (A) Another answer would be to enter the "Full" email address (LOcal and Domain part of address) into the routing rule for Exchange e.g. "U1 @ fes.com" so that all emails addressed to this user will be delivered into SAP. However this method requires a lot of Admin as you will have to update Exchange with ALL email address that need to receive emails. Also if your corporate mail address is "U1 @ fes.com" then all mails will be forwarded to SAP.
    I would definitely NOT recommend this method but the decision is up to you.
    P.S. The IP address of the SAP system is entered into the mail header of the email. This is standard practice in SMTP relay. You can suppress this header in Exchange
    Hope this helps
    Michael

  • Problem with Speaker and Headset in Windows Vista

    Hi, I just got my Macbook Pro 13" and having problem with speaker and headset when working with Windows Vista (I have installed the driver from bootcamp). The sound very weak if I play music from Itunes or youtube even the volume already full and if i put my headset the sound not coming out. Is there anyone can help me to solve this problem?
    Regards,Edwin

    When you post about Windows / Boot Camp, in Mac Pro (workstation) forum where others with a MacBOOK would be more likely to have same hardware configuration, and you won't find Windows drivers on Apple downloads. More like at
    http://www.guru3d.com or other sites, or go to RealTek (if that is the type of audio you have).

Maybe you are looking for