How to switch tabs in jTabbedPane by clicking a Button?

白昼怎懂夜的黑 提交于 2019-12-03 11:14:47

问题


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]
       }
}


回答1:


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.




回答2:


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




回答3:


its very simple: use the code below:

JTabbedpane.setSelectedIndex(); 

what ever the name is of you J Panel replace it with the above JTabbedpane and for example you want to select the first tabs simply put 0 in bracket and if you want to select second tab then put 1 in bracket eg: my J tabbed pane is called jtabbedpanel and I want the first tab then the line will look as:

jtabbedpanel.setSelectedIndex(0);

hope this helps!!




回答4:


Just like to add that your action listener has to be in the same class as your tabs.




回答5:


Just! With:

JTabbedPane.setSelectedComponnet(component);


来源:https://stackoverflow.com/questions/4157293/how-to-switch-tabs-in-jtabbedpane-by-clicking-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!