嗯,我正在學習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 –