0

I need to get the value of different text boxes.

I want to get the value of each one using a for loop or something like this:

txt0,txt1,txt2,txt3;
for(int i=0;i<4;i++){
  String valor = (txt+i).getText();
}

There is a way to get the value by concatenating another value to the name of the textbox or any other object??

1
  • 5
    You might be able to get something to work that way using reflection, but it would be way, way easier to just add the text boxes to a Collection (or an array) and then iterate over each element. Commented Jul 25, 2014 at 13:31

2 Answers 2

4

I don't know if you have access to the variables but you can use an array instead. This will make looping much easier.

TextBox[] text = {txt0, txt1, txt2, txt3};

for (TextBox txt : text) {
   String valor = txt.getText();
}
Sign up to request clarification or add additional context in comments.

Comments

0

I don't know if I have well understood your question so this might be a wild guess.

If you want to have all your text boxes fields concatenated value, You need to have a set that can hold all of their references and your main solution should be JAVA Collections API.

You need to store all of your JTextField objects references in a Collection (each time you construct a new one add it to the Collection), can be a List, Map or a Set, then iterate over that Collection once it is filled and build your concatenated String using their values (I would suggest to use a StringBuilder that the way you actually do it):

// Initialize your Collection, will be an ArrayList for this e.g.
List<JTextField> textFields = new ArrayList<JTextField>;

// Instantiation example, it should be done for all fields
JTextField txt0 = new JTextField(20);
textFields.add(txt0);
// Do the same for txt1, txt2 ...

// Iterate over your List to get the concatenated String
StringBuilder sBuilder = new StringBuilder();
for(JTextField textField : textFields){
  sBuilder.append(textField.getText());
}

// Print your final value
System.out.print(sBuilder.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.