java 如何在java中使用for循环清除文本字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17777284/
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
How to clear text fields using for loop in java
提问by DnwAlgorithma
I created text fields in Java as following. When I click a "clear" button I want to clear all of these text fields at once.
我在 Java 中创建了文本字段,如下所示。当我单击“清除”按钮时,我想一次清除所有这些文本字段。
private javax.swing.JTextField num1;
private javax.swing.JTextField num2;
private javax.swing.JTextField num3;
private javax.swing.JTextField num4;
private javax.swing.JTextField num5;
private javax.swing.JTextField num6;
private javax.swing.JTextField num7;
Now I want to know how to use a for loop to clear these all text fields like:
现在我想知道如何使用 for 循环来清除这些所有文本字段,例如:
for(int i=1;1<7;i++){
num[i].settext(null);
}
回答by Azad
You can easily get the components inside the container by container.getComponents() method with consider some important things:
您可以通过 container.getComponents() 方法轻松获取容器内的组件,并考虑一些重要事项:
- There may another container like JPanel.
- There may another component like JLabel,JButton,....
- 可能还有另一个容器,如 JPanel。
- 可能还有另一个组件,如 JLabel、JButton、....
Use this method:
使用这个方法:
public void clearTextFields (Container container){
for(Component c : container.getComponents()){
if(c instanceof JTextField){
JTextField f = (JTextField) c;
f.setText("");
}
else if (c instanceof Container)
clearTextFields((Container)c);
}
}
Call the method like this:
像这样调用方法:
clearTextFields(this.getContentPane());
回答by Hovercraft Full Of Eels
Code like this:
像这样的代码:
private javax.swing.JTextField num1;
private javax.swing.JTextField num2;
private javax.swing.JTextField num3;
private javax.swing.JTextField num4;
private javax.swing.JTextField num5;
private javax.swing.JTextField num6;
private javax.swing.JTextField num7;
Is code that is crying out to be arranged and simplified by using collections or arrays. So if you use an array of JTextField or perhaps better an ArrayList<JTextField>
. Then clearing them all is trivial.
是否需要使用集合或数组来排列和简化代码。因此,如果您使用 JTextField 数组或更好的ArrayList<JTextField>
. 然后清除它们是微不足道的。
public static final int FIELD_LIST_COUNT = 7;
private List<JTextField> fieldList = new ArrayList<JTextField>();
// in constructor
for (int i = 0; i < FIELD_LIST_COUNT; i++) {
JTextField field = new JTextField();
fieldList.add(field);
fieldHolderJPanel.add(field); // some JPanel that holds the text fields
}
// clear method
public void clearFields() {
for (JTextField field : fieldList) {
field.setText("");
}
}