Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch tabs in jTabbedPane by clicking a Button?

Tags:

I have two JTabbedPanes, JTabbedPane1 & 2 How can I press button in JTabbedPane2 to show JTabbedPane1 ?

Here is the code for JTabbedPane:

public class TabbedPane extends JFrame {      public TabbedPane() {           setTitle("Tabbed Pane");           setSize(300,300);           JTabbedPane jtp = new JTabbedPane();         getContentPane().add(jtp);         JPanel1 jp1 = new JPanel1();//This will create the first tab         JPanel jp2 = new JPanel2();//This will create the second tab         //add panel .........      //example usage      public static void main (String []args){         TabbedPane tab = new TabbedPane();     }  } 

here is class JPane1:

...    JLabel label1 = new JLabel();        label1.setText("This is Tab 1");        jp1.add(label1); 

and class Jpane2 with button on int

JButton test = new JButton("Press"); jp2.add(test);

ButtonHandler phandler = new ButtonHandler(); test.addActionListener(phandler); setVisible(true);  

} so problem is here in ActionListener of button on Jpanel2

class ButtonHandler implements ActionListener{        public void actionPerformed(ActionEvent e){               // what i do now ? to call  jpanel 1 show ![alt text][1]        } } 

alt text

like image 918
tiendv Avatar asked Nov 11 '10 17:11

tiendv


People also ask

Which method is used to add tabs to a JTabbedPane?

To create a tabbed pane, instantiate JTabbedPane , create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.

What is tabbed pane?

The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class.


2 Answers

If you make the tabbed pane accessible to ButtonHandler you can do this:

class ButtonHandler implements ActionListener{        public void actionPerformed(ActionEvent e){               jtp.setSelectedIndex(0);        } } 

You can do this by making jtp (ideally with a better name) a private attribute with a getter method or it can be passed in as a constructor argument to ButtonHandler.

like image 61
Ventral Avatar answered Oct 11 '22 07:10

Ventral


You should use the method JTabbedPane.setSelectedIndex(int index) with the index of the tab you want.

like image 29
Guillaume Avatar answered Oct 11 '22 09:10

Guillaume