文章目录
创建按钮
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class Main extends Application {
/*
JavaFX是借用剧院的术语来命名应用程序界面的,
JavaFX程序用户界面的顶层称为Stage,代表窗口,
舞台Stage中摆放的是场景Scene,场景Scene中
可以包含各种局部面板和控件共同组成用户界面。
*/
@Override
public void start(Stage primaryStage) throws Exception{
//创建按钮
Button btn = new Button("我是按钮");
//创建场景并添加按钮
Scene scene = new Scene(btn,210,80);
primaryStage.setTitle("我的JavaFX窗口");
//创建舞台并添加场景
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
运行效果图如下:
创建栈面板并放置按钮
栈面板就是组件不断叠加,比如添加两个按钮,第一次添加按钮1,再添加按钮2时就会叠在按钮1上面,以此类推,不断在前面的基础上叠加。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Button btnConfirm = new Button("确定");
//创建栈面板
StackPane stackPane = new StackPane();
//设置按钮的颜色为蓝色
btnConfirm.setStyle("-fx-border-color: blue");
Button btnCancle = new Button("取消");
btnCancle.setPrefSize(80,50);
btnCancle.setStyle("-fx-border-color: green");
//将btnCancle按钮逆时针旋转45度
btnCancle.setRotate(-45);
//得到栈面板的节点并往上添加按钮
stackPane.getChildren().addAll(btnCancle,btnConfirm);
//将栈面板顺时针旋转45度
stackPane.setRotate(45);
stackPane.setStyle("-fx-border-color: red;-fx-background-color:lightgray;");
//设置场景并往场景上添加面板
Scene scene = new Scene(stackPane,180,100);
//创建舞台并往上面添加场景
primaryStage.setTitle("栈面板");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
效果图如下:
创建流式面板并放置按钮
流式面板就是按流水一样顺序排列,一个一个接着排,排完一行就换一行。
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Button[] btn = new Button[6];
//创建流式面板
FlowPane rootPane = new FlowPane();
//设置节点水平摆放
rootPane.setOrientation(Orientation.HORIZONTAL);
//设置面板边缘内侧上、右、下、左空白的距离
rootPane.setPadding(new Insets(12,13,14,15));
//设置面板上节点之间的水平距离为8像素
rootPane.setHgap(8);
//设置面板上节点之间的垂直距离为5像素
rootPane.setVgap(5);
for(int i=0;i<btn.length;i++){
btn[i] = new Button("按钮"+(i+1));
//添加按钮
rootPane.getChildren().add(btn[i]);
}
Scene scene = new Scene(rootPane,200,80);
primaryStage.setTitle("流式面板");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
效果图如下:
创建边界面板并在每个区域中放置一个按钮
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.