Is it possible to create multiple JTextFields
with different names inside a loop?
I need to so this since I later need to get the text that is in each of them, I need to do something like this:
while (sst_ResultSet.next()) {
p_vertabla.add(new JLabel(sst_ResultSet.getString(1));
p_vertabla.add(new JTextField(sst_ResultSet.getString(1)));
}
This works just fine when adding the JLabel
and the JTextField
the way I want it to the JPanel
p_vertabla
, but I don't know how to later call the method .getText();
on the JTextFields
.
How can I create the JTextFields
in the loop or how can I later call the method on them?
I'm answering my own question with a little from a comment on the question, I found out that there is no need to assign the variables a name, with an ArrayList<JtextFiel>
will work, the point is just to follow the order in what they were added to the JPanel
that way I was able to retrieve the information associated with the JTextField
in that particular position. I did something like this:
ArrayList<JLabel> listadelabels = new ArrayList<JLabel>();
ArrayList<JTextField> listadetextfields = new ArrayList<JTextField>();
ArrayList<JCheckBox> listadecheckbox = new ArrayList<JCheckBox>();
...
Statement stmt=db.createStatement();
ResultSet sst_ResultSet = stmt.executeQuery(query);
JPanel p_obtenerregistro = new JPanel(new GridLayout(0,3));
while (sst_ResultSet.next()) {
listadelabels.add(new JLabel(sst_ResultSet.getString(1)));
listadetextfields.add(new JTextField(12));
listadecheckbox.add(new JCheckBox());
}
for(int i=0 ; i<listadelabels.size(); i++){
listadecheckbox.get(i).addItemListener(this);
p_obtenerregistro.add(listadecheckbox.get(i));
p_obtenerregistro.add(listadelabels.get(i));
listadetextfields.get(i).setEditable(false);
p_obtenerregistro.add(listadetextfields.get(i));
}
And then to get the info associated with the list I did it like this:
for (int i = 0; i < activos; i++) {
atributos[i] = listadetextfields.get(arreglodeactivos[i]).getText();
columnas[i] = listadelabels.get(arreglodeactivos[i]).getText();
ModificarRegistro.where = ModificarRegistro.where + columnas[i] + "=" + "'" + atributos[i] + "' AND ";
}
I really hope it could useful for a lot of people