JavaFX: Red border for text field

后端 未结 4 2039
生来不讨喜
生来不讨喜 2020-12-28 17:52

I have a form with text fields and I want to give them a red border if I click on \"save\" but e.g. nothing was input in required fields, letters for the \"birthday\" field,

4条回答
  •  情深已故
    2020-12-28 18:27

    The above mentioned solution by James_D works perfectly fine ( but not for JAVAFX 8.0 ). James have already mentioned the code changes for JAVAFX 8.0, i just tried that and it works like a charm. Here is the changed version for JAVAFX 8.0, just incase someone needs a quick reference.All CREDIT GOES TO JAMES_D

    import java.util.Collections;
    
    import javafx.application.Application;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.ObservableList;
    import javafx.css.PseudoClass;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    
    public class ValidatingTextFieldExample extends Application {
    private final PseudoClass errorClass = PseudoClass.getPseudoClass("error");
    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        TextField nameTF = new TextField();
        TextField emailTF = new TextField();
    
        root.add(new Label("Name:"), 0, 0);
        root.add(nameTF, 1, 0);
        root.add(new Label("Email:"), 0, 1);
        root.add(emailTF, 1, 1);
    
        setUpValidation(nameTF);
        setUpValidation(emailTF);
    
        Scene scene = new Scene(root, 250, 150);
        scene.getStylesheets().add(getClass().getResource("text-field-red-border.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void setUpValidation(final TextField tf) { 
        tf.textProperty().addListener(new ChangeListener() {
    
            @Override
            public void changed(ObservableValue observable,
                    String oldValue, String newValue) {
                validate(tf);
            }
    
        });
    
        validate(tf);
    }
    
    private void validate(TextField tf) {
        ObservableList styleClass = tf.getStyleClass();
        if (tf.getText().trim().length()==0) {
            tf.pseudoClassStateChanged(errorClass, true);
        }
        else{
            tf.pseudoClassStateChanged(errorClass, false);
        }
    
    }
    
    public static void main(String[] args) {
        launch(args);
    }
    

    }

提交回复
热议问题