Warm tip: This article is reproduced from stackoverflow.com, please click
changelistener java jtabbedpane swing

JTabbedPane ChangeListener

发布于 2020-03-27 10:20:12

I need to detect when the selected tab changes, and get its index.

The following code works, but it fires the println as many times as the amount of tabs currently loaded:

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

What is the correct way of doing this? Thank you in advance.

Questioner
vemv
Viewed
137
belgther 2011-07-24 05:30

By JDK 6 Update 26 (Windows 7 64-Bit), I only get one event for the following demonstration code:

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

Can you figure out in the debugger why the listener is triggered three times?