JTabbedPane ChangeListener

2022-09-01 01:30:56

我需要检测所选选项卡何时更改,并获取其索引。

以下代码有效,但它触发的次数与当前加载的选项卡数量一样多:println

tabbedPane.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
        System.out.println("Tab: " + tabbedPane.getSelectedIndex());
        // Prints the string 3 times if there are 3 tabs etc
    }
});

正确的方法是什么?


答案 1

通过JDK 6 Update 26(Windows 7 64位),我只得到以下演示代码的一个事件:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setBounds(0, 0, 300, 400);
    frame.setLayout(null);
    final JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("One", new JPanel());
    tabbedPane.addTab("Two", new JPanel());
    tabbedPane.addTab("Three", new JPanel());
    tabbedPane.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            System.out.println("Tab: " + tabbedPane.getSelectedIndex());
        }
    });
    tabbedPane.setBounds(0, 0, 300, 400);
    frame.add(tabbedPane);
    frame.setVisible(true);
}

你能在调试器中找出为什么监听器被触发三次吗?


答案 2

例如

import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TestTabbedPane {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                final JPanel ui = new JPanel(new BorderLayout(1, 1));
                JTabbedPane jtp = new JTabbedPane(JTabbedPane.LEFT);
                jtp.addTab("Apple", new JLabel("Apple"));
                jtp.addTab("Banana", new JLabel("Banana"));
                jtp.addTab("Cherries", new JLabel("Cherries"));
                jtp.addTab("Grapes", new JLabel("Grapes"));
                ui.add(jtp, BorderLayout.CENTER);
                jtp.setPreferredSize(new Dimension(200, 200));
                jtp.addChangeListener(new ChangeListener() {

                    @Override
                    public void stateChanged(ChangeEvent e) {
                        if (e.getSource() instanceof JTabbedPane) {
                            JTabbedPane pane = (JTabbedPane) e.getSource();
                            System.out.println("Selected paneNo : " + pane.getSelectedIndex());
                        }
                    }
                });
            }
        };
        SwingUtilities.invokeLater(r);
    }

    private TestTabbedPane() {
    }
}

打印输出

run:
Selected paneNo : 1
Selected paneNo : 2
Selected paneNo : 3
BUILD SUCCESSFUL (total time: 7 seconds)

推荐