Java JTabbedPane获取组件

时间:2017-10-27 20:14:16

标签: java swing jtabbedpane

我正在尝试更新我编写的程序的GUI。在新的GUI上,我有一个JFrame,其中包含一个JPanel,它有一个JTabbedPane和两个上面的按钮。

在JTabbedPane内部,我有三个JPanel,里面有不同的组件。 (比如按钮,文本字段等)所以现在我必须让所有组件根据类型对它们执行相同的操作。

实施例。如果有一个文本字段我必须做一些事情,但如果有一个按钮我必须做其他事情。

所以以前我做过这样的事情:

    Container focus = general_panel.getFocusCycleRootAncestor();
    FocusTraversalPolicy ftp = focus.getFocusTraversalPolicy();
    Component comp = ftp.getFirstComponent(general_panel);
    Component first = comp;
    while(comp != null){
       if(comp instanceof JComboBox){
           ((JComboBox) comp).setSelectedIndex(0);
       }
       ....

       comp = ftp.getComponentAfter(focus, comp);

       if(comp.equals(first)){
           break;
       }
    }

使用以前GUI的JPanel工作正常。 但是现在,与tabbedpane相同的方法我只收到第一个组件和很多“null”而不是其他组件。

这是在tabbedpane中有一个Jpanel的System.out.pritnln(comp)的结果

javax.swing.JComboBox[,26,24,78x25,layout=javax.swing.plaf.basic.BasicComboBoxUI$Handler,alignmentX=0.0,alignmentY=0.0,border=com.bulenkov.darcula.ui.DarculaComboBoxUI@3b43d6ce,flags=328,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=Bianco]
null
null
null
null
null
null
null
null
null
null
null
null
null
null

“旧”GUI和新旧GUI都是使用NetBeans中嵌入的GUI创建者完成的,因此所有组件的设置可能都是相同的。

但TabbedPane中的Panel是否通过JFrame以不同的方式处理JPanel?

1 个答案:

答案 0 :(得分:0)

为了防止有人在同样的情况下陷入困境,我解决了这个问题:

在GUI类中创建了一个带面板的容器:

Container focus = pnl_generali.getFocusCycleRootAncestor();

然后以下方法完成剩下的工作:

public static List<Component> getAllComponents(final Container c) {
        Component[] comps = c.getComponents();
        List<Component> compList = new ArrayList<Component>();
        for (Component comp : comps) {
          compList.add(comp);
          if (comp instanceof Container) {
            compList.addAll(getAllComponents((Container) comp));
          }


            if(comp instanceof JTextField){
                 System.out.println(comp);
            }

        }
        return compList;
    }
相关问题