我试图将两个按钮直接放在标签下,并使所有内容都集中在表单上。当前,所有内容都只打印在一行上。
@Override public void start(Stage primaryStage)引发异常{
HBox hb = new HBox();
hb.setSpacing(15);
hb.setPadding(new Insets(15, 20, 5, 10));
hb.setAlignment(Pos.CENTER);
Label label = new Label("Greetings! Would you like to purchase cruise ticket for a family of two?");
hb.getChildren().add(label);
button1 = new Button("Yes");
hb.getChildren().add(button1);
button1.setOnAction(this);
button2 = new Button("No");
hb.getChildren().add(button2);
button2.setOnAction(this);
Scene scene = new Scene(hb, 550, 250);
primaryStage.setTitle("Cruise for two!");
primaryStage.setScene(scene);
primaryStage.show();
}
答案 0 :(得分:3)
有关JavaFX中可用的许多布局选项的更多信息,Oracle提供了一个great tutorial,建议您查看!
HBox
始终将其子级排列在水平行中。通过将您的Label
添加到HBox
中,JavaFX可以按照您的指示进行操作。
您还有一个VBox
,它可以垂直排列节点。在VBox
中,添加您的Label
,然后添加您的HBox
;它们将与HBox
下的Label
一起排列。
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.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private Button button1;
private Button button2;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
HBox hb = new HBox();
hb.setSpacing(15);
hb.setPadding(new Insets(15, 20, 5, 10));
hb.setAlignment(Pos.CENTER);
Label label = new Label("Greetings! Would you like to purchase cruise ticket for a family of two?");
root.getChildren().add(label);
button1 = new Button("Yes");
hb.getChildren().add(button1);
button2 = new Button("No");
hb.getChildren().add(button2);
root.getChildren().add(hb);
Scene scene = new Scene(root, 550, 250);
primaryStage.setTitle("Cruise for two!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
结果:
答案 1 :(得分:-1)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity">
<children>
<Label text="Label" />
<HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity">
<children>
<Button mnemonicParsing="false" text="Button" />
<Button mnemonicParsing="false" text="Button" />
</children>
</HBox>
</children>
</VBox>
</children>
</StackPane>