嗯,我正在学习Java FX,但是这次我在NetBeans中使用FXML,然后我想限制TextField允许的键。就像数字或只是字母。过滤器键盘TextField Java FXML
我发现This,然后我创建了一个新的类,然后把这个代码(检查为正确的链接),我扩展TextField,但是当我运行代码时,抛出一个异常,我认为是因为SceneBuilder doesn没有我的班级。
更新,我发现对Java FX类似的代码:
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.control.TextFormatter.Change;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* @author Alejandro
*/
public class JavaFXApplication2 extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
TextFormatter<String> textFormatter = getTextFormatter();
textField.setTextFormatter(textFormatter);
VBox root = new VBox();
root.getChildren().add(textField);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("TextFormat");
primaryStage.setScene(scene);
primaryStage.show();
}
private TextFormatter<String> getTextFormatter() {
UnaryOperator<Change> filter = getFilter();
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
return textFormatter;
}
private UnaryOperator<Change> getFilter() {
return change -> {
String text = change.getText();
if (!change.isContentChange()) {
return change;
}
if (text.matches("[a-z]*") || text.isEmpty()) {
return change;
}
return null;
};
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
上面的代码工作正常,在Java FX应用程序,但我需要一个在Java中FXML使用,后下一个类似的代码一个人,它编译,没有trows异常,但不起作用,或者我不知道如何实现它。
这种联系是很老。你应该为这种功能使用一个'TextFormatter'。参见例如https://stackoverflow.com/questions/40472668/numeric-textfield-for-integers-in-javafx-8-with-textformatter-and-or-unaryoperat –