我有一个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();
}
}
});
}
}
答案 0 :(得分:2)
您可以使用isEditValid()方法检查内容
final boolean editValid = phone.isEditValid();
showMessageDialog(frame, "The length of input is :" + phone.getText().length() + ". It is " + (editValid ? "" : "not ") + "valid!");