我怎么做 textField 在 Java 中只接受字母“N 或 E”?不接受數字和其他字符。
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.length() > 1) textField.setText(oldValue);
if (newValue.matches("[^\\d]")) return;
textField.setText(newValue.replaceAll("\\d*", ""));
});
我試過了,這對 maxValue 有效。但我需要 textField 只接受“N”和“E”字符。那么我該怎么做呢?
uj5u.com熱心網友回復:
使用一個TextFormatter. 您可以修改或否決對文本的建議更改。這個版本:
- 僅接受鍵入(或粘貼)的文本為“N”或“E”(大寫或小寫)的更改
- 使文本大寫
- 更改提議的更改以替換現有文本,而不是添加到其中
- 允許洗掉當前文本
您的確切要求可能略有不同。有關更多詳細資訊,請參閱JavadocTextFormatter.Change。
import java.util.function.UnaryOperator;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class NorETextField extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
TextField textField = new TextField();
UnaryOperator<TextFormatter.Change> filter = c -> {
if (c.getText().matches("[NnEe]")) {
c.setText(c.getText().toUpperCase());
c.setRange(0, textField.getText().length());
return c ;
} else if (c.getText().isEmpty()) {
return c ;
}
return null ;
};
textField.setTextFormatter(new TextFormatter<String>(filter));
BorderPane root = new BorderPane(textField);
Scene scene = new Scene(root, 400, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
uj5u.com熱心網友回復:
你可以試試這個。這僅接受字符 N
Pattern pattern = Pattern.compile("N");
UnaryOperator<TextFormatter.Change> filter = c -> {
if (pattern.matcher(c.getControlNewText()).matches()) {
return c ;
} else {
return null ;
}
};
TextFormatter<String> formatter = new TextFormatter<>(filter);
textField.setTextFormatter(formatter);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/349214.html
上一篇:驗證不適用于貓鼬模式
