【问题标题】:How do we test if JFormattedTextField is empty?我们如何测试 JFormattedTextField 是否为空?
【发布时间】:2015-05-11 11:55:55
【问题描述】:

我有一个JFormattedTextField,供用户输入电话号码。我的电话号码采用以下格式:+### ###-###-###。我想在将电话号码保存到数据库之前检查空字符串。问题是我无法检查/确定该字段是否为空。当我打印field.getText().length() 时,它输出 16 表示某些字符已经在该字段中。如何检查用户是否输入了某些字符?

下面是我的代码:

public class JTextFiledDemo {

private JFrame frame;

JTextFiledDemo() throws ParseException {
    frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(300, 300);
    frame.setLayout(new GridLayout(4, 1));
    frame.setLocationRelativeTo(null);
    iniGui();
}

private void iniGui() throws ParseException {

    JButton login = new JButton("Test");
    JFormattedTextField phone = new JFormattedTextField(new MaskFormatter(
            "+### ###-###-###"));

    frame.add(phone);
    frame.add(login);
    frame.pack();

    login.addActionListener((ActionEvent) -> {

        JOptionPane.showMessageDialog(frame, "The length of input is :"
                + phone.getText().length());

    });

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                JTextFiledDemo tf = new JTextFiledDemo();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
      }

   }

【问题讨论】:

  • 使用java.text.Format 而不是MaskFormatter(参见this question),问题就会消失。
  • @Robin 好吧,谢谢让我研究一下,现在我已经使用了下面的答案

标签: java swing validation jformattedtextfield


【解决方案1】:

可以使用isEditValid()方法查看内容

 final boolean editValid = phone.isEditValid();
 showMessageDialog(frame, "The length of input is :" + phone.getText().length() + ".  It is " + (editValid ? "" : "not ") + "valid!");

【讨论】:

  • 嗯,这就是我一直在寻找的 - 让我们实现它。
猜你喜欢
  • 1970-01-01
  • 2011-02-27
  • 2011-09-17
  • 1970-01-01
  • 2019-03-22
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多