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

99封情书 提交于 2019-11-30 14:00:26

问题


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:

   static Paint value0 = Paint.valueOf("FFFFFF");
   TextField colorBox0;
   colorBox0.setBackground(new Background(new BackgroundFill(value0, CornerRadii.EMPTY, Insets.EMPTY)));

Any help is very much appreciated
Thank you


回答1:


I found that you can construct a string of css code out of a string and a variable by using the to string method and the substring method like this:

colorBox0
.setStyle("-fx-control-inner-background: #"+value0.toString().substring(2));



回答2:


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.




回答3:


Try to set the color using CSS:

TextField colorBox0;
colorBox0.setStyle("-fx-background-color: white;");



回答4:


Elegant solution with colour translation:

static Paint black = Paint.valueOf(Integer.toHexString(Color.BLACK.hashCode()));
TextField textfield;
textField.setStyle(
"-fx-control-inner-background: #"+black.toString().substring(2));


来源:https://stackoverflow.com/questions/27700006/how-do-you-change-the-background-color-of-a-textfield-without-changing-the-borde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!