簡體   English   中英

如何使用 hbox 向 StackPane 添加填充

[英]How can I add padding to StackPane using hbox

我仍在學習如何處理面板和 hbox、vbox 等。我希望能夠圍繞 StackPane 的中心設置填充。

@Override
    public void start(Stage stage) throws Exception {

        stage.setTitle("GUIGUI");
       
        HBox hbox = new HBox(10); // number sets spacing between things
        
        Button roll1 = new Button("Roll");
        hbox.setPadding(new Insets(40,40,40,40));
        hbox.getChildren().add(roll1);  
        
        StackPane root = new StackPane();
        root.setAlignment(hbox, Pos.CENTER);
        root.getChildren().add(hbox);

        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.show();  
        
    }
public static void main(String[] args) {
        launch(args);
         
    }
...

我已經嘗試使用 hbox 在滾動(這是一個按鈕)周圍設置填充,以便在 StackPane 中調用(?)時它的填充為 40,40,40,40。

我的代碼在按鈕周圍設置了填充,但即使我已經完成,它也沒有位於中心

root.setAlignment(hbox, Pos.CENTER);

你可能想要這樣的東西。 這會為您的 StackPane 添加填充並使您的按鈕居中。 確保您只有 javafx 導入而不是 awt 導入。

    @Override
    public void start(Stage stage) throws Exception {

        stage.setTitle("GUIGUI");
       
        HBox hbox = new HBox(10); // number sets spacing between things
        
        Button roll1 = new Button("Roll");
        hbox.setPadding(new Insets(40,40,40,40));
        hbox.getChildren().add(roll1);
        hbox.setAlignment(Pos.CENTER);
        hbox.setStyle("-fx-background-color:TAN");
        
        StackPane root = new StackPane();
        root.getChildren().add(hbox);
        root.setPadding(new Insets(40,40,40,40));
        root.setStyle("-fx-background-color:BLUE");
        

        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.show();  
        
    }

我不是 100% 確定您要做什么,但我認為您應該給HBox一個首選尺寸。 然后您應該將HBox最大大小設置為USE_PREF_SIZE

我使用@Kleopatra 的建議更新了答案。

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class App extends Application
{

    @Override
    public void start(Stage stage)
    {
        stage.setTitle("GUIGUI");

        HBox hbox = new HBox(10); // number sets spacing between things
        hbox.setStyle("-fx-background-color: yellow");
        Button roll1 = new Button("Roll");
        hbox.setPadding(new Insets(40, 40, 40, 40));
        hbox.getChildren().add(roll1);
        hbox.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
        StackPane root = new StackPane();
        root.getChildren().add(hbox);
        root.setStyle("-fx-background-color: green");
        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.show();
    }
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM