Skip to content
Advertisement

Java get JPanel Components

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

Advertisement

Answer

Well bear in mind they didn’t get there by them selves ( I think a read some questions about dynamically creating these panels at runtime )

In the answers posted there, someone said you should kept reference to those textfields in an array. That’s exactly what you need here:

List<JTextField> list = new ArrayLists<JTextField>();

// your code...
for (int i=0; i<maxPoints; i++) { 
    JTextField textField = new JTextField();
    points.add(textField);
    list.add( textField ); // keep a reference to those fields.
}

// Later

for( JTextField f : list ) { 
   System.out.println( f.getText() ) ;
}

Wasn’t that easy?

Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don’t think they belong to the interface.

Let’s say you want to get the array of texts, instead of

 public List<JTextField> getFields();

You should consider:

 public List<String> getTexts(); // get them from the textfields ... 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement