V
V
Vitaly2014-05-21 12:35:57
Java
Vitaly, 2014-05-21 12:35:57

How to create dynamic object names?

There is this code:

Jpanel panel1 = new Jpanel();
for(int i=0; i<3; i++){
     JTextField textfield = new JTextField();
     panel1.add(textfield);
}

I need to create three JTextFields with type names: textfield1, textfield2, textfield3.
Variant with anonymous JTextField:
Jpanel panel1 = new Jpanel();
for(int i=0; i<3; i++){
     panel1.add(new JTextField());
}

does not fit, because I need to get data from these fields.
How can I implement this correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dfire, 2014-05-21
@silverhawk90

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

for (int i=0; i<3; i++) { 
    JTextField textField = new JTextField();
    points.add(textField);
    list.add( textField ); 
}

If you need names, you can use Map

A
Alexey Kulakov, 2014-05-21
@carbon88

I do not understand something, do you need to form variable names? but this is nonsense, all the same, you shove these fields into the panel, and the name of the variable in which you initialize does not play any role. and the field must have a unique identifier by which it can be uniquely identified and found, for example, a name. But the JPanel does not have a method to search by name among the components nested in it, so you have to do the search by iterating or mapping the name into an index.

M
Malah, 2014-05-21
@Malah

If you have exactly 3 input fields (a finite number), then make them members of the class, then you will always have links to them from any handler (within the window or dialog class). Create a method that will initialize your fields. For example like this:

private JTextField textfield1; // Фамилия
private JTextField textfield2; // Имя
private JTextField textfield3; // Отчество

private void createFields(JPanel panel) {
  textfield1 = new JTextField();
  textfield1.setText("Например значение по умолчанию");
  panel.add(textfield1);
  
  textfield2 = new JTextField();
  textfield2.setText("Например значение по умолчанию");
  panel.add(textfield2);

  textfield3 = new JTextField();
  textfield3.setText("Например значение по умолчанию");
  panel.add(textfield3);
}

// Ваш код станет выглядеть так
Jpanel panel1 = new Jpanel();
createFields(panel1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question