JTabbedPane ChangeListener

时间:2011-07-23 10:17:21

标签: java swing jtabbedpane changelistener

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

以下代码有效,但它会触发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
    }
});

这样做的正确方法是什么?提前谢谢。

2 个答案:

答案 0 :(得分:52)

通过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);
}

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

答案 1 :(得分:11)

例如

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() {
    }
}

printOut的

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