리플렉션을 사용해 볼 수 있습니다. 성능 - 현명한하지만 속도가 느려집니다 :
public class Snippet {
JTextField field1 = new JTextField("1");
JTextField field2 = new JTextField("2");
JTextField field3 = new JTextField("3");
JTextField field4 = new JTextField("4");
// add more fields here
public static void main(String[] args) throws Exception {
new Snippet().run();
}
private void run() throws Exception {
for (int i = 1; i <= 4; i += 2) {
JTextField textfieldA = getTextField(i);
JTextField textfieldB = getTextField(i + 1);
System.out.println(textfieldA.getText() + " " + textfieldB.getText());
}
}
private JTextField getTextField(int i) throws NoSuchFieldException, IllegalAccessException {
Field field = Snippet.class.getDeclaredField("field" + i);
JTextField textfield = (JTextField) field.get(this);
return textfield;
}
}
이 신속하고 더러운이며, 장기적으로 (예 : 목록 또는지도) 적절한 데이터 구조로 텍스트 필드를 넣어 더 좋을 것이고, 단순히 반복 .
양식을 만들 때 모음 (지도, 목록 또는 사용자 지정 구조)에 필드를 추가하기 만하면됩니다. 나중에 이것 만 반복하면 ... 스윙에 관한 것일까? – home