I am learning Java with Swing and I have some problems with using JTextField. In my program I want to dynamically add a few JTextFields with some text:
while( (ln = bufFile.readLine()) != null ) {
// inIdPanel is JPanel
inIdPanel.add(new JTextField(ln));
}
And it works good. However, the content of these JTextFields can be modified by users, and later I want to call getText() from all of them. Is this possible? How can I do this?
I saw this question: Java Swing: JButton creates new JTextField(s) but this isn’t enough to solve my problem (I think using arrays in my case is not a good idea but maybe I’m wrong).
The reason why you cannot call
getText()is that you have not stored a reference to theJTextFieldwhen you created it. You will need to use an array or collection to store theJtextFields as you create them so you can call the method on them later. Acollectionwill be easier than anarraybecause you do not know how many lines you will read in so you want it to be able to grow.Then you can call the
.getText()from all of them