0

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?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • Please post some code on how you handle the tab switching. – span Mar 19 '13 at 08:51
  • 2
    1) Why not update 'tab 3' as soon as the user changes tabs 2 or 1? 2) You probably want a `ComponentListener` or an `AncestorListener` on a component in the panel. 3) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Mar 19 '13 at 08:54

1 Answers1

11

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);
}
}
Loki
  • 4,065
  • 4
  • 29
  • 51