When changing tabs, JTabbedPane always focuses the first focusable Component inside the tab. How can I change its behaviour so that it will either focus the last focused component or none at all? Invoking requestFocus afterwards is not an option because JTabbedPane must not set the focus in the wrong field at all.
Asked
Active
Viewed 5,070 times
2 Answers
4
Take a look at: Remembering last focused component.
You need to keep track of which component has focus in each tab. Then when a tab is selected, you need to change focus to the appropriate component. Here is the code taken from the link above:
class TabbedPaneFocus extends JTabbedPane implements ChangeListener, PropertyChangeListener {
private Hashtable tabFocus;
public TabbedPaneFocus() {
tabFocus = new Hashtable();
addChangeListener(this);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(this);
}
/*
* (non-Javadoc)
*
* @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent e) {
if ("permanentFocusOwner".equals(e.getPropertyName())) {
final Object value = e.getNewValue();
if (value != null) {
tabFocus.put(getTitleAt(getSelectedIndex()), value);
}
}
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
@Override
public void stateChanged(ChangeEvent e) {
Object value = tabFocus.get(getTitleAt(getSelectedIndex()));
if (value != null) {
((Component) value).requestFocusInWindow();
}
}
}

dogbane
- 266,786
- 75
- 396
- 414
2
basically this works inside one Top-Level Container correctly
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
someComponent.grabFocus();
someComponent.requestFocus();//or inWindow
}
});

mKorbel
- 109,525
- 20
- 134
- 319
-
How does this prevent JTabbedPane from setting the focus in the first field? – Markus Jul 19 '11 at 13:36
-
@Markus that's depends if first field <> expected field, then yes (and I can't identify what components is field, too) – mKorbel Jul 19 '11 at 13:44