JDesktopPane / JInternalFrames and Focus

Hi,
I am running into a confusing focus issue with JDesktopPane and JInternalFrames. The problem is that when I close a JInternalFrame that has the keyboard focus, the DesktopPane will activate another internal frame, but that internal frame doesn't get the keyboard focus. I thought that some of my extension classes might be screwing this up, but I can recreate the problem using just the basic JDesktopPane and JInternalFrame objects. Has anyone run into this before? If so, how have you gotten around it? I'm using JDK 1.5 and the default Metal LAF.
I have included a little application that demonstrates the issue. Click on one frame, then click on another frame and close this frame. The first frame will be active (ie highlighted), but it doesn't own the keyboard focus. Acutally the first frame gains the focus and then immediately looses the focus.
Thanks for any help,
-Yeath
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DesktopTest extends JFrame
   private JDesktopPane desktop_pane;
   private int number;
   public DesktopTest()
      super( "DesktopTest Application" );
      this.desktop_pane = new JDesktopPane();
      this.number = 0;
      this.getContentPane().setLayout( new BorderLayout() );
      this.getContentPane().add( this.desktop_pane, BorderLayout.CENTER );
      JMenuBar menu_bar = new JMenuBar();
      JMenu file_menu = new JMenu( "File" );
      file_menu.add( new AbstractAction( "New Frame", null )
         public void actionPerformed( ActionEvent e )
            newFrame();
      menu_bar.add( file_menu );
      this.setJMenuBar( menu_bar );
      for( int i = 0; i < 4; i++ )
         newFrame();
   private void newFrame()
      final JInternalFrame jif = new JInternalFrame( "Frame " + Integer.toString( number + 1 ), true, true, true );
      jif.getContentPane().setLayout( new BorderLayout() );
      JTextField jtf = new JTextField();
      jif.getContentPane().add( jtf );
      jif.setBounds( number * 30, number * 30, 150, 100 );
      jtf.addFocusListener( new FocusListener()
         public void focusGained( FocusEvent e )
            System.out.println( jif.getTitle() + " has gained the focus" );
         public void focusLost( FocusEvent e )
            System.out.println( jif.getTitle() + " has lost the focus" );
      this.desktop_pane.add( jif );
      jif.setVisible( true );
      this.number++;
   public static void main( String[] args )
      DesktopTest desktop = new DesktopTest();
      desktop.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      desktop.setSize( 800, 800 );
      desktop.setVisible( true );
}

Thanks for the replies,
This sounds very much like the bug that has already been reported. But the work around doesn't seem to solve the problem. I catch the internalFrameClosed() event, and have the newly selected frame request the keyboard focus. But still I run into the situation where the frame gets the focus and immediately looses it again. If you look at the debug statements when executing the app, you'll see what i mean.
Here is my updated newFrame function
private void newFrame()
   final JInternalFrame jif = new JInternalFrame( "Frame " + Integer.toString( number + 1 ), true, true, true, true );
   jif.getContentPane().setLayout( new BorderLayout() );
   final JTextField jtf = new JTextField();
   jif.getContentPane().add( jtf );
   jif.setBounds( number * 30, number * 30, 150, 100 );
   jif.addInternalFrameListener( new InternalFrameAdapter()
      public void internalFrameActivated( InternalFrameEvent e )
         jtf.requestFocusInWindow();
      public void internalFrameClosed( InternalFrameEvent e )
         JInternalFrame selected = desktop_pane.getSelectedFrame();
         if( selected != null )
            selected.requestFocus();
   jtf.addFocusListener( new FocusListener()
      public void focusGained( FocusEvent e )
         System.out.println( jif.getTitle() + " has gained the focus" );
      public void focusLost( FocusEvent e )
         System.out.println( jif.getTitle() + " has lost the focus" );
   this.desktop_pane.add( jif );
   jif.setVisible( true );
   this.number++;
}When I run this, and close a frame, I get the following debug output: It is as if nothing owns the keyboard focus after closing a frame.
Frame 2 has lost the focus
Frame 1 has gained the focus
Frame 1 has lost the focusThanks for your help,
-Yeath

Similar Messages

  • [svn] 3079: Pop up and focus fixes.

    Revision: 3079
    Author: [email protected]
    Date: 2008-09-03 10:53:07 -0700 (Wed, 03 Sep 2008)
    Log Message:
    Pop up and focus fixes.
    QE: YES
    Doc:
    Checkintests: YES
    Reviewer: Alex
    Bugs: SDK-16669, SDK-15688
    mx/events/SWFBridgeEvent.as
    Add marshal() method. Update ASDoc.
    mx/managers/FocusManager.as
    Fix bug SDK-15688. Type coercion error fixed by moving to a common super class of IFocusManagerComponent and SWFLoader.
    mx/managers/PopUpManagerImpl.as
    Renaming.
    airframework/src/mx/managers/WindowedSystemManager.as
    mx/managers/SystemManager.as
    Fix problems introduced from API scrub and fix an old problem activating A.2.2.
    mx/managers/SystemManagerProxy.as
    Override addEventListener() and removeEventListener() to also add listeners on the proxied SystemManager. This
    allows the Proxy to get keyboard focus events that happen in the proxied SystemManager. Dispatch activate/deactivate messages to the sandbox root.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-16669
    http://bugs.adobe.com/jira/browse/SDK-15688
    http://bugs.adobe.com/jira/browse/SDK-15688
    Modified Paths:
    flex/sdk/branches/3.0.x/frameworks/projects/airframework/src/mx/managers/WindowedSystemMa nager.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/events/SWFBridgeEvent.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/FocusManager.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/PopUpManagerImpl.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/SystemManager.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/SystemManagerProxy. as

    I would suggest not to use JWindow but JPopupMenu! In
    the JPopupMenu you can add any swing-components!
    You can show the Popup in focusGained (ok, that is
    not so user-friendly, in my opinion a shortcut would
    do better!).
    The Popup will hide automatically if you click with
    the mouse somewhere else or hit escape.Thank you for the reply.
    I'm still having problems. I'd prefer not to use a jpopupmenu, because I want to use that for something else. This was just going to be a simple list that would appear near the text field so user could have a list of options to choose from.
    Focus gained on the textfield brings up the list. Selecting something on the list clears it (hides). This idea works well on the mac. But on the pc the jwindow keeps hiding behind the main frame ?
    I have the following code
    The windows is created as follows
         listWindow = new JWindow(SwingUtilities.getWindowAncestor(this));
    listWindow.getContentPane().add(pane);
    listWindow.setVisible(false);
    pane contains the jlist of values
    Then the textfield is as follows
    textField.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusGained(java.awt.event.FocusEvent evt) {
    if (showListWindow) {
    if (!listWindow.isVisible()) {
    Point los = getLocationOnScreen();
    listWindow.setVisible(true);
    listWindow.setLocation(los.x +580, los.y +75);
    listWindow.pack();
    listWindow.toFront();
              textField().requestFocus();
    I use a boolean showListWindow to decide when to show. Because I noticed that displaying the jlist and requesting focus to the textfield caused the focusGain to fire again.
    Any ideas why the pc keeps the list hidden ? If I move the main frame I can see !

  • AWT and focusing on different windows

    Hey guys.
    I have a problem, I'm trying to set the focus a window but can't.
    I have two windows A and B.
    I also have a Events being picked up set on window A.
    So the set of events are detailed as follows.
    Window A display's and responds to events.
    When a particular event occurs it loads up a new window (WindowB) and focus is given to that window.Wasn't a problem until we realised that there was a delay between Window A being displayed and Window B being displayed, enough to cause a problem.
    So the code was changed like follows.
    WindowB.pack();
    WindowB.setVisible(true);
    WindowA.setVisible(false);When it was changed to the above, we lost the ability to pick up keyboard events, as WindowA was still the window with focus.
    I've had a look at the KeyboardFocusManager where it seems that focus can be change between components.
    However is also states for method setGlobalFocusWindow() that it can only be set if it is in the same context.
    Which it is not.
    Is it possible to set focus to the window before the window has been set visible? Is KeyboardManager the right class to look at?
    Sorry about the lack of code(It's spread in many directions and is sensitive)
    Thanks for any help in advance

    hello,
    the following link may help: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
    wrappingduke

  • Web browser resets scroll position and focus when page load completes

    when a page is loading, the scroll position of the page reverts to the top-left and focus in a form element is lost whenever an element or the whole page finishes loading
    Post relates to: Pre p100eww (Sprint)

    Possibly related to the OP's question, I wish we could get the composition page to scroll when typing a reply here on the forum (while using my Pre plus).
    Quoting a reply fills half the text box, then once I reach the bottom of the box, I can't scroll any further downward to complete my reply...
    WyreNut
    I am a Volunteer here, not employed by HP.
    You too can become an HP Expert! Details HERE!
    If my post has helped you, click the Kudos Thumbs up!
    If it solved your issue, Click the "Accept as Solution" button so others can benefit from the question you asked!

  • urgent when jinternalframe lose focus

    i want do something when the jinternalframe lose focus but the focuslistener of java only listener to keystroke focus.
    anyone know how can i listener to the jinternalframe losing focus?

    have u looked into InternalFrameListener? if not then it out in the JDK documentation.....
    asrar

  • My iphone6 camera is rear , and focus dosnt work in it , although my front camera is working great

    My iphone6 camera is rear , and focus dosnt work in it , although my front camera is working great

    Hey there Aydarezania,
    It sounds like you are able to focus using the front camera, but the back one doesnt seem to. I would use these troubleshooting steps from the following article, named:
    Get help with the camera on your iPhone, iPad, or iPod touch
    Force the app to close, then open the Camera app again.
    Restart your device, then open the Camera app again.
    Your photos are blurred or out of focus
    If your photos are blurred, out of focus, or have dark spots, try these steps:
    Make sure that the camera lens is clean. If you need to clean the lens, use a microfiber cloth. If you see dirt or debris inside the lens, take your device to an Apple Retail Store or Authorized Service Provider for more help.
    Make sure that there’s nothing blocking the camera lens. If you’re using a case, try removing it.
    With iPhone 6 Plus, a metallic case or magnetic lens could interfere with optical image stabilization. If you have a metallic case or magnetic lens attachment, try taking a picture without it. Then compare the quality.
    Adjust the focus by tapping on the person or object in the preview screen. You’ll see the screen pulse or briefly go in and out of focus as the camera adjusts. In photo mode, try to stay steady when adjusting the focus. If you move too far in any direction, the camera will automatically refocus to the center. In video mode, you can adjust the focus before you begin recording.
    If the color seems too bright, or you see double-exposures of moving objects, make sure that HDR is set to Auto or Off. Tap HDR at the top of the screen to choose a different setting.
    Thank you for using Apple Support Communities.
    Cheers,
    Sterling

  • Problem while adding both Key And Focus Listeners to JTextField

    Hi!
    I have something peculiar while adding Key and Focus Listener to JTextField. Suppose i add just Key Listener then everything's fine and i could keep track of keys being pressed. But as soon as i add a Focus Listener to it with the code to select full text in focusGained() method, it starts reponding wrongly to arrow keys pressed and does not perform desired actions. For let arrow key it moves caret by one for the first time after that it does not resond to that unless caret is changed by using mouse. If right arrow key is pressed the it moves the caret to last position from wherever it is. For UP and DOWN it selects the full text(This should be done when it gets focus)
    public void focusGained(FocusEvent fe)
    setCaretPosition(0);
    moveCaretPosition(getDocument().getLength());
    Can someone help me out on this?
    thanks and regards,
    Amit.

    None of those things will cause your JFrame to resize itself. And this is probably a good thing, because your JFrame shouldn't change size once you have created it. Why not create your JPanel so that it has enough space for you to add the component later? Or why not just add the component to start with and then enable it or make it editable when you decide that's necessary?

  • What's focus-angle and  focus-distance in CSS radial-gradients?

    Reading the reference ( http://docs.oracle.com/javafx/2.0/api/javafx/scene/doc-files/cssref.html#typepaint ) I found these two values you can set in a radial-gradient definition:
    radial-gradient([ *focus-angle* <angle>, ]? [ *focus-distance* <percentage>, ]? [ center <point>, ]? radius [ <length> | <percentage> ] [ [ repeat | reflect ], ]? <color-stop>[, <color-stop>]+)
    Could someone enlighten me what they mean? I wrote a little tool for visual definition of Gradients (http://88.198.17.44/blog/2012/04/13/it-works-fxexperience-tools-gradienteditor-plugin/) as an extension to FXExperience Tools, and I'd like to include it if it makes sense.
    Thanks
    Toni

    focus-angle and focus-distance are together used to determine the focal point of the radial pattern.
    See this image: http://www.webdesign.org/img_articles/6822/gradient.jpg

  • Plazmic CDK 4.6 caret and focus button issues

    I hope I'm posting in the right thread? This is regarding the Plazmic CDK 4.6 for Blackberry - to create your own themes.
    Ok. I think I some what get the hang of Plazmic CDK 4.6 except for a few things.
    I use ArcSoft PhotoStudio to make color changes to certain things. However, in the Today style, when I try to change the 'caret' color, which is that selection bar, no matter how much I resize it, it always looks really thick, almost covering the top of the 2nd line (see image below).
    Also, when I try to change the focus circle, I open it with PhotoStudio and it changes the circle to this circle with a box around it, so when I try to change the color, it turns out like this (see picture below)
    I also have issues with using a transparent background if I upload and make minor changes to an icon (see picture below). So I found this american flag icon, altered the pic to make the colors darker, then it adds this white background instead of keeping it transparent.
    Is there a better program I could be using? Or any idea how to make these changes with this program? Or where can I find 'caret' and 'focus' icons so I don't have to worry about changing the colors.
    Sorry if I sound confusing, hopefully someone understands what I'm saying?
    Thanks!

    you can only use Plazmik, sorry.
    about transparency, when you use your drawing software and save the images, do you use a format that supports transparency ? There are two : GIF and PNG. All others add an opaque background color.
    The search box on top-right of this page is your true friend, and the public Knowledge Base too:

  • GridBagLayout: JInternalFrames and internal JDesktopPanes?

    What I want:
    A JToolbar a the top of my main JFrame and a JPanel (status bar) at the bottom of my frame that stretches/shrinks with the screen.
    AND JInternalFrames in the center area (the number is arbitrary and the position is -- for now -- arbitrary). These frames are NOT effected by any resizing of the main JFrame window.
    My problem:
    With all the components added to the JFrame, the JToolbar and JPanel are placed fine, but the JInternalFrames won't allow me to resize them -- i.e., when I drag the iframe(s) to a new size, not only do they revert back to the original size, but sometimes the frame will reposition itself within the frame altogether!! And even sometimes a graphic glitch will occur and suddenly two instances of my iframe(s) will appear (only one will actually be functional)! Plus, when I try to iconify one of the iframes, its desktopicon moves to the absolute bottom of the JFrame, and shifts my JPanel on top of it!
    I tried adding an internal JPanel to try to isolate my inner iframes from the nasty GB's effects and to try to make an, but it seems like the parent GridBagLayout still had an effect on the JPanel's contents.
    Is there a way to:
    1) allow the JInternalFrames to freely resize, and
    2) place an "internal JDesktopPane" so that when I iconify iframes, the desktopIcon appears above my JPanel status bar?
    Thank you for any help!
    Paul

    Here is some code (I don't recommend using GridBagLayout's, it's often much easier and flexible to use nested containers).
    JDesktopPane desktopPane = new JDesktopPane();
    JPanel toolbarContainer = new JPanel(new BorderLayout());
    toolbarContainer.add(myToolBar, BorderLayout.NORTH);
    toolbarContainer.add(desktopPane, BorderLayout.CENTER);
    JPanel main = new JPanel(new BorderLayout());
    main.add(toolbarContainer, BorderLayout.CENTER);
    main.add(myStatusBar, BorderLayout.SOUTH);

  • Wierd problem regarding JInternalFrames and OUTLINE_DRAG_MODE

    Hi there,
    I'm currently experiencing a strange problem regarding the use of a JDesktopPane and JInternalFrames.
    Code may look as this, its a random Example as I encounter the same results no matter how I construct the Frame and so on:
    public class Example extends JFrame{
        public Example() {
            this.setTitle("Example");
            this.setPreferredSize(new Dimension(800,800));
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            JPanel contentPane = (JPanel) this.getContentPane();
            contentPane.setLayout(new BorderLayout());
            JDesktopPane dp = new JDesktopPane();
            dp.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
            contentPane.add(dp, BorderLayout.CENTER);
            this.setVisible(true);
            JInternalFrame f = new JInternalFrame("not so cool", true);
            f.setPreferredSize(new Dimension(400,400));
            f.pack();
            dp.add(f);
            f.setVisible(true);
        public static void main(String args[]){
            Example ex = new Example();
    }So, I'm currently using Netbeans and when I'm running any application/project with those settings from inside the IDE
    theres absolutley no problem. As soon as I'm running the Jar file, the drawing of the "outlines" while resizing the InternalFrame
    is kinda laggy and choppy as hell. I spent 2 hours of googling now and I still got no idea why thats the case, so I hope anyone
    here can enlighten me.
    The Java version installed is 1.6.0_10
    regards, me

    AndrewThompson64 wrote:
    (shrugs) Maybe the IDE is using -Dsun.java2d.d3d=false? In any case, very few people around here provide support* for IDEs.
    * Read that as 'speculate on why an IDE does it different - why it works in an IDE'Sir, seems like you got the point, I wasnt familiar with those command line options for the VM before, regarding Graphics options.
    Working fine as soon as I disable D3D. Should've come to that myself but oh well -.-.
    Thanks guys!

  • Problem with applet, popup window and focus loss

    Hi all !
    I've got a problem when my applet lose the focus. Let me explain :
    I've got an applet embed in a jsp page. There are several buttons in it that allow the user to open modal windows.
    The problem comes when the user gives the focus to another application whithout closing the modal window first.
    When he tries to come back to the web page owning the applet (using the task bar), then the modal window stays behind it and blocks any action on the applet.
    Does anyone know how to force the modal window to be displayed in front of the applet, even when the user plays with focuses ?
    Thank's in advance.

    thank you for your help, sils.
    I've written that code :
    * Cr�� le 31 ao�t 05
    package com.scor.apricot.web.rpc.ltnp.applet.listener.ldf;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    public class AppletWindowListener extends WindowAdapter {
         private JPanel panel;
         private JDialog dialogWindow;
         public AppletWindowListener(JPanel panel, JDialog dialogWindow) {
              this.panel = panel;
              this.dialogWindow = dialogWindow;
         public void windowActivated(WindowEvent e) {
              if (dialogWindow!=null && dialogWindow.isShowing())
                   dialogWindow.toFront();
    }Is that right ?
    I don't know how to add the listener, where must I put the addWindowListener method ? It seems that this method cannot be used with a JApplet object.

  • JOptionPane.showInputDialog and Focus

    I have a program that allows the user to type in a String in a text box and when they hit the enter key the text will appear in a text area. I've also added a menu bar to the program. When the user clicks on File and then Connect from the menu bar I want a JOptionPane to pop up that asks for the user to type in a username and then prompt for a password. And I've gotten all of that to work. Now for the problem. I click on file from the menu bar and then connect and it prompts me for the username as it should. I am able to just type in a phrase in the text field of the username dialog box and hit the enter key and then it prompts me for my password. I am still able to type in a phrase in the text field of the password Dialog box, however when I hit the enter key, the Dialog box does not close as it did for the username Dialog box. It will still close if I click on the OK button, but just pressing the enter key does not close the Dialog box as it did when it prompted for a username. I'm thinking I need to direct the focus to the password dialog box, but not sure how to go about doing this. Any help in solving this problem would be greatly appreciated.
    Here is my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class TestJOptionPane extends JFrame implements ActionListener{
         private static int borderwidth = 570;
         private static int borderheight = 500;
         private JPanel p1 = new JPanel();
         private JMenu m1 = new JMenu("File");
         private JMenuBar mb1 = new JMenuBar();
         private JTextArea ta1 = new JTextArea("");
         private JTextField tf1 =new JTextField();
         private Container pane;
         private static String s1, username, password;
         private JMenuItem [] mia1 = {new JMenuItem("Connect"),new JMenuItem("DisConnect"),
              new JMenuItem("New..."), new JMenuItem ("Open..."), new JMenuItem ("Save"),
              new JMenuItem ("Save As..."), new JMenuItem ("Exit")};
    public TestJOptionPane (){
         pane = this.getContentPane();
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
         dispose();
    System.exit(0);
         setJMenuBar(mb1);
    mb1.add(m1);
    for(int j=0; j<mia1.length; j++){
         m1.add(mia1[j]);
    p1.setLayout( new BorderLayout(0,0));
    setSize(borderwidth, borderheight);
    pane.add(p1);
              p1.add(tf1, BorderLayout.NORTH);
              p1.add(ta1, BorderLayout.CENTER);
              this.show();
              tf1.addActionListener(this);
              for(int j=0; j<mia1.length; j++){
                   mia1[j].addActionListener(this);
         public void actionPerformed(ActionEvent e){
              Object source = e.getSource();
              if(source.equals(mia1 [0])){
                   username = JOptionPane.showInputDialog(pane, "Username");
                   password = JOptionPane.showInputDialog(pane, "Password");
              if(source.equals(tf1)){
                   s1=tf1.getText();
                   ta1.append(s1+"\n");
                   s1="";
                   tf1.setText("");
         public static void main(String args[]){
              TestJOptionPane test= new TestJOptionPane();
    }

    But using JOptionPane doesn't get the focus when you call itworks ok like this
    import javax.swing.*;
    import java.awt.event.*;
    class Testing
      public Testing()
        final JPasswordField pwd = new JPasswordField(10);
        ActionListener al = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            pwd.requestFocusInWindow();}};
        javax.swing.Timer timer = new javax.swing.Timer(250,al);
        timer.setRepeats(false);
        timer.start();
        int action = JOptionPane.showConfirmDialog(null, pwd,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
        if(action < 0)JOptionPane.showMessageDialog(null,"Cancel, X or escape key selected");
        else JOptionPane.showMessageDialog(null,"Your password is "+new String(pwd.getPassword()));
        System.exit(0);
      public static void main(String args[]){new Testing();}
    }

  • JComboBox.setPopupVisible() and focus

    Hello,
    the following code demonstrates that always when the combobox is editable and the standard focus sequence is modified, a setPopupVisible(true) indeed opens the popup, but it is immediately closed again. Is anything wrong with the code?
    Although there are quite a number of JComboBox bugs in the database, I did not find this one. If it is a bug, of course I would be interested in a workaround.
    Regards
    J�rg
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Y extends JFrame
      private JComboBox cmb;
      public Y()
      { setSize(300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container cp= getContentPane();
        cp.setLayout(null);
        final JCheckBox cb= new JCheckBox("Combo editable");
        cb.setBounds(80,30,130,20);
        cb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
         cmb.setEditable(cb.isSelected());
        final JTextField tf1= new JTextField();
        tf1.setBounds(50,60,60,20);
        tf1.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
         if (!tf1.getText().equals("ee")) {
           cmb.requestFocusInWindow(); // Prevents popup to stay open.
           cmb.setPopupVisible(true);
           System.out.println(cmb.isVisible());
        JTextField tf2= new JTextField();
        tf2.setBounds(150,60,60,20);
        tf2.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
         cmb.setPopupVisible(true);
        cmb = new JComboBox(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"});
        cmb.setBounds(100,90,50,20);
        cmb.setSelectedIndex(-1);
        System.out.println("LightWeight: "+cmb.isLightWeightPopupEnabled());
        cp.add(cb);
        cp.add(tf1);
        cp.add(tf2);
        cp.add(cmb);
        setVisible(true);
        tf1.requestFocusInWindow();
      public static void main(String args[])
      { java.awt.EventQueue.invokeLater(new Runnable()
        { public void run()
          { new Y();
    }

    Well, there's two things I note. The first is you're printing out the comboBox's visible status, which is always true, when you're probably trying to get the comboBox's popup's visible status.
    The second thing is the cause of your problem. You request focus on the combo box. When it is editable, however, it is the editor component that gets the focus, not the combo box. So, the popup is made visible and then the editor component loses focus because the combo box gets focus, and so the popup is hidden.
    This change does what you want, I think:
        tf1.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
        if (!tf1.getText().equals("ee")) {
            if ( cmb.isEditable() )
                cmb.getEditor().getEditorComponent().requestFocusInWindow();
            else
                cmb.requestFocusInWindow(); // Prevents popup to stay open.
          cmb.setPopupVisible(true);
          System.out.println(cmb.isVisible());
        });

  • Problem with custom control and focus

    I've a problem with the focus in a custom control that contains a TextField and some custom nodes.
    If i create a form with some of these custom controls i'm not able to navigate through these fields by using the TAB key.
    I've implemented a KeyEvent listener on the custom control and was able to grab the focus and forward it to the embedded TextField by calling requestFocus() on the TextField but the problem is that the TextField won't get rid of the focus anymore. Means if i press TAB the first embedded TextField will get the focus, after pressing TAB again the embedded TextField in the next custom control will get the focus AND the former focused TextField still got the focus!?
    So i'm not able to remove the focus from an embeded TextField.
    Any idea how to do this ?

    Here you go, it contains the control, skin and behavior of the custom control, the css file and a test file that shows the problem...
    control:
    import javafx.scene.control.Control;
    import javafx.scene.control.TextField;
    public class TestInput extends Control {
        private static final String DEFAULT_STYLE_CLASS = "test-input";
        private TextField           textField;
        private int                 id;
        public TestInput(final int ID) {
            super();
            id = ID;
            textField = new TextField();
            init();
        private void init() {
            getStyleClass().add(DEFAULT_STYLE_CLASS);
        public TextField getTextField() {
            return textField;
        @Override protected String getUserAgentStylesheet() {
                return getClass().getResource("testinput.css").toExternalForm();
        @Override public String toString() {
            return "TestInput" + id + ": " + super.toString();
    }skin:
    import com.sun.javafx.scene.control.skin.SkinBase;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.EventHandler;
    import javafx.scene.control.TextField;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    public class TestInputSkin extends SkinBase<TestInput, TestInputBehavior> {
        private TestInput control;
        private TextField textField;
        private boolean   initialized;
        public TestInputSkin(final TestInput CONTROL) {
            super(CONTROL, new TestInputBehavior(CONTROL));
            control     = CONTROL;
            textField   = control.getTextField();
            initialized = false;
            init();
        private void init() {
            initialized = true;
            paint();
        public final void paint() {
            if (!initialized) {
                init();
            getChildren().clear();
            getChildren().addAll(textField);
        @Override public final TestInput getSkinnable() {
            return control;
        @Override public final void dispose() {
            control = null;
    }behavior:
    import com.sun.javafx.scene.control.behavior.BehaviorBase;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.EventHandler;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    public class TestInputBehavior extends BehaviorBase<TestInput> {
        private TestInput control;
        public TestInputBehavior(final TestInput CONTROL) {
            super(CONTROL);
            control = CONTROL;
            control.getTextField().addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
                @Override public void handle(final KeyEvent EVENT) {
                    if (KeyEvent.KEY_PRESSED.equals(EVENT.getEventType())) {
                        keyPressed(EVENT);
            control.focusedProperty().addListener(new ChangeListener<Boolean>() {
                @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean wasFocused, Boolean isFocused) {
                    if (isFocused) { isFocused(); } else { lostFocus(); }
        public void isFocused() {
            System.out.println(control.toString() + " got focus");
            control.getTextField().requestFocus();
        public void lostFocus() {
            System.out.println(control.toString() + " lost focus");
        public void keyPressed(KeyEvent EVENT) {
            if (KeyCode.TAB.equals(EVENT.getCode())) {
                control.getScene().getFocusOwner().requestFocus();
    }the css file:
    .test-input {
        -fx-skin: "TestInputSkin";
    }and finally the test app:
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    public class Test extends Application {
        TestInput input1;
        TestInput input2;
        TestInput input3;
        TextField input4;
        TextField input5;
        TextField input6;
        Scene     scene;
        @Override public void start(final Stage STAGE) {
            setupStage(STAGE, setupScene());
        private Scene setupScene() {
            input1 = new TestInput(1);
            input2 = new TestInput(2);
            input3 = new TestInput(3);
            input4 = new TextField();
            input5 = new TextField();
            input6 = new TextField();
            GridPane pane = new GridPane();
            pane.add(input1, 1, 1);
            pane.add(input2, 1, 2);
            pane.add(input3, 1, 3);
            pane.add(input4, 2, 1);
            pane.add(input5, 2, 2);
            pane.add(input6, 2, 3);
            scene = new Scene(pane);
            return scene;
        private void setupStage(final Stage STAGE, final Scene SCENE) {
            STAGE.setTitle("Test");
            STAGE.setScene(SCENE);
            STAGE.show();
        public static void main(String[] args) {
            launch(args);
    The test app shows three custom controls on the left column and three standard textfields on the right column. If you press TAB you will see what i mean...

Maybe you are looking for