java 通过 JPanel 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1037139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
loop through JPanel
提问by akarnokd
In order to initialize all JTextfFields on a JPanelwhen users click a "clear button", I need to loop through the JPanel(instead of setting all individual field to "").
为了在用户单击“清除按钮”时初始化所有JTextfFields JPanel,我需要循环遍历JPanel(而不是将所有单个字段设置为“”)。
How can I use a for-each loop in order to iterate through the JPanelin search of JTextFields?
如何使用 for-each 循环来遍历JPanelin 搜索JTextFields?
回答by akarnokd
for (Component c : pane.getComponents()) {
if (c instanceof JTextField) {
((JTextField)c).setText("");
}
}
But if you have JTextFields more deeply nested, you could use the following recursive form:
但如果您有更深的 JTextFields 嵌套,则可以使用以下递归形式:
void clearTextFields(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JTextField) {
((JTextField)c).setText("");
} else
if (c instanceof Container) {
clearTextFields((Container)c);
}
}
}
Edit:A sample for Tom Hawtin - tacklinesuggestion would be to have list in your frame class:
编辑:Tom Hawtin 的一个示例- 主攻建议是在你的框架类中有列表:
List<JTextField> fieldsToClear = new LinkedList<JTextField>();
and when you initialize the individual text fields, add them to this list:
当您初始化各个文本字段时,将它们添加到此列表中:
someField = new JTextField("Edit me");
{ fieldsToClear.add(someField); }
and when the user clicks on the clear button, just:
当用户点击清除按钮时,只需:
for (JTextField tf : fieldsToClear) {
tf.setText("");
}
回答by Tom Hawtin - tackline
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.
通常希望层之间的静态依赖是一种方式。你应该需要通过getCommponents. 强制转换(假设是泛型)是一种查看出现问题的简单方法。
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 than JComponents.
因此,当您为表单创建文本字段时,请将它们添加到要在清除操作中清除的列表以及将它们添加到面板中。当然,在实际代码中,您可能还想对它们做其他事情。在实际代码中,您可能想要处理模型(可能Document)而不是JComponents。

