有没有办法在java中循环动态创建的组件?
我正在动态创建 jtextfields,我想知道是否有一种方法可以循环遍历每个字段并检查它的值,
如下所示:
foreach(JTextField:jtf in JFrame)
System.out.prinlnt(jtf.getText());
编辑:
我当前执行此操作的方法是创建一个数组列表:
private ArrayList<JTextField> txtFields = new ArrayList<JTextField>();
当我调用 createDynamic 时:
final JTextField txtDirPath = new JTextField(20);
txtFields.add(txtDirPath);
然后在我的按钮上我有一个执行此操作的操作:
for (int i = 0; i < txtFields.size(); i++) {
String strPath = txtFields.get(i).getText();
System.out.println(txtFields.size());
System.out.println(strPath);
}
I am dynamically creating jtextfields and I was wondering if there was a way to loop through each one and check for it's value
something like this:
foreach(JTextField:jtf in JFrame)
System.out.prinlnt(jtf.getText());
Edit:
The current way I'm doing this is creating an array list:
private ArrayList<JTextField> txtFields = new ArrayList<JTextField>();
When I call createDynamic:
final JTextField txtDirPath = new JTextField(20);
txtFields.add(txtDirPath);
Then on my button I have an action which perform this:
for (int i = 0; i < txtFields.size(); i++) {
String strPath = txtFields.get(i).getText();
System.out.println(txtFields.size());
System.out.println(strPath);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
动态创建文本字段时,只需将文本字段放入列表 (
java.util.List
) 中,然后循环遍历该列表即可:Just put you text fields in a list (
java.util.List<JTextField>
) when creating them dynamically, and loop over this list :如果您不想将其存储在 @JB Nizet 建议的列表中,您可以调用
Container#getComponents
获取所有子组件的数组。并检查每个字段是否为JTextField
。If you don't want to store thos in a list as @JB Nizet proposed, You can call
Container#getComponents
to get an array of all the child components. And for each one check if it aJTextField
.