[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 564
  • Last Modified:

Setting focus in a complex panel

I have a BorderLayout main frame whose Center is a GridLayout, 12 rows and 9 columns, and I've set most of the cells (JTextFields) to setEditable( false ).  I want to start with focus on a specific editable cell, but <cellname>.requestFocus() has no effect.  I can successfully shift focus between editable cells once I've established focus, but how do I get the initial focus?
0
Bob_Everard
Asked:
Bob_Everard
  • 2
1 Solution
 
raffaelCommented:
Perhaps you used requestFocus in an incorrect way.
requestFocus() just works if your window with the textfields is already visible.

Best regards, Raffael Vogler
0
 
raffaelCommented:
You could addionally give a try to:

SwingUtilities.invokeLater(new Runnable(){
  public void run(){
    [requestFocus()]
  }
});

Best regards, Raffael Vogler
0
 
yongsingCommented:
You can set focus on a component only when it's visible on screen. What you can do is to add a window listener to your JFrame. When the JFrame is opened (become visible), you set the focus to the cell.

frame.addWindowListener(
  new WindowAdapter() {
    public void windowOpened(WindowEvent e) {
      <cellname>.requestFocus();
    }
  }
);
0
 
Bob_EverardAuthor Commented:
Thanks, raffael, for your prompt answer.

I tried adding the following code round the requestFocus:

      int l = 0;
      while ( !scoreText[ 0 ].isVisible() ) {
         System.out.println( "Waiting(" + ++l +
                             ") for visibility for scoreText[ 0 ]..." );
         l++;
      } // while
      scoreText[ 0 ].requestFocus();
      l = 0;
      while ( !scoreText[ 0 ].hasFocus() ) {
         System.out.println( "Waiting(" + ++l +
                             ") for focus for scoreText[ 0 ]..." );
      } // while

The interesting thing is that sometimes I go through the "Waiting for focus" loop 3 times, sometimes 5, but often I have to force focus by clicking on the field to avoid an infinite wait.  And the whole purpose of this exercise is to avoid having to select focus by hand.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now