简体   繁体   中英

Java JTabbedPane get Components

I'm trying to renew the GUI of a program I wrote. On the new GUI I have a JFrame that contains a JPanel which has a JTabbedPane and two buttons above.

Inside the JTabbedPane I have three JPanels with different components in it. (like buttons, textfields and so on) So now I have to get all the components to perform the same action on them based on the type.

Ex. if there is a textfield I have to do something but if there is a button I have to do something else.

So previously I did something like this:

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

And with the JPanel with the previous GUI works fine. But now, the same method with the tabbedpane i only receive the first component and a lot of "null" instead of the other components.

This is the result of a System.out.pritnln(comp) with a Jpanel inside the tabbedpane

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

Both the "old" GUI and the new one has been done with the GUI creator embedded in NetBeans, so probably the settings from all the components are the same..

But does the Panel inside the TabbedPane are handled differently form a JPanel over a JFrame?

Just in case somebody ever get stacked in the same situation, I solved with this:

Inside the GUI class created a container with the panel:

Container focus = pnl_generali.getFocusCycleRootAncestor();

Then the below method does the rest:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM