过滤键盘TextField Java FXML

时间:2017-09-25 17:21:20

标签: java model-view-controller javafx desktop-application

我正在学习Java FX,但这次我在NetBeans中使用FXML,然后我想限制TextField允许的Keys。就像数字或只是字母。

我找到This,然后我创建了一个新类,然后把那个代码(在链接中检查为正确),我扩展TextField,但是当我运行代码时抛出一个异常,我认为是因为SceneBuilder没有我的班级。

更新我找到了类似的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异常,但是没有工作,或者我不知道不知道如何实现它。

1 个答案:

答案 0 :(得分:0)

如果您想将文本限制为ALPHA / NUMERIC,可以使用如下文本格式:

public class MaxLengthTextFormatter extends TextFormatter<String> {
    private int maxLength;

public MaxLengthTextFormatter(int maxLength) {
    super(new UnaryOperator<TextFormatter.Change>() {
        @Override
        public TextFormatter.Change apply(TextFormatter.Change change) {
            //If the user is deleting the text (i.e. full selection, ignore max to allow the
            //change to happen)
            if(change.isDeleted()) {
                //if the user is pasting in, then the change could be longer
                //ensure it stops at max length of the field
                if(change.getControlNewText().length() > maxLength){
                    change.setText(change.getText().substring(0, maxLength));
                }

            }else if (change.getControlText().length() + change.getText().length() >= maxLength) {
                int maxPos = maxLength - change.getControlText().length();
                change.setText(change.getText().substring(0, maxPos));
            }
            return change;
        }
    });
    this.maxLength = maxLength;
}

public int getMaxLength()
{
    return maxLength;
}

}

public class AlphaNumericTextFormatter extends TextFormatter<String> {

    /** The Constant ALPHA_NUMERIC_ONLY. */
    //private static final String ALPHA_NUMERIC_ONLY = "^[a-zA-Z0-9]*$";
    /** MAKE NUMERIC ONLY **/
    private static final String DIGITS_ONLY = "^[0-9]*$";

    /**
     * Instantiates a new alpha numeric text formatter.
     */
    public AlphaNumericTextFormatter() {
        super(applyFilter(null));
    }

    /**
     * Instantiates a new alpha numeric text formatter.
     *
     * @param maxLength
     *            the max length
     */
    public AlphaNumericTextFormatter(int maxLength) {
        super(applyFilter(new MaxLengthTextFormatter(maxLength).getFilter()));
    }

    /**
     * Apply filter.
     *
     * @param filter
     *            the filter
     * @return the unary operator
     */
    private static UnaryOperator<Change> applyFilter(UnaryOperator<Change> filter) {
        return change -> {
            if (change.getControlNewText() != null && change.getControlNewText().matches(DIGITS_ONLY)) {
                if (filter != null) {
                    filter.apply(change);
                }
                return change;
            }
            return null;
        };
    }

}

创建格式化程序而不仅仅允许数字和字母 - 您可以根据需要调整模式。

您可以将它附加到您的文本字段....

@FXML
private TextField myTextField;


@FXML
private void initialize() {
    //Create a alpha field which max length of 4
    myTextField.setTextFormatter(new AlphaNumericTextFormatter(4));
}