Javafx网格窗格中心元素

时间:2019-02-25 01:42:20

标签: java javafx

我正在研究javafx应用程序。它的一部分包括使用网格元素的滚动面板将列表渲染到Gui中。我正确地获得了所需的值,但是我不知道如何居中每个网格窗格单元。

// clear existing content if it exists  
    if(content.getChildren()!=null)
    {
        content.getChildren().clear();
    }
     // get Elements to display 
    OfferService os = new OfferService();
    List<Offer> myList = os.afficheroffre();
    UserService us = new UserService();

    GridPane Container = new GridPane();  // main container for all data specific to an offer
    Container.setAlignment(Pos.CENTER);

    // Scroll pane to display all the found contact requests
    ScrollPane scrollPane = new ScrollPane(Container);
    scrollPane.setPrefSize(900, 630);
    scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);

    AnchorPane.setTopAnchor(scrollPane, 0.);
    Container.setPrefWidth(900);
    Container.setPrefHeight(630);

    content.setRightAnchor(scrollPane, 0.);
    content.setBottomAnchor(scrollPane, 0.);
    content.setLeftAnchor(scrollPane, 0.);

    Container.setPadding(new Insets(30,0,0,30));

    // iterate through all offers and create an offer element
    int i = 0;
    int j = 0;
    for (Offer o : myList)
    {
       final User u = us.getById(o.getIdOfferuser());
        //HBox : single with spacing
        HBox Hb = new HBox();
        //VBox : single
        VBox Vb = new VBox();

        ImageView img = new ImageView(new Image("/Uploads/" + o.getImageOffer()));

        Label name = new Label(o.getNameOffer());

        ImageView avatar = new ImageView(new Image("/Uploads/" + u.getAvatar()));

        Button profile = new Button(u.getFirstName());

        Label price = new Label(String.valueOf(o.getPriceOffer()));

        Rating rating = new Rating();
        HBox hbb = new HBox();
        Button reserve = new Button("Reserve");

        Button details = new Button("more details");
        hbb.getChildren().add(reserve);
        hbb.getChildren().add(details);

        Vb.getChildren().add(name);
        Vb.getChildren().add(avatar);
        Vb.getChildren().add(profile);
        Vb.getChildren().add(price);
        Vb.getChildren().add(rating);
        Vb.getChildren().add(hbb);

        Hb.getChildren().add(Vb);

        // Add all the service elements to the services container
        Container.add(img,i,j);
        Container.add(Hb, i, j);

        i++;
        if(i>2)
        {
            i = 0;
            j++;
        }
    }

基本上我有这个令人失望的地方,我希望元素在Hb变量(HBox)内部居中。我尝试了Container.setAlignment(Pos.CENTER);但没有结果。任何帮助都非常实用enter image description here

1 个答案:

答案 0 :(得分:2)

您不能在GridPane级别上设置每个单元格的对齐方式。您需要在列级和行级进行设置。

因此,对于添加的每一列,您需要添加如下所示的列约束以使其水平居中对齐:

ColumnConstraints col = new ColumnConstraints();
col.setHalignment(HPos.CENTER);
gridPane.getColumnConstraints().add(col);

对于添加的每一行,您需要添加如下所示的行约束以使其垂直居中对齐:

RowConstraints row = new RowConstraints ();
row.setValignment(VPos.CENTER);
gridPane.getRowConstraints().add(row);