1 java validation javafx textfield
我怎样才能在Java中让textField只接受字母“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*", ""));
});
Run Code Online (Sandbox Code Playgroud)
我尝试了这个,这对 maxValue 有效。但我需要 textField 仅接受“N”和“E”字符。那么我该怎么做呢?
用一个TextFormatter。您可以修改或否决对文本的拟议更改。这个版本:
您的具体要求可能略有不同。有关更多详细信息,请参阅Javadocs 。TextFormatter.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);
}
}
Run Code Online (Sandbox Code Playgroud)