angelvals
angelvals

Reputation: 21

Concatenate value to variable name

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??

Upvotes: 0

Views: 2557

Answers (2)

tmarwen
tmarwen

Reputation: 16354

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());

Upvotes: 0

Jay Harris
Jay Harris

Reputation: 4271

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

Upvotes: 4

Related Questions