java field 空_java – 如何检查所有JTexField是否为空?

我正在使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值