例子
以下程序是 HBox 布局的示例。在这里,我们插入一个文本字段和两个按钮,播放和停止。这是用 10 的间距完成的,每个都有尺寸 - (10, 10, 10, 10) 的边距。
将此代码保存在名称为的文件中 HBoxExample.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.layout.HBox;
public class HBoxExample extends Application {
@Override
public void start(Stage stage) {
//creating a text field
TextField textField = new TextField();
//Creating the play button
Button playButton = new Button("Play");
//Creating the stop button
Button stopButton = new Button("stop");
//Instantiating the HBox class
HBox hbox = new HBox();
//Setting the space between the nodes of a HBox pane
hbox.setSpacing(10);
//Setting the margin to the nodes
hbox.setMargin(textField, new Insets(20, 20, 20, 20));
hbox.setMargin(playButton, new Insets(20, 20, 20, 20));
hbox.setMargin(stopButton, new Insets(20, 20, 20, 20));
//retrieving the observable list of the HBox
ObservableList list = hbox.getChildren();
//Adding all the nodes to the observable list (HBox)
list.addAll(textField, playButton, stopButton);
//Creating a scene object
Scene scene = new Scene(hbox);
//Setting title to the Stage
stage.setTitle("Hbox Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令从命令提示符编译并执行保存的 java 文件。
javac HBoxExample.java
java HBoxExample.java
执行时,上述程序会生成一个 JavaFX 窗口,如下所示。