(JavaFX)如何根据输入的有效性更改文本字段中的文本颜色?

时间:2019-05-12 23:27:53

标签: javafx input textfield

我需要知道如何更改文本字段的文本颜色。如果输入无效,则文本应更改为红色。如果有效,则应改回黑色。单击文本框时,颜色需要更改。

我曾尝试使用EventHandler来完成工作,但是单击文本框时会有延迟。我的教授说要使用绑定,但是我不确定要绑定什么。

import javafx.application.Application;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.*;
import org.junit.Test;


public class DataEntryGUI extends Application{
    @Override
    public void start(Stage primaryStage){
        GridPane root = new GridPane();
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(30, 30, 30, 30));
        root.setHgap(5.5);
        root.setVgap(5.5);

        // TextFields
        NameTextField firstName = new NameTextField();
        firstName.setPromptText("Name");
        firstName.setOnMouseExited(e -> NameTextField.nameIsValid(firstName));

        NameTextField secondName = new NameTextField();
        secondName.setPromptText("Name");
        secondName.setOnMouseExited(e -> NameTextField.nameIsValid(secondName));

        NameTextField thirdName = new NameTextField();
        thirdName.setPromptText("Name");
        thirdName.setOnMouseExited(e -> NameTextField.nameIsValid(thirdName));

        PhoneTextField firstNumber = new PhoneTextField();
        firstNumber.setPromptText("(###) ###-####");
        firstNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(firstNumber));

        PhoneTextField secondNumber = new PhoneTextField();
        secondNumber.setPromptText("(###) ###-####");
        secondNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(secondNumber));

        PhoneTextField thirdNumber = new PhoneTextField();
        thirdNumber.setPromptText("(###) ###-####");
        thirdNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(thirdNumber));

        // "Create Profiles" button
        StackPane btnPane = new StackPane();
        Button btn = new Button("Create Profiles");
        btnPane.getChildren().add(btn);
        StackPane.setAlignment(btn, Pos.CENTER);

        //Enable/Disable button depending on if any TextField is empty
        btn.disableProperty().bind(firstName.textProperty().isEmpty()
            .or(secondName.textProperty().isEmpty()).or(thirdName.textProperty().isEmpty())
            .or(firstNumber.textProperty().isEmpty()).or(secondNumber.textProperty().isEmpty())
            .or(thirdNumber.textProperty().isEmpty()));

        // Layout of window
        root.add(firstName, 0, 0);
        root.add(secondName, 0, 1);
        root.add(thirdName, 0, 2);
        root.add(firstNumber, 1, 0);
        root.add(secondNumber, 1, 1);
        root.add(thirdNumber, 1, 2);
        root.add(btnPane, 0, 3, 2, 3);

        // Creating scene
        Scene scene = new Scene(root);
        primaryStage.setTitle("Data Entry GUI");
        primaryStage.setScene(scene); primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}



import javafx.scene.control.TextField;

public class NameTextField extends TextField{
    public NameTextField(){
        super();
    }
    public NameTextField(String text){
        super(text);
    }
    public static void nameIsValid(NameTextField input) {
        String text = input.getText();
        if (text.split(" ").length != 2)
            input.setStyle("-fx-text-inner-color: red;");
        else
            input.setStyle("-fx-text-inner-color: black;");
    }
}



import javafx.scene.control.TextField;

import javax.xml.soap.Text;


public class PhoneTextField extends TextField {
    public PhoneTextField(){
        super();
    }
    public PhoneTextField(String text){
        super(text);
    }
    public static void phoneIsValid(PhoneTextField input){
        String text = input.getText();
        if (text.split(" ").length != 2)
            input.setStyle("-fx-text-inner-color: red;");
        else
            return;

    }
}

2 个答案:

答案 0 :(得分:1)

您可以在字段的textProperty上完成此操作:

