Answer the question
In order to leave comments, you need to log in
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);
}
Jpanel panel1 = new Jpanel();
for(int i=0; i<3; i++){
panel1.add(new JTextField());
}
Answer the question
In order to leave comments, you need to log in
List<JTextField> list = new ArrayLists<JTextField>();
for (int i=0; i<3; i++) {
JTextField textField = new JTextField();
points.add(textField);
list.add( textField );
}
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.
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 questionAsk a Question
731 491 924 answers to any question