我想画一条垂直线,这条垂直线可能与文本对象相交。当我这样做而不做任何修改时,该行直接穿过单词,使单词难以阅读。我想使该行在到达文本时消失,并在文本节点之后立即继续。我试过使用带有 css 背景的 toBack() 使文本在其周围形成一个正方形,但似乎文本节点具有透明背景,因此该行在字母后面仍然可见。是否有另一种方法可以使文本不与线相交?请注意,文本可能一直存在也可能不存在,并且由于我程序的性质,它可以位于任何坐标,所以我不能只画两条线(一条在文本之前,一条在文本之后)。
最佳答案
使用 Label
而不是 Text
会使事情变得更容易。 Label
是(最终)Region
的子类,因此它具有可以设置样式的背景颜色等属性,使其具有不透明背景。使用 CSS 规则
-fx-background-color: -fx-background ;
在标签上会给它默认的背景颜色。相比之下,Text
是 Shape
的子类,只有 fill
和 stroke
等属性,它们为分别构成文本的字形的内部和外部。
所以你可以这样做
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextVsLabel extends Application {
@Override
public void start(Stage primaryStage) {
StackPane labelPane = new StackPane();
labelPane.setMinSize(250, 250);
Label label = new Label("A Label");
label.setStyle("-fx-background-color: -fx-background;");
labelPane.getChildren().add(label);
addLineToPane(labelPane);
StackPane textPane = new StackPane();
textPane.setMinSize(250, 250);
textPane.getChildren().add(new Text("A Text"));
addLineToPane(textPane);
HBox root = new HBox(5, labelPane, textPane);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
private void addLineToPane(Pane pane) {
Line line = new Line();
line.startXProperty().bind(pane.widthProperty().divide(2));
line.endXProperty().bind(line.startXProperty());
line.setStartY(0);
line.endYProperty().bind(pane.heightProperty());
// add line to beginning of pane's parent list, so it appears
// behind everything else
pane.getChildren().add(0, line);
}
public static void main(String[] args) {
launch(args);
}
}
结果
请注意,如果您需要在标签中的文本周围留出更多空间,您可以在标签中添加填充:-fx-padding: 1em;
等
关于css - 如何在看不到节点内的线的情况下绘制与文本节点相交的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46184293/