循环遍历 JPanel
为了在用户单击“清除按钮”时初始化 JPanel
上的所有 JTextfField
,我需要循环遍历 JPanel
(而不是将所有单独字段设置为“”)。
如何使用 for-each 循环来迭代 JPanel
来搜索 JTextField
?
In order to initialize all JTextfField
s on a JPanel
when users click a "clear button", I need to loop through the JPanel
(instead of setting all individual field to "").
How can I use a for-each loop in order to iterate through the JPanel
in search of JTextField
s?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
但是,如果您的 JTextField 嵌套更深,您可以使用以下递归形式:
编辑:Tom Hawtin - tackline 建议的示例是在您的框架类中包含列表:
当您初始化各个文本字段时,将它们添加到此列表中:
并且当用户单击清除按钮时,只需:
But if you have JTextFields more deeply nested, you could use the following recursive form:
Edit: A sample for Tom Hawtin - tackline suggestion would be to have list in your frame class:
and when you initialize the individual text fields, add them to this list:
and when the user clicks on the clear button, just:
虽然另一个答案显示了解决您问题的直接方法,但您的问题暗示了一个糟糕的解决方案。
通常希望层之间的静态依赖关系是一种方式。 您应该需要通过
getCommponents
来打包。 强制转换(假设是泛型)是一种发现问题的简单方法。因此,当您为表单创建文本字段时,请将它们添加到要通过清除操作清除的列表以及将它们添加到面板中。 当然,在实际代码中,您可能还想对它们做其他事情。 在实际代码中,您可能希望处理模型(可能是
Document
)而不是JComponent
。Whilst another answer shows a direct way to solve your problem, your question is implying a poor solution.
Generally want static dependencies between layers to be one way. You should need to go a pack through
getCommponents
. Casting (assuming generics) is an easy way to see that something has gone wrong.So when you create the text fields for a form, add them to the list to be cleared in a clear operation as well as adding them to the panel. Of course in real code there probably other things you want to do to them too. In real code you probably want to be dealing with models (possibly
Document
) rather thanJComponent
s.