0

I am testing our (exam project) application. In this particular case, I'm testing that the textfield behaves as it should when focus changes.

JTextField main = xa.getTextField();
String prompt = "Insert text";
String selected = "";

    assertTrue(!main.isFocusOwner());
    assertTrue(main.getText().equals(prompt));

    main.requestFocusInWindow();

    assertTrue(main.isFocusOwner());
    assertTrue(main.getText().equals(selected));

The last two assertTrue statments throws an assertion error. Why is this? I also tried requestFocus() with same result.

Aphex
  • 408
  • 1
  • 5
  • 17
  • http://stackoverflow.com/questions/17680817/difference-between-requestfocusinwindow-and-grabfocus-in-swing. Maybe try grabFocus. – JP Moresmau May 12 '15 at 19:44

2 Answers2

0

Use grabFocus() :

JTextField main = xa.getTextField();

main.grabFocus();

assertTrue(main.isFocusOwner());

See other solutions here: How to Set Focus on JTextField?

Community
  • 1
  • 1
Arnaud
  • 36
  • 5
0

Components do not gain focus immediately. That is focus requests are executed asynchronously. So when your code executes the change in focus has not been done yet.

Read the section on Requesting Focus. One comment in particular states:

developers must never assume that this Component is the focus owner until this Component receives a FOCUS_GAINED event.

Also read the section on Focus and PropertyChangeListener since the KeyboardFocusManager can listen for all focus changes, so you don't need to add a FocusListener to each component.

camickr
  • 321,443
  • 19
  • 166
  • 288