JTabbedPane - 在标签更改后关注最后关注的组件

时间:2011-07-19 13:19:01

标签: java swing focus jtabbedpane

更改选项卡时,JTabbedPane始终将第一个可聚焦组件聚焦到选项卡中。 如何更改其行为以使其聚焦最后一个聚焦组件或根本不聚焦? 之后调用requestFocus不是一个选项,因为JTabbedPane根本不能将焦点设置在错误的字段中。

2 个答案:

答案 0 :(得分:4)

看看:Remembering last focused component

您需要跟踪每个标签中哪个组件具有焦点。然后,选择选项卡时,需要将焦点更改为适当的组件。以下是从上面的链接中获取的代码:

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();
        }
    }
}

答案 1 :(得分:2)

基本上这可以在一个Top-Level Container内正确

EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         someComponent.grabFocus();
         someComponent.requestFocus();//or inWindow
     }
});