如何通过单击按钮切换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(); } }
这是类JPane1:
... JLabel label1 = new JLabel(); label1.setText("This is Tab 1"); jp1.add(label1);
和类Jpane2与int上的按钮
JButton test = new JButton(“Press”); jp2.add(测试);
ButtonHandler phandler = new ButtonHandler(); test.addActionListener(phandler); setVisible(true);
所以问题在于Jpanel2上按钮的ActionListener
class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ // what i do now ? to call jpanel 1 show ![alt text][1] } }
如果您使ButtonHandler可以访问选项卡式窗格,则可以执行以下操作:
class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ jtp.setSelectedIndex(0); } }
您可以通过使用getter方法将jtp(理想情况下使用更好的名称)作为私有属性来实现此目的,或者可以将其作为构造函数参数传递给ButtonHandler。
您应该使用方法JTabbedPane.setSelectedIndex(int index)
和所需选项卡的索引。
它很简单:使用下面的代码:
JTabbedpane.setSelectedIndex();
什么名称是你J面板用上面的JTabbedpane替换它,例如你想选择第一个选项卡简单地将0放在括号中,如果你想选择第二个选项卡然后将1放在括号中,例如:我的J选项卡式窗格是调用jtabbedpanel,我想要第一个标签,然后该行看起来像:
jtabbedpanel.setSelectedIndex(0);
希望这可以帮助!!
就像添加一样,您的动作侦听器必须与选项卡位于同一个类中。
只是! 附:
JTabbedPane.setSelectedComponnet(component);
- 尝试将新的Class实例添加到ArrayList时,while循环中出现NullPointerException
- 如何从子类调用重写的父类方法?
- 如何使用hibernate在spring boot中实现分页
- 非常简单的Apache-commons配置检查会抛出ConfigurationRuntimeException
- 为Eclipse安装Checkstyle-Plugin(7.2.0)Neon失败
- java可以系统输出导致内存不足的问题
- 使用Jackson反序列化非字符串映射键
- java.lang.ClassNotFoundException:com.fasterxml.jackson.annotation.JsonInclude $ Value
- 为什么我得到StackOverflowError