Home Ask Login Register

Developers Planet

Your answer is one click away!

Yasin Bilir February 2016

Creating textField with unique name for each in a loop

im beginner level programmer on Java. I would like to create textField in a for loop but i also want it to have a unique name (for calling after loop). For ex. I have this loop;

for (int i =0;i<x;i++)


            Composite composite_10 = new Composite(composite_20, SWT.BORDER);
            composite_10.setBackground(SWTResourceManager.getColor(230, 230, 250));
            composite_10.setBounds(x1, y1, 542, 76);

            txtBaseSeri = new Text(composite_10, SWT.BORDER);
            txtBaseSeri.setMessage("Base Seri");
            txtBaseSeri.setBounds(x2, y2, 95, 21);

Here, I want the second Textfield have a name like txtBaseSeri1, then txtBaseSeri2... so that i can call them after exiting the loop. Is there any way to do that ? Thanks in advance..


Andreas Fester February 2016

I want the second Textfield have a name like txtBaseSeri1, then txtBaseSeri2 - Is there any way to do that?

No. Use an ArrayList instead and add your text fields to that list, for example like this:

List<Text> txtBaseSeri = new ArrayList<>();
for (int i = 0; i < x; i++) {
    // ...

    Text txt = new Text(composite_10, SWT.BORDER);
    // ...


Afterwards, you can access each Text object through its index, like

Text first = txtBaseSeri.get(0);
Text second = txtBaseSeri.get(1);
// ...

or you can loop through them, like

for (Text txt : txtBaseSeri) {
    // in each loop iteration, txt will be set to the next element
    // ...

Post Status

Asked in February 2016
Viewed 1,835 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life