我正在使用NetBeans开发Java应用程序。我在JTextFields
中有5 JTextArea
和2 JFrame
。我想使用循环立即清除它们。怎么办呢?
答案 0 :(得分:6)
迭代所有组件并将所有JTextField
和JTextArea
对象的文本设置为空字符串:
//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
}
}
答案 1 :(得分:2)
适当的代码应该是这个
Component[] components = jframe.getContentPane().getComponents();
for (Component component : components) {
if (component instanceof JTextField || component instanceof JTextArea) {
JTextComponent specificObject = (JTextComponent) component;
specificObject.setText("");
}
}