Accessing GUI JTextField objects that are dynamically generated

旧时模样 提交于 2019-12-25 03:32:42

问题


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.



来源:https://stackoverflow.com/questions/10482796/accessing-gui-jtextfield-objects-that-are-dynamically-generated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!