如何通过单击按钮切换jTabbedPane中的选项卡? [英] How to switch tabs in jTabbedPane by clicking a Button?

查看:1008
本文介绍了如何通过单击按钮切换jTabbedPane中的选项卡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以下是JTabbedPane的代码:

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

}

这里是JPane1类:

here is class JPane1:

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

和类Jpane2与int上的按钮

and class Jpane2 with button on int

JButton测试=新JButton(按);
jp2.add(test);

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

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

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

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

推荐答案

如果你使ButtonHandler可以访问选项卡式窗格,你可以这样做:

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);
       }
}

你可以通过制作jtp(理想情况下是更好的名称)带有getter方法的私有属性,或者它可以作为构造函数参数传递给ButtonHandler。

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.

这篇关于如何通过单击按钮切换jTabbedPane中的选项卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