4

假设我有带有 ChangeListener 的 JTabbedPane

JTabbedPane tabbedPane = new JTabbedPane();

// Add few tabs
.....
.....

tabbedPane.addChangeListener(new ChangeListener() {
  public void stateChanged(ChangeEvent changeEvent) {
    // How to determine if the changeEvent was fired because of a tab remove/add ?
  }
});

在某个地方我正在做一个

tabbedPane.removeTabAt(2);

和其他地方

tabbedPane.add(panel, 0);

ChangeListener 现在应该被触发,有没有办法在监听器中确定它是否由于标签删除/添加而被调用?

编辑:我基本上只是在用户在选项卡之间切换而不是在添加或删除时才尝试执行一些操作。

4

4 回答 4

7

如果我没记错的话,JTabbedPane 将componentAdded()在添加新选项卡时触发一个事件(在容器中定义),componentRemoved()如果删除一个选项卡,则会触发一个事件。

您应该能够通过注册ContainerListener来监听选项卡的添加或删除

http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#addContainerListener(java.awt.event.ContainerListener)

stateChanged()事件只是添加的副作用,因为 JTabbedPanel 会自动切换到新选项卡。

于 2012-08-20T11:10:09.430 回答
2

You might also want to examine the client property __index_to_remove__, which is set by removeTabAt().

于 2012-08-20T11:18:27.050 回答
2

根据确切的要求,您可能会跟踪所选组件,并且仅在发生更改时才执行操作:

ChangeListener l = new ChangeListener() {

    Component lastSelected = tabbedPane.getSelectedComponent();
    @Override
    public void stateChanged(ChangeEvent e) {
        if (lastSelected != tabbedPane.getSelectedComponent()) {
            LOG.info("changed: " + tabbedPane.getSelectedIndex());
            lastSelected = tabbedPane.getSelectedComponent();
        }

    }
};
tabbedPane.addChangeListener(l);

但是,可能还不够好,因为如果选定的选项卡本身被删除,它将触发。

于 2012-08-20T11:51:32.997 回答
0

通过跟踪当前选项卡的数量,您可以检测基于添加或删除的选择更改

ChangeListener l = new ChangeListener() {

    int lastTabCount = tabbedPane.getTabCount();
    Component lastSelected = tabbedPane.getSelectedComponent();

    @Override
    public void stateChanged(ChangeEvent e) {
        if (lastSelected != tabbedPane.getSelectedIndex())
        {
            int currentTabCount = tabbedPane.getTabCount();
            if (lastTabCount == currentTabCount ) {
                LOG.info("changed: " + tabbedPane.getSelectedIndex());
            } else if (lastTabCount < currentTabCount)
                LOG.info("changed due to delete: " + tabbedPane.getSelectedIndex());
            } else if (lastTabCount > currentTabCount)
                LOG.info("changed due to add: " + tabbedPane.getSelectedIndex());
            }
            lastTabCount = tabbedPane.getTabCount();
            lastSelected = tabbedPane.getSelectedComponent();
        }

    }
};
tabbedPane.addChangeListener(l);
于 2014-01-07T22:00:51.050 回答