我正在研究JavaFX项目,使用TextField控件时遇到问题。我想将用户将输入到每个TextField的字符限制为一个。如果您使用带有Listener的单个文本字段,我找到了一个解决方案:
public static void addTextLimiter(final TextField tf, final int maxLength) {
tf.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
if (tf.getText().length() > maxLength) {
String s = tf.getText().substring(0, maxLength);
tf.setText(s);
}
}
});
但问题是我有一个TextFields数组。你们可能知道如何为TextFieldArray重写这个监听器吗?
数组列表实现:
static public TextField[] tfLetters = new TextField[37];
阵列的初始化:
private void layoutNodes() {
int letternummer = 0;
for (int i = 1; i < 8; i++) {
for (int j = 0; j < i + 1; j++) {
this.tfLetters[letternummer] = new TextField("Letter " + i);
this.add(tfLetters[letternummer], j, i);
tfLetters[letternummer].setPadding(new Insets(5, 30, 5, 5));
tfLetters[letternummer].setAlignment(Pos.CENTER);
tfLetters[letternummer].setMinSize(10, 10);
letternummer++;
}
}
我使用了给定的解决方案:
Arrays.asList(tfLetters).forEach(tfLetters -> GamePresenter.addTextLimiter(tfLetters,1));
GamePresenter是编写监听器的视图的演示者。 在视图&#34; GameView&#34;我已经实现了文本字段数组。但是现在当我运行给定的解决方案时,我会发出以下NullPointerException:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at be.kdg.letterpyramide.view.GameView.GamePresenter.addTextLimiter(GamePresenter.java:36)
at be.kdg.letterpyramide.view.GameView.GameView.lambda$layoutNodes$0(GameView.java:52)
at java.util.Arrays$ArrayList.forEach(Arrays.java:3880)
GameView专栏:36
tf.textProperty().addListener(new ChangeListener<String>() {
GameView行:52
Arrays.asList(tfLetters).forEach(tfLetters -> GamePresenter.addTextLimiter(tfLetters,1));
旁注:我把它设为公共静态,所以我可以在我的GamePresenter中使用它。我是Java的新手。
提前致谢!
答案 0 :(得分:2)
这是一个没有GridPane的解决方案,但这也是将Fields添加到GridPane的简单过程。现在使用更好的TextFormatter。
import java.util.ArrayList;
import java.util.List;
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.VBox;
import javafx.stage.Stage;
public class ChangeListenerDemo extends Application {
@Override
public void start(Stage primaryStage) {
List<TextField> fields = createLimitedTextFields(9, 1);
VBox box = new VBox();
box.getChildren().addAll(fields);
Scene scene = new Scene(box, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
private List<TextField> createLimitedTextFields(int num, int maxLength) {
final List<TextField> fields = new ArrayList<>();
final UnaryOperator<TextFormatter.Change> filter
= (TextFormatter.Change change) -> {
if (change.getControlNewText().length() > maxLength) {
return null;
}
return change;
};
for (int i = 0; i < num; i++) {
final TextField tf = new TextField();
tf.setTextFormatter(new TextFormatter(filter));
fields.add(tf);
}
return fields;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}