Search code examples
javaswingjtabbedpanechangelistener

How to call a certain function when click on a Tab in Java?


In a panel i have 3 Tabs (using JTabbedPane). The user can do whatever he wants in Tab1 or Tab2, but when he switches to Tab3 I want him to see the results of what he did in Tab2 or Tab1.

How do I do this? I think I have to call a function when the user clicks on Tab3?


Solution

  • You can add a ChangeListener on your TabbedPane. This snippet shows you how to add the Listener and how to indicate which Tab is active:

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    public class TestTabbedPane {
    
    static JTabbedPane p;
    static JFrame f;
    public static void main(String[] args) {
    
        f = new JFrame();
        f.setSize(800,600);
        f.setLocationRelativeTo(null);
    
        p = new JTabbedPane();
        p.addTab("T1", new JPanel());
        p.addTab("T2", new JPanel());
        p.addTab("T3", new JPanel());
    
        p.addChangeListener(new ChangeListener() { //add the Listener
    
            public void stateChanged(ChangeEvent e) {
    
                System.out.println(""+p.getSelectedIndex());
    
                if(p.getSelectedIndex()==2) //Index starts at 0, so Index 2 = Tab3
                {
                    //do your stuff on Tab 3
                }
            }
        });
        f.add(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
    }