Java get JPanel Components

Devoted picture Devoted · Dec 16, 2008 · Viewed 53.3k times · Source

I have a JPanel full of JTextFields...

for (int i=0; i<maxPoints; i++) {
    JTextField textField = new JTextField();
    points.add(textField);
}

How do I later get the JTextFields in that JPanel? Like if I want their values with

TextField.getText();

Thanks

Answer

Uri picture Uri · Dec 16, 2008

Every JPanel in Java is also an AWT container. Thus, you should be able to use getComponents to get the array of contained components in the panel, iterate over them, check their types (To make sure you didn't get other controls), and do whatever you need with them.

However, this is generally poor design. If you know that you will need to access specific components, it is better to maintain an array of those text fields and pass it around, even though they are visually contained within the container.

If this is a recurrent task or could be done from multiple points, it may even make sense to have a special class representing a panel with text fields, that will then provide through its interface means of accessing these fields.