正如 Hovercraft Full Of Eels 所建议的那样,一个干净的实现将事情分开:分组字段收集并对其执行处理。
特别是,如果通过反射执行分组。
以下代码更具可读性和可维护性。
public class MyComponent extends JFrame{
List<JTextField> fields = new ArrayList();
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
public MyComponent(){
textField1 = new JTextField ("");
textField2 = new JTextField ("");
textField3 = new JTextField ("");
addTextFieldInList(textField1, textField2, textField3);
}
public void addTextFieldInList(JTextField fieldArgs...) {
fields.addAll(Arrays.asList(fieldArgs));
}
public void iterateAllTextFields(){
for (JTextField field : fields){
String yourValue = field.getText();
}
}
在指定处理超过50个JTtextField的问题更新后更新。
在这种情况下,我提出的另一种解决方案可能更合适。
确实,有十几个字段,冒着忘记在列表中添加 JTextField 的可能性不大,但超过 50 个,我们可以理解这是一个容易出错的处理。创建您的自定义 JTextField 可能是一个更好的选择。
想法如下:使用新类 JTextFieldWatched 扩展 JTextField 并使用附加参数强制 JTextFieldWatched 构造函数:注册 JTextField 实例的对象。
JTextFieldWatched 扩展 JTextField :
public class JTextFieldWatched extends JTextField{
public JTextFieldWatched(String text, JTextFieldWatcher textFieldWatcher){
super(text);
if (textFieldWatcher==null){
// force the constraint
throw new IllegalArgumentException("textFieldWatcher is mandatory");
}
textFieldWatcher.add(this);
}
}
注册JTextfield实例的类:
public class JTextFieldWatcher {
List<JTextField> fields = new ArrayList();
public void add(JTextField textField){
fields.add(textField);
}
public List<JTextField> getAllTextField(){
return new ArrayList(fields);
}
}
如何使用这些类:
public class MyComponent extends JFrame{
private JTextFieldWatcher fieldsWatcher = new JTextFieldWatcher();
private JTextFieldWatched textField1;
private JTextFieldWatched textField2;
private JTextFieldWatched textField3;
public MyComponent(){
textField1 = new JTextFieldWatched ("",fieldsWatcher);
textField2 = new JTextFieldWatched ("",fieldsWatcher);
textField3 = new JTextFieldWatched ("",fieldsWatcher);
}
public void iterateAllTextFields(){
for (JTextField field : fieldsWatcher.getAllTextField()){
String yourValue = field.getText();
}
}
}
所有代码都是在没有IDE的情况下编写的,如果有任何错误,请见谅。