Accessing GUI JTextField objects that are dynamica

2019-08-16 14:34发布

问题:

I am writing a program that contains a JButton. Every time the button is clicked, a new JTextField is added to a JPanel.

My problem is that, after the user has created all the JTextFields and filled them with information, I need to get the text of each field. How can I get access to the JTextFields when they are dynamically generated, as they don't have instance names? Is there a better way to get the text of each one, without knowing their instance name.

Here is the code of the actionPerformed event of the JButton...

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    JTextField x = new JTextField();
    x.setColumns(12);
    p.add(x); 
    validate();
}

回答1:

You say you want to get the text from each field. So, when you create the new instances x, why don't you keep a collection of them, such as adding the JTextFields to an ArrayList?

Alternatively, assuming that p is a JPanel, you should be able to get all the children, which would be the JTextFields that you're adding. Try using getComponents() like so...

Component[] children = p.getComponents();
for (int i=0;i<children.length;i++){
    if (children[i] instanceof JTextField){
        String text = ((JTextField)children[i]).getText():
    }
}


回答2:

You can find them all by looping through the components of the panel (or whatever "p" is). If necessary, check if each is a text box. That is, do p.getComponents and then loop through the returned array. Like:

Component[] components=p.getComponents();
for (Component c : components)
{
  if (c instanceof JTextField)
  {
    String value=((JTextField)c).getText();
    ... do whatever ...
  }
}

If they are interchangeable, that should be all you need. If you need to distinguish them, I think the cleanest thing to do would be to create your own class that extends JTextField and that has a field for a name or sequence number or whatever you need.