我遇到了JavaFX textformatter的问题。我想知道我做错了什么或者Java JDK中有错误。
以下是显示问题的代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TestApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
TextField field = new TextField("test0");
field.setTextFormatter(new TestTextFormatter());
Button btn = new Button();
btn.setText("Test");
btn.setOnAction(e -> {
field.setText(null);
field.setText("test");
});
BorderPane root = new BorderPane();
root.setTop(btn);
root.setCenter(field);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
class TestTextFormatter extends TextFormatter<String> {
public TestTextFormatter() {
super(c -> {
System.out.println("newControlText=" + c.getControlNewText());
return c;
});
}
}
}
点击按钮几次。 第一次按预期工作 输出是: newControlText = TEST0 newControlText = newControlText =测试
第二次和每次下一次尝试都会导致异常:
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: The start must be <= the end
at javafx.scene.control.TextInputControl.getText(TextInputControl.java:446)
at javafx.scene.control.TextInputControl$TextInputControlFromatterAccessor.getText(TextInputControl.java:1609)
at javafx.scene.control.TextFormatter$Change.getControlNewText(TextFormatter.java:453)
at TestApp$TestTextFormatter.lambda$0(TestApp.java:34)
at javafx.scene.control.TextInputControl.filterAndSet(TextInputControl.java:1165)
at javafx.scene.control.TextInputControl.access$900(TextInputControl.java:79)
at javafx.scene.control.TextInputControl$TextProperty.doSet(TextInputControl.java:1410)
at javafx.scene.control.TextInputControl$TextProperty.set(TextInputControl.java:1323)
at javafx.scene.control.TextInputControl.setText(TextInputControl.java:349)
at TestApp.lambda$0(TestApp.java:21)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
...
你能帮我理解哪里有问题(我的代码还是JDK)?
答案 0 :(得分:2)
请查看此答案https://stackoverflow.com/a/32893573/814304
您正在尝试更改事件内的文本,这正是您不想做的事情。
答案 1 :(得分:0)
这是一个过滤器,在应用方法c.getControlNewText()
时会引发异常。
如果您的代码允许设置空值,则应按以下方式重写TestTextFormatter
类
class TestTextFormatter extends TextFormatter<String> {
public TestTextFormatter() {
super(c -> {
if ( ((TextField)c.getControl()).getText() == null ) {
return c;
}
System.out.println("newControlText=" + c.getControlNewText());
return c;
});
}
}