JTabbedPane - focus last focused component after tab change
When changing tabs, JTabbed开发者_运维知识库Pane 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.
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();
}
}
}
basically this works inside one Top-Level Container correctly
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
someComponent.grabFocus();
someComponent.requestFocus();//or inWindow
}
});
精彩评论