JTabbedPane:从其他 类 调用标签

JTabbedPane: call tabs from other classes

这就是问题所在:我构建了一个 JTappedPane 应用程序。我为每个选项卡制作了一个单独的 class:

MainFrame

public MainFrame () {
    StartTab startTab = new StartTab();
    KundeTab kundeTab = new KundeTab();
    ProjektTab projektTab = new ProjektTab();
    StimmzettelTab stimmzettelTab = new StimmzettelTab();
    ExportTab exportTab = new ExportTab();

    JTabbedPane jtp = new JTabbedPane();
    jtp.addTab("xxx",startTab);
    jtp.addTab("xxx",kundeTab);
    jtp.addTab("xxx",projektTab);
    jtp.addTab("xxx",stimmzettelTab);
    jtp.addTab("xxx",exportTab);

    frame.getContentPane().add(jtp);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

现在想用StartTab中的一个按钮调用KundeTab

开始选项卡中的按钮

button1.addActionListener(new ActionListener() {  
    public void actionPerformed (ActionEvent s) {
      s.getActionCommand();

      // How can i switch to Tab xy?

      System.out.println("Switch Tab");
    }
});

在我的第一个 JTappedPane 项目中,我在一个 class 中完全构建了图形用户界面。在这种情况下,我可以将 jtp.setSelectedIndex(int) 与选项卡的 Int 一起使用。但这不适用于制表符的多个 classes。

希望你能帮助我!我整天都在寻找解决方案...

您可以检索被点击的 Component(此处为 JButton)的连续父代,直到找到 JTabbedPane :

button1.addActionListener(new ActionListener() {
    public void actionPerformed(final ActionEvent s) {
        s.getActionCommand();

        Component source = (Component) s.getSource();

        Container parent = source.getParent();// will give the container of the button

        do {

            parent = parent.getParent();

        } while (!(parent instanceof JTabbedPane));

        JTabbedPane tabbedPane = (JTabbedPane)parent;

        // How can i switch to Tab xy?
        tabbedPane.setSelectedIndex(xyIndex);

        System.out.println("Switch Tab");
    }
});