Java Swing - 知道是否已在ChangeListener中删除/添加了选项卡

时间:2012-08-20 10:52:22

标签: java swing jtabbedpane changelistener

假设我有一个带有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 个答案:

答案 0 :(得分:7)

如果我没记错的话,JTabbedPane将在添加新标签时触发componentAdded()事件(在Container中定义),如果删除标签,则会触发componentRemoved()事件。

您应该可以通过注册ContainerListener

来收听或删除标签

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

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

答案 1 :(得分:2)

您可能还想检查由__index_to_remove__设置的客户端属性removeTabAt()

答案 2 :(得分: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);

但可能不够好,因为如果删除了所选标签本身,它会触发。

答案 3 :(得分: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);