[英]Force User not to enter numeric entry in jTextField in java
如何鎖定用戶的鍵盤,以使用戶無法在JTextField
輸入任何數字值?
javax.swing.InputVerifier
適用於大多數簡單任務。
這是我前幾天淘汰的一個:
public class TexFieldValidator extends InputVerifier {
String regex;
String errorMsg;
JDialog popup;
public TexFieldValidator(String regex, String errorMsg) {
this.regex = regex;
this.errorMsg = errorMsg;
}
@Override
public boolean verify(JComponent input) {
boolean verified = false;
String text = ((JTextField) input).getText();
if (text.matches(regex)) {
input.setBackground(Color.WHITE);
if (popup != null) {
popup.dispose();
popup = null;
}
verified = true;
} else {
if (popup == null) {
popup = new JDialog((Window) input.getTopLevelAncestor());
input.setBackground(Color.PINK);
popup.setSize(0, 0);
popup.setLocationRelativeTo(input);
Point point = popup.getLocation();
Dimension dim = input.getSize();
popup.setLocation(point.x - (int) dim.getWidth() / 2, point.y + (int) dim.getHeight() / 2);
popup.getContentPane().add(new JLabel(errorMsg));
popup.setUndecorated(true);
popup.setFocusableWindowState(false);
popup.getContentPane().setBackground(Color.PINK);
popup.pack();
}
popup.setVisible(true);
}
return verified;
}
}
從這里被盜。
使用示例:
iDTextField.setInputVerifier(new TexFieldValidator("[a-zA-Z0-9]{3}", "ID must be 3 alphanumerics."));
您可以為此使用DocumentFilter ,也可以使用JFormattedTextField 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.