2017-12-01 14 views
0

패널의 모든 텍스트 필드에는 문서 수신기가 있습니다. 모든 텍스트 필드에 모든 값을 추가하고 합계를 다른 패널에있는 다른 텍스트 필드로 설정합니다.패널의 모든 jtextfields의 모든 값 가져 오기

제 문제는 74 개의 텍스트 필드가 있는데, for 루프를 사용하여 그 값을 모두 확인할 수 있습니까? 나는 무엇을 해야할지 모른다.

답변

1

아래 코드를 확인하십시오. 그것의 요지는 의견에있다.

건배!

import java.awt.Component; 
import java.awt.Container; 
import java.util.stream.Stream; 

import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class IterateOverJTextField { 

    private static void iterateOverJTextFields(Container container) { 
     // You have to call getComponents in order to access the 
     // container's children. 
     // Then you have to check the type of the component. 
     // In your case you're looking for JTextField. 
     // Then, you do what you want... 
     // Old-style 
     for (Component component : container.getComponents()) { 
      if (component instanceof JTextField) { 
       System.out.println(((JTextField) component).getText()); 
      } 
     } 

     // New-style with Stream 
     Stream.of(container.getComponents()) 
       .filter(c -> c instanceof JTextField) 
       .map(c -> ((JTextField) c).getText()) 
       .forEach(System.out::println); 
    } 

    public static void main(String[] args) { 
     JPanel panel = new JPanel(); 
     panel.add(new JTextField("text 1")); 
     panel.add(new JTextField("text 2")); 
     panel.add(new JTextField("text 3")); 
     panel.add(new JTextField("text 4")); 

     // You have to work with your container 
     // the has the 74 fields. I created this 
     // panel just to test the code. 
     iterateOverJTextFields(panel); 
    } 

} 
+0

대단히 감사합니다! 신의 축복이 – justuser

+0

이 방법으로 모든 유형의 구성 요소를 얻을 수 있습니다. – xxxvodnikxxx

관련 문제