访问动态生成的GUI JTextField对象 [英] Accessing GUI JTextField objects that are dynamically generated
问题描述
我正在编写一个包含JButton
的程序.每次单击按钮时,都会将新的JTextField
添加到JPanel
.
I am writing a program that contains a JButton
. Every time the button is clicked, a new JTextField
is added to a JPanel
.
我的问题是,在用户创建了所有JTextFields
并将其填充信息之后,我需要获取每个字段的文本.动态生成JTextFields
时,由于它们没有实例名称,如何获得它们的访问权限?是否有一种更好的方法来获取每个文本,而又不知道它们的实例名称.
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.
这是JButton
...
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
JTextField x = new JTextField();
x.setColumns(12);
p.add(x);
validate();
}
推荐答案
您说您想从每个字段中获取文本.因此,当您创建新实例x
时,为什么不保留它们的集合,例如将JTextFields
添加到ArrayList
?
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
?
或者,假设p
是JPanel
,您应该能够获取所有子级,这就是您要添加的JTextFields
.尝试像这样使用getComponents()
...
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():
}
}
这篇关于访问动态生成的GUI JTextField对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!