[英]How to restrict entering whitespaces as input to JTextField elements in Java Swing?
我將 Java Swing 用於連接 GUI。 我需要防止在 JTextField 元素中輸入空格,尤其是在密碼字段中。 我曾使用 isEmpty() 或 isBlank() 來了解是否輸入了空格。 但它沒有奏效。 如果我輸入空格,它不會返回真值,因為如果只有空格,isBlank() 應該返回真。
String errorMessage = "No Errors"; //Intializing as No errors
private boolean checkValueAndSetErrorMessage(Map<String, String> map) {
boolean truth = false;
for (Map.Entry<String, String> mapElement : map.entrySet()) {
if (mapElement.getKey().isEmpty()|| mapElement.getKey().isBlank()) {
errorMessage = String.format("%1$s should not be blank.", mapElement.getValue()); //Changing errorMessage to empty
truth = false;
break;
} else {
truth = true;
}
}
return truth;
}
嘗試:
mapElement.getKey().contains(" ")
您可以使用regular expression
來測試鍵是否包含任何空白字符。
Pattern.matches("\\s+", mapElement.getKey())
有關我提供的正則表達式的更多解釋,
\s+
表示它將嘗試匹配一個或多個空格字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.