javafx中如何在不改变边框的情况下改变TextField的背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27700006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you change the background color of a TextField without changing the border in javafx?
提问by sazzy4o
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:
我试图将我的 TextField“colorBox0”的背景颜色更改为“value0”,但它摆脱了边框。
这是我的代码的简化版本:
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
非常感谢任何帮助
谢谢
采纳答案by sazzy4o
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:
我发现您可以使用 to string 方法和 substring 方法从字符串和变量中构造一串 css 代码,如下所示:
colorBox0
.setStyle("-fx-control-inner-background: #"+value0.toString().substring(2));
回答by javaHunter
Try to set the color using CSS:
尝试使用 CSS 设置颜色:
TextField colorBox0;
colorBox0.setStyle("-fx-background-color: white;");
回答by eckig
Looking at the (shortened) default JavaFX styles for the TextField
explains a lot:
查看(缩短的)默认 JavaFX 样式TextField
解释了很多:
.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.
所以背景是包括边框的分层背景。这种技术在整个 JavaFX 中被大量使用。但是只修改一种颜色非常容易。
First we need to assign a new custom style class to our TextField
:
首先,我们需要为我们的 分配一个新的自定义样式类TextField
:
TextField textField = new TextField();
textField.getStyleClass().add("custom");
and the CSS file:
和 CSS 文件:
.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.
如您所见,您不必覆盖文本字段的所有样式,仅覆盖用于背景的颜色变量就足够了。
回答by Jerzy Nowakowski
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));