【发布时间】: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