我正在使用for循环来创建9个JTextFields,这很好用.我的问题是,我想一次检查所有这些JTextField是否为空.我知道有一种方法:
if (textbox.getText().trim().equals(""))
检查JTextField是否为空,但我不确定它是否适合我用于JTextField的方法.下面是我的for循环:
for (int index = 1; index <=9; index++)
{
JTextField field = new JTextField(3);
field.setPreferredSize(new Dimension(150, 50));
field.setHorizontalAlignment(JTextField.CENTER);
field.setEditable(false);
second.add(field);
second.add(Box.createHorizontalStrut(10));
second.add(Box.createVerticalStrut(10));
}
解决方法:
将文本字段存储在List中,以便稍后迭代它们.
public class ClassContainingTextFields {
private final ArrayList textFields = new ArrayList<>();
// ... inside the method that creates the fields ...
for (int i = 0; i < 9; i++) {
JTextField field = new JTextField(3);
// .. do other setup
textFields.add(field);
}
/**
* This method returns true if and only if all the text fields are empty
**/
public boolean allFieldsEmpty() {
for (JTextField textbox : textFields) {
if (! textbox.getText().trim().isEmpty() ) {
return false; // one field is non-empty, so we can stop immediately
}
}
return true; // every field was empty (or else we'd have stopped earlier)
}
// ....
}
标签:java,is-empty,swing,jtextfield
来源: https://codeday.me/bug/20190725/1534306.html