textField.textProperty().addListener((ObservableValue<? extends String> o, String oldValue, String newValue) ->
{                             
    if (!isStringValidPhoneNumber(newValue))
    {
        textField.setStyle("-fx-border-color: red ; -fx-border-width: 1px ;");
    } else
    {                
        textField.setStyle(null);               
    }

}

public static boolean isStringValidPhoneNumber (String field)
{
    // do the validating here
    return false;
}

答案 1 :(得分:0)

因此,从一开始,您应该重新考虑一些事情,例如,如果您不断重新键入同一件事,则将setPromptText(...);分别设置为同一件事,很有可能可以完成效率更高,所以我创建了一个初始化方法,该方法执行您要重新键入的事情,这意味着在初始化类时它将运行,而该方法中的内容我也从nameIsValid()方法中删除了静态方法,因为它不需要以及textfield输入参数。然后我解雇名称是在文本字段上失去焦点的有效方法,因为这是一个更好的设计。看看下面的最终结果

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(30, 30, 30, 30));
        root.setHgap(5.5);
        root.setVgap(5.5);

        // TextFields
        NameTextField firstName = new NameTextField();
//        firstName.setPromptText("Name");
//        firstName.setOnMouseExited(e -> NameTextField.nameIsValid(firstName));

        NameTextField secondName = new NameTextField();
//        secondName.setPromptText("Name");
//        secondName.setOnMouseExited(e -> NameTextField.nameIsValid(secondName));

        NameTextField thirdName = new NameTextField();
//        thirdName.setPromptText("Name");
//        thirdName.setOnMouseExited(e -> NameTextField.nameIsValid(thirdName));

        PhoneTextField firstNumber = new PhoneTextField();
//        firstNumber.setPromptText("(###) ###-####");
//        firstNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(firstNumber));

        PhoneTextField secondNumber = new PhoneTextField();
//        secondNumber.setPromptText("(###) ###-####");
//        secondNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(secondNumber));

        PhoneTextField thirdNumber = new PhoneTextField();
//        thirdNumber.setPromptText("(###) ###-####");
//        thirdNumber.setOnMouseExited(e -> PhoneTextField.phoneIsValid(thirdNumber));

        // "Create Profiles" button
        StackPane btnPane = new StackPane();
        Button btn = new Button("Create Profiles");
        btnPane.getChildren().add(btn);
        StackPane.setAlignment(btn, Pos.CENTER);

        //Enable/Disable button depending on if any TextField is empty
        btn.disableProperty().bind(firstName.textProperty().isEmpty()
                .or(secondName.textProperty().isEmpty()).or(thirdName.textProperty().isEmpty())
                .or(firstNumber.textProperty().isEmpty()).or(secondNumber.textProperty().isEmpty())
                .or(thirdNumber.textProperty().isEmpty()));

        // Layout of window
        root.add(firstName, 0, 0);
        root.add(secondName, 0, 1);
        root.add(thirdName, 0, 2);
        root.add(firstNumber, 1, 0);
        root.add(secondNumber, 1, 1);
        root.add(thirdNumber, 1, 2);
        root.add(btnPane, 0, 3, 2, 3);

        // Creating scene
        Scene scene = new Scene(root);
        primaryStage.setTitle("Data Entry GUI");
        primaryStage.setScene(scene); primaryStage.show();
    }

    public static void main(String[] args) { launch(args); }

    public class NameTextField extends TextField {
        public NameTextField(){
            super();
            initialize();
        }
        public NameTextField(String text){
            super(text);
            initialize();
        }
//        public static void nameIsValid(NameTextField input) {
        private void nameIsValid() {
            String text = this.getText();
            if (text.split(" ").length != 2)
                this.setStyle("-fx-border-color: red; -fx-text-inner-color: red;");
            else
                this.setStyle("-fx-text-inner-color: black;");
        }
        private void initialize() {
            this.setPromptText("Name");
            this.focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
                if (oldPropertyValue)
                    nameIsValid();
            });
        }
    }

    public class PhoneTextField extends TextField{
        public PhoneTextField(){
            super();
            initialize();
        }
        public PhoneTextField(String text){
            super(text);
            initialize();
        }
//        public static void phoneIsValid(PhoneTextField input){
        private void phoneIsValid(){
            String text = this.getText();
            if (text.split(" ").length != 2)
                this.setStyle("-fx-border-color: red; -fx-text-inner-color: red;");
            else
                this.setStyle("-fx-text-inner-color: black;");

        }
        private void initialize() {
            this.setPromptText("(###) ###-####");
            this.focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
                if (oldPropertyValue)
                    phoneIsValid();
            });
        }
    }
}