JTabbedPane track previous tab selection

让人想犯罪 __ 提交于 2019-12-24 01:54:28

问题


I have a class that extends BasicTabbedPaneUI and does some paint component overriding.

I want to be able to add a addMouseListener to the class I use it in to check when the user selects a tab the current tab index and the previous tab index.

NOTE: The user is able to navigate to tabs via the keyboard and not just clicking on a tab and I want to be able to make sure the previous index tracks this. So in the example below preIndex would equal the previous index regardless to whether the user navigated to it via the keyboard or mouse.

Any ideas please?

    tabbedPane.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            JTabbedPane tabP = (JTabbedPane) e.getSource();
            int currIndex = tabP.indexAtLocation(e.getX(), e.getY());

            int prevIndex = ?????
        }
    });

Many thanks!!!!


回答1:


I would use the change listener instead of mouse listener (it's called in both cases: for mouse and key event triggered tab change). If you cannot determine previously selected tab you can use following approach: save currently selected tab index as client property of the tabbed pane.

private static final String OLD_TAB_INDEX_PROPERTY = "oldTabIdx";

tabbedPane.addChangeListener(new ChangeListener() {
  public void stateChanged(ChangeEvent e) {
    JTabbedPane tabP = (JTabbedPane) e.getSource();
    int currIndex = tabP.getSelectedIndex();

    int oldIdx = 0;
    Object old = tabP.getClientProperty(OLD_TAB_INDEX_PROPERTY);
    if (old instanceof Integer) {
      oldIdx = (Integer) old;
    }
    tabP.putClientProperty(OLD_TAB_INDEX_PROPERTY, currIndex);
    // now we can use old and current index
  }
});


来源:https://stackoverflow.com/questions/29719292/jtabbedpane-track-previous-tab-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!