我正在编写一个收银机程序,我目前正在研究收银员视图,其中我为收银员添加了一个选项来输入客户收到的现金金额。我现在格式化它,以便用户只能输入数字和 1 个句点。我现在想将句点后可以输入的数字限制为两个。我正在努力完成这项工作。
我注释掉了我尝试过的代码之一,但没有工作,以防它可能很有趣。
感谢所有的帮助! 溴, 胜利者
private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
//boolean tail = false;
if ((Character.isDigit(c) || (c == KeyEvent.VK_BACKSPACE) || c == KeyEvent.VK_PERIOD)) {
int period = 0;
if (c == KeyEvent.VK_PERIOD) { //Allows only one period to be added to the textfield
//tail = false;
String s = getTextFieldCash();
int dot = s.indexOf(".");
period = dot;
if (dot != -1) {
evt.consume();
}
}
//. if (tail=true){ //This is the code that I tried to use to limit input after the period to two
// String x = getTextFieldCashTail();
// if (x.length()>1){
// evt.consume();
// }
// }
}
else {
evt.consume();
}
}
如果您死心塌地地想用KeyEvent
来做这件事,这里有一种可能的方法:
private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
if ((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_PERIOD)) {
String s = getTextFieldCash();
int dot = s.indexOf(".");
if(dot != -1 && c == KeyEvent.VK_PERIOD) {
evt.consume();
} else if(dot != -1 && c != KeyEvent.VK_BACK_SPACE){
String afterDecimal = s.substring(dot + 1);
if (afterDecimal.length() > 2) {
evt.consume();
}
}
}
}
希望这有帮助。请记住,通过收听KeyEvent
,如果有人将值复制并粘贴到您的JTextField
中,这不会捕获。如果要捕获任何可能的输入类型,则需要使用 DocumentListener。如果您想知道如何使用DocumentListener
,这里有一些代码显示了如何在JTextField
上使用它。