java 规则“-fx-text-alignment”不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30326525/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:54:44  来源:igfitidea点击:

The rule "-fx-text-alignment" doesn't work?

javajavafxjavafx-css

提问by Oscar

I'm creating a simple user interface with JavaFX, where some labels showing texts are used. I tried to move text to the center of labels with the rule:

我正在使用 JavaFX 创建一个简单的用户界面,其中使用了一些显示文本的标签。我尝试使用规则将文本移动到标签的中心:

-fx-text-alignment: center

yet it doesn't work and text is still located on the left by default. I have also checked that I haven't used any other rules that could override this. Any ideas? Here is the css code:

但它不起作用,默认情况下文本仍位于左侧。我还检查过我没有使用任何其他可以覆盖它的规则。有任何想法吗?这是css代码:

#subtitle
{
    -fx-font: bold italic 18pt "Arial";
    -fx-text-alignment: center;
    -fx-effect: dropshadow( one-pass-box, black, 8, 0.0, 2, 0 );
    -fx-text-fill: #1ebd1e;
}

Java code:

爪哇代码:

Label title = new Label("Trees");
title.setId("subtitle");
grid.add(title, 0, 0, 2, 1);

enter image description here

在此处输入图片说明

回答by maurille

I have the same problem.

我也有同样的问题。

The text in the label cannot be centered or right aligned, or ... nor in CSS nor in code like mylabel.setTextAlignment(TextAlignment.Center)when the label is larger than the text.

标签中的文本不能居中或右对齐,或者 ... 也不能在 CSS 中,也不能在代码中,例如mylabel.setTextAlignment(TextAlignment.Center)标签大于文本时。

I use instead mylabel.setAlignment(Pos.CENTER)to solve the problem; also works in CSS with -fx-alignment:center;

我用代替mylabel.setAlignment(Pos.CENTER)来解决问题;也适用于 CSS-fx-alignment:center;

回答by henriqueor

You can solve this problem using the code below:

您可以使用以下代码解决此问题:

Label title = new Label("Trees");
title.setId("subtitle");
GridPane.setHalignment(title, HPos.CENTER);
gridpane.add(title, 0, 0, 2, 1);

This is the result I got:

这是我得到的结果:

enter image description here

在此处输入图片说明

Note:The -fx-text-alignmenttag is going to center the text inside the label's borders. If the label's width is exactly the size it needs to fit the text, you have no changes about the alignment, but if you set a width bigger than the text needs you can align the text inside the Label's borders.

注:-fx-text-alignment标签将会居中标签边框内的文本。如果标签的宽度恰好是适合文本所需的大小,则对齐方式没有任何更改,但如果您设置的宽度大于文本所需的宽度,则可以在标签的边框内对齐文本。