JavaFX边框标题

6

图片描述

上图是我的代码结果,但我想要像下面这样的效果。
图片描述

我该怎么解决?以下是我的代码。我看了很多资料,但它们都太复杂了。比如我看过的一个,我认为这种方法非常复杂。也许有一个简单的方法来解决这个问题。

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Test extends Application {

    public BorderPane border = new BorderPane();

    public Label name = new Label("Name");
    public Label surname = new Label("Surname");

    public TextField name1 = new TextField();
    public TextField surname1 = new TextField();

    public static void main(String[] args) {
        launch(args);

    }

    @Override
    public void start(Stage arg0) throws Exception {
        Scene scene = new Scene(new VBox(), 300, 200);
        arg0.setTitle("Header");
        arg0.setResizable(false);
        scene.setFill(Color.OLDLACE);

        StackPane grid = addStackPane();
        border.setMargin(grid, new Insets(12,12,12,12));
        border.setCenter(grid);

        ((VBox) scene.getRoot()).getChildren().add(border);
        arg0.setScene(scene);
        arg0.show();

    }

    @SuppressWarnings("static-access")
    public StackPane addStackPane() {
        StackPane pane = new StackPane();
        GridPane grid = new GridPane();
        Label title = new Label("Border Title");
        title.setStyle("-fx-translate-y: -7");
        pane.setAlignment(title, Pos.TOP_LEFT);
        grid.setStyle("-fx-content-display: top");
        grid.setStyle("-fx-border-insets: 20 15 15 15");
        grid.setStyle("-fx-background-color: white");
        grid.setStyle("-fx-border-color: black");
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 10, 25, 10));
        grid.add(name, 1, 0);
        grid.add(name1, 2, 0);

        grid.add(surname, 1, 1);
        grid.add(surname1, 2, 1);
        pane.getChildren().addAll(grid, title);

        return pane;
    }

}

感谢阅读此主题的所有人。
2个回答

5
尝试将标题标签的-fx-background-color设置为与borderPane的背景色相同。确保在css文件中进行设置,因为除非您将它们连接起来,否则无法通过setStyle()设置多个样式:
myComponent.setStyle("-fx-text-fill: white;"+
    "-fx-background-color: black;");

此外,使用内联样式表是一种不好的做法,因为它的优先级总是高于CSS样式表中指定的规则。

(如果您将pane.setAlignment(title, Pos.TOP_LEFT)更改为StackPane.setAlignment(title, Pos.TOP_LEFT),可以消除“静态访问”警告。)


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接