JavaFX: Red border for text field

后端 未结 4 2045
生来不讨喜
生来不讨喜 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:41

    With this it now works pefectly fine (it doesn't even need "setUpValidation"):

    public void initialize(URL arg0, ResourceBundle arg1) {
        removeRed(tfFirstName);
        removeRed(tfLastName);
    }
    
    public void OKButtonClicked() {
        try{
            //also: call validation class here
            removeRed(tfFirstName);
            removeRed(tfLastName);
        } catch(ValidationException e) {
            setRed(tfFirstName);
            setRed(tfLastName);
        }
    
    }
    
    private void setRed(TextField tf) {
        ObservableList styleClass = tf.getStyleClass();
    
        if(!styleClass.contains("tferror")) {
            styleClass.add("tferror");
        }
    }
    
    
    private void removeRed(TextField tf) {
        ObservableList styleClass = tf.getStyleClass();
        styleClass.removeAll(Collections.singleton("tferror"));
    }
    

    And in the css I added the following (unfortunately it didn't change the border width with "-fx-border-width: 2px" anymore):

    .tferror {  
         -fx-text-box-border: red ;
         -fx-focus-color: red ;   
    }
    

提交回复
热议问题