gpt4 book ai didi

java - 如何限制输入类型

转载 作者:行者123 更新时间:2023-11-29 03:42:55 25 4
gpt4 key购买 nike

我正在学习java swing。有一个可编辑的 JComboBox 用于选择不同的水深,还有一个 JTextField 用于接受手机号码。我的问题是如何限制用户在这两个字段中只能输入数字,以及如何限制手机号码的最大字符输入数,例如不超过 10 个?是否有满足这些要求的方法,或者我需要自己定义它们?预先感谢您的帮助。

最佳答案

使用 JFormattedTextField 类似于:

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
JFrame frame = new JFrame("JFormattedTextField Example");
MaskFormatter fmt = null;

// A phone number 10 digits
try {
fmt = new MaskFormatter("(###)-###-####");//brackets () are optional just there for my pref
fmt.setPlaceholderCharacter('*');//set place holder for the empty digits of the number

} catch (java.text.ParseException e) {
}

JFormattedTextField tft1 = new JFormattedTextField(fmt);

frame.add(tft1);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}

这会自动具有您想要的属性,它只接受指定格式的数字也可以查看文档以获取更多信息:JFormattedTextField

关于java - 如何限制输入类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12297956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com