如何通过单击按钮切换jTabbedPane中的选项卡?

tie*_*ndv 19 java swing jtabbedpane

我有两个JTabbedPanes,JTabbedPane1和2如何在JTabbedPane2中按下按钮来显示JTabbedPane1?

以下是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();
    }

}
Run Code Online (Sandbox Code Playgroud)

这是类JPane1:

...    JLabel label1 = new JLabel();
       label1.setText("This is Tab 1");
       jp1.add(label1);
Run Code Online (Sandbox Code Playgroud)

和类Jpane2与int上的按钮

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

ButtonHandler phandler = new ButtonHandler();
test.addActionListener(phandler);
setVisible(true); 
Run Code Online (Sandbox Code Playgroud)

所以问题出现在Jpanel2上按钮的ActionListener中

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

替代文字

小智 41

如果您使ButtonHandler可以访问选项卡式窗格,则可以执行以下操作:

class ButtonHandler implements ActionListener{
       public void actionPerformed(ActionEvent e){
              jtp.setSelectedIndex(0);
       }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过使用getter方法将jtp(理想情况下使用更好的名称)作为私有属性来实现此目的,或者可以将其作为构造函数参数传递给ButtonHandler.


Gui*_*ume 7

您应该将该方法JTabbedPane.setSelectedIndex(int index)与所需选项卡的索引一起使用.