1

I'm working on a Swing application that uses the default Swing methods for handling focus. Focus isn't working as I'd expect.

In one case, I have a JTextField that I call .requestFocusInWindow() When the window is displayed a JLabel has focus instead

The Java 6 docs for JLabel say "As a result, it cannot get the keyboard focus." http://docs.oracle.com/javase/6/docs/api/javax/swing/JLabel.html

However, I have a sample application that shows a JLabel receiving focus and KeyboardFocusManager.getFocusOwner() returns that component. (http://github.com/akinsgre/swingStarter)

The code the the class is https://raw.github.com/akinsgre/swingStarter/master/src/main/java/test/HelloWorldSwing.java

Can anyone help me understand or explain what I'm missing?

Greg
  • 430
  • 1
  • 5
  • 17
  • 3
    most of us not going to the unknow_depots, and for future readers especially, for better help sooner edit your question with an [SSCCE](http://sscce.org/), JLabel and one of focusable JComponent e.g. JTextField with demonstrating your Focus and Focusable – mKorbel Jun 06 '12 at 20:03
  • 3
    No idea why the JLabel would receive focus but a suggestion for your other problem. The javadoc for [requestFocus()](http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#requestFocus(boolean)) recommends to not use that method as it is platform dependent and to use [requestFocusInWindow()](http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Component.html#requestFocusInWindow()) whenever possible. – Danny Jun 06 '12 at 20:10
  • mKorbel: I thought I was doing that. The Github repo (unknown?) is a maven project, with a Single class file. But.. OK. The class file is here https://raw.github.com/akinsgre/swingStarter/master/src/main/java/test/HelloWorldSwing.java (and isn't a link to the source better than pasting the code inline)? – Greg Jun 06 '12 at 23:56
  • Thanks Danny. I use requestFocusInWindow in the source. But that doesn't give me any different results. – Greg Jun 06 '12 at 23:57
  • 1
    *"I have a JTextField that I call .requestFocus()"* That is not what is suggested by the line in `HelloWorldSwing` that states `label.requestFocusInWindow();` – Andrew Thompson Jun 07 '12 at 05:24

1 Answers1

1

I think you need to associate the label with the text field. So try using the setLabelFor method and see if that helps.

  • Thanks Bill That doesn't change the behavior. The JLabel still can have Focus. I can avoid the problem by using setFocusable(false).. that still doesn't clear up why the docs seem to disagree with behavior of the JLabel – Greg Jun 07 '12 at 14:41