2012-06-16 2 views
1

안녕하세요 :) 저는 자바 스윙에서 초보자이고 내 문제에 대해 Google 솔루션을 사용할 수 없습니다. JPanel을 가지고 있고 JButton을 누른 후 동적으로 JTextField를 추가하려고합니다. 그리고 나중에 어떻게 getText()를 할 수 있습니까? 내 코드, 주석 처리 된 부분이 제대로 작동하지 않습니다.자바 스윙 : JButton이 새로운 JTextField를 만듭니다

변수 '카운터'는 패널에있는 필드 수를 계산합니다.

tfData[counter-1].getText(); 

당신에게 마지막으로 추가 된 텍스트 필드의 텍스트를 표시합니다 : 이미 텍스트 필드에 대한 참조를 저장하고 따라

public class AppPanel extends JPanel { 

    private JTextField tfData[]; 
    private JButton btAdd; 
    private int counter = 1; 

    public AppPanel() { 
      setLayout(null); 

      //tfData[counter] = new JTextField(); 
      //tfData[counter-1].setBounds(20, 20, 250, 20); 
      //add(tfData[counter-1]); 

      btAdd = new JButton("Add field"); 
      btAdd.setBounds(280, 20, 120, 20); 
      btAdd.addActionListener(new alAdd()); 
      add(btAdd); 
    } 

    class alAdd implements ActionListener { 
      public void actionPerformed(ActionEvent e) { 
        //tfData[counter] = new JTextField(); 
        //tfData[counter].setBounds(20, 20+20*counter, 250, 20); 
        //add(tfData[counter]); 
        ++counter; 
      } 
    } 
} 
+0

당신은이 질문에 http://stackoverflow.com/questions/5522279/how-can-i-add-a-textfield-dynamically-after-clicking-a-button를 참조 할 수 있습니다 – 20911141

답변

1

, 단지 텍스트 필드의 텍스트를 조회하려면이 배열을 사용 .

하지만 실제로 배열을 초기화해야합니다. 그렇지 않으면 항목을 추가 할 수 없습니다. 나는 당신이 당신의 추가 코드를 주석 처리했을 때 그것이 당신의 주된 문제라고 생각한다.

// think about how many text fields you will need (here: 16) 
private JTextField tfData[] = new tfData[16]; 

배열을 사용하는 경우 경계를 넘지 않도록주의하십시오. 하지만 더 나은 use a list은 동적으로 커지며 배열 경계를 다룰 필요가 없으며 카운팅을 건너 뛸 수도 있습니다 (목록에서 사용자를 위해 수행합니다).