如何在我的 JavaFX 主类中使用此代码,以便我可以在 JavaFX 中设置最大字符长度TextField
?
class LimitedTextField extends TextField {
private final int limit;
public LimitedTextField(int limit) {
this.limit = limit;
}
@Override
public void replaceText(int start, int end, String text) {
super.replaceText(start, end, text);
verify();
}
@Override
public void replaceSelection(String text) {
super.replaceSelection(text);
verify();
}
private void verify() {
if (getText().length() > limit) {
setText(getText().substring(0, limit));
}
}
};
我的 JavaFX 主类如下所示:
public class TextFiled extends Application {
@Override
public void start(Stage primaryStage) {
final TextField t_fname = new TextField();
StackPane root = new StackPane();
root.getChildren().add(t_fname);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}