关闭标签后获取焦点标签

Get the in-focus tab after closing a tab

在 JTabbedPane 中,我将一个定制的数据对象关联到每个添加的选项卡。 I also have a corresponding Metadata object that shows up in another panel when the tab is selected.我现在遇到的问题是当一个选项卡关闭时,元数据面板显示刚刚关闭的选项卡中数据对象的元数据。理想情况下,我希望面板显示用户看到的焦点选项卡的元数据。但是,关闭选项卡的行为意味着“选定的选项卡”是正在关闭的选项卡,因此 tabpane.getSelectedIndex() 将不起作用。关闭标签页后如何获取焦点所在的标签页?提前致谢!

细节决定成败,你提供了none。

我做了一个快速测试,发现 ChangeListenerContainerListener 之前被调用,这真的很痛苦,但是,它总是报告正确的索引。

所以,您需要做的是将两者结合在一起,这样,当它们被调用时,它们都会更新元数据窗格。

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JTabbedPane tabbedPane = new JTabbedPane();
                tabbedPane.addTab("One", new TabPane(tabbedPane));
                tabbedPane.addTab("Two", new TabPane(tabbedPane));
                tabbedPane.addTab("Three", new TabPane(tabbedPane));
                tabbedPane.addTab("Four", new TabPane(tabbedPane));

                tabbedPane.addContainerListener(new ContainerListener() {
                    @Override
                    public void componentAdded(ContainerEvent e) {
                    }

                    @Override
                    public void componentRemoved(ContainerEvent e) {
                        System.out.println("Removed " + e.getChild());

                    }
                });

                tabbedPane.addChangeListener(new ChangeListener() {
                    @Override
                    public void stateChanged(ChangeEvent e) {
                        System.out.println(tabbedPane.getSelectedIndex());
                    }
                });

                JFrame frame = new JFrame();
                frame.add(tabbedPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TabPane extends JPanel {
        private JTabbedPane parent;

        public TabPane(JTabbedPane parent) {
            this.parent = parent;
            setLayout(new GridBagLayout());
            JButton btn = new JButton("Close");
            add(btn);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    parent.remove(TabPane.this);
                }
            });
        }

    }

}