How do you change the background color of a TextField without changing the border in javafx?

后端 未结 4 1447
离开以前
离开以前 2020-12-31 10:00

I am trying to change the background color of my TextField \"colorBox0\" to \"value0\" but it gets rid of the border.
Here is a simplified version of my code:

         


        
4条回答
  •  暖寄归人
    2020-12-31 10:30

    Looking at the (shortened) default JavaFX styles for the TextField explains a lot:

    .text-input {
      -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
      -fx-background-insets: 0, 1;
      -fx-background-radius: 3, 2;
    }
    

    So the background is a layered background including the border. This technique is used a lot throughout JavaFX. But it is very easy to modify just one color.

    First we need to assign a new custom style class to our TextField:

    TextField textField = new TextField();
    textField.getStyleClass().add("custom");
    

    and the CSS file:

    .custom {
      -fx-control-inner-background: orange;
    }
    

    As you can see, you do not have to override all styles of the textfield, it is sufficient to only override the color variable used for the background.

提交回复
热议问题