gpt4 book ai didi

java - 将 JTextField 的输入限制为双数?

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

在 java 中,我正在尝试制作简单的货币转换器,但为此我需要一个文本字段,它可以将输入限制为仅数字,更重要的是双数。我尝试使用 JFormatedTextField它只会在您完成输入并单击其他地方后格式化输入 但我需要将 TextField 限制为 consume()输入时的每个无效字符。

可能的尝试:

使用 JFormatedTextField:

JFormatedTextField textField = new JFormatedTextField(new DoubleFormat());
textField.setBounds(190, 49, 146, 33);
frame.getContentPane().add(textField);
textField.setColumns(10);

使用 KeyTyped 事件:

char c = arg0.getKeyChar();
if(!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c== KeyEvent.VK_DELETE)){
arg0.consume();
}

使用 KeyTyped 事件 和正则表达式:

if(!((textField.getText().toString+arg0.getKeyChar()).matches("[0-9]*(.[0-9]*)?"))){
arg0.consume();
}

第二次和第三次尝试很接近,但第二次尝试在点值上失败,第三次尝试总是读取 textField 上的第一个字符,不管它是什么,所以有什么建议吗?我不太喜欢 JAVA GUI,所以请耐心等待。

最佳答案

如果你知道你想要的小数点前后有多少位,你也可以使用MaskFormatter。例如:

JFormattedTextField field = new JFormattedTextField(getMaskFormatter("######.##"));

(...)

private MaskFormatter getMaskFormatter(String format) {
MaskFormatter mask = null;
try {
mask = new MaskFormatter(format);
mask.setPlaceholderCharacter('0');
}catch (ParseException ex) {
ex.printStackTrace();
}
return mask;
}

但是它会变成 JTextField 的外观,因此它在其中始终可见 000000.00

编辑

另一种方式,不太优雅,但在我看来是可行的。尝试使用 DecumentListener,也许它会满足您的需求:

field = new JFormattedTextField();
field.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
Runnable format = new Runnable() {
@Override
public void run() {
String text = field.getText();
if(!text.matches("\\d*(\\.\\d{0,2})?")){
field.setText(text.substring(0,text.length()-1));
}
}
};
SwingUtilities.invokeLater(format);
}

@Override
public void removeUpdate(DocumentEvent e) {

}

@Override
public void changedUpdate(DocumentEvent e) {

}
});

我使用了正则表达式:\\d*(\\.\\d{0,2})? 因为两位小数足以表示货币。

关于java - 将 JTextField 的输入限制为双数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33348481/

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