2012-10-27 57 views
3

我正在使用NetBeans开发Java应用程序。我在JFrame中有5 JTextFields和2 JTextArea。我想用循环立即清除它们。如何做呢?如何使用循环清除jframe的所有文本字段?

+4

使用'.getContentPane( ).getComponents()'在JFrame上获取它的子级数组。迭代该数组,并为每个项检查'instanceOf TextComponent'如果是这样,调用'setText(null)' –

回答

6

遍历所有的组分和所有JTextFieldJTextArea对象的文本设置为空字符串:

//Note: "this" should be the Container that directly contains your components 
//(most likely a JPanel). 
//This won't work if you call getComponents on the top-level frame. 
for (Component C : this.getComponents()) 
{  
    if (C instanceof JTextField || C instanceof JTextArea){ 

     ((JTextComponent) C).setText(""); //abstract superclass 
    } 
} 
+0

但textarea不清除。 –

+0

对于模糊不清,我表示歉意。对getComponents()的调用应该在包含所有组件的JPanel上进行,而不是顶层Frame,它的add(Component)方法实际上将组件添加到嵌套在JRootPane中的JPanel(因此它的getComponents()方法将只返回JRootPane)。我已经测试过这个方法,它完美的工作。 – ApproachingDarknessFish

+0

没有明白。它不工作,只返回JRootPane。我在JFrame上试过这个...有什么建议吗? Component [] components = jframe.getRootPane()。getComponents(); –

2

适当的代码应该是这样一个

Component[] components = jframe.getContentPane().getComponents(); 
    for (Component component : components) { 
     if (component instanceof JTextField || component instanceof JTextArea) { 
      JTextComponent specificObject = (JTextComponent) component; 
      specificObject.setText(""); 
     } 
    } 
相关问题