Java获取JPanel组件

我有一个充满JTextFields的JPanel ……

for (int i=0; i<maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField); } 

我以后如何在该JPanel中获取JTextField? 就像我想要他们的价值观一样

 TextField.getText(); 

谢谢

请记住,他们没有自己到达那里(我认为阅读一些关于在运行时动态创建这些面板的问题)

在那里发布的答案中,有人说你应该继续引用数组中的那些文本字段。 这正是你需要的:

 List list = new ArrayLists(); // your code... for (int i=0; i 

//稍后

 for( JTextField f : list ) { System.out.println( f.getText() ) ; } 

那不容易吗?

请记住尽可能将这些工件(列表)保密。 它们仅供您控制,我不认为它们属于界面。

假设您希望获得一系列文本,而不是

  public List getFields(); 

你应该考虑:

  public List getTexts(); // get them from the textfields ... 

Java中的每个JPanel也是一个AWT容器。 因此,您应该能够使用getComponents来获取面板中包含的组件数组,迭代它们,检查它们的类型(确保您没有获得其他控件),并使用它们做任何您需要的事情。

然而,这通常是糟糕的设计。 如果您知道需要访问特定组件,最好维护这些文本字段的数组并将其传递,即使它们在视觉上包含在容器中也是如此。

如果这是一个周期性的任务,或者可以从多个点完成,那么有一个特殊的类代表具有文本字段的面板甚至是有意义的,然后通过其接口方式提供访问这些字段的方法。

您应该使用JPanel上所有元素的数组调用getComponents方法。 在您可以迭代数组并检查它是否与所寻求的组件相等时。

 List list = new ArrayLists(); Component[] components = panel.getComponents(); for (Component component : components) { if (component.getClass().equals(JTextField.class)) { list.add((JTextField)component); } } 
  //una forma de recorer todos los elementos dentro de un jpanel Component[] components = jPanelX.getComponents(); for (int i = 0; i < components.length; i++) { if(components[i].getClass().getName().toString().equals("javax.swing.JTextField")){ components[i].setEnabled(false); } } 

这就是我通过递归遍历容器并获取JPanel上的文本字段所做的。

 private void ClearAllFields(Container myContainer) { Component myComps[] = myContainer.getComponents(); for (int i=0; i 

然后使用它,你这样称呼它

 ClearAllFields([jdialog or jframe etc].getContentPane()); 

你的问题是编写繁琐的代码文本。 为什么不生成它并粘贴到程序中!! …

 for(int i=1 ; i<=maxpoints ;i++){ System.out.println("JTextField tf"+i+" = new JTextField()"+";"); System.out.println("points.add(tf"+i+")"+";"); } 

将上述代码的输出粘贴到程序中即可完成。 现在,要访问文本字段的内容,您可以以类似的方式生成繁琐的代码文本....

 for(int i=1 ; i<=maxpoints ;i++){ System.out.println("String s"+i+" = JTextField tf"+i+".getText()"+";"); }