基础框架
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
public void start(Stage primaryStage) {
//......
primaryStage.show();
}
}
可打开一个窗口
重要概念:舞台(窗口)、场景、布局、控件
( 工具为IDEA )
创建一个.fxml ( FXML File )文件,右键单击,选择Open In SceneBuilder
在Library的右侧搜索框中可搜索控件,拖拽就能自动生成布局和控件,Ctrl+S保存后会在.fxml文件自动生成布局和控件的代码
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("hello-controller.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
stage.setTitle("Hello");
stage.setScene(scene);
stage.show();
以上代码操作为:将hello-controller.fxml生成的布局加入场景(Scene)中,再将场景加入舞台(Stage)
运行该程序就能得到在SceneBuilder编辑的界面
这是位于右侧的功能,在Identity下面的输入将会自动生成变量声明,在DragDrop下面的输入将会自动生成方法声明
ScenceBuild在这里自动生成了代码,复制下来用于创建一个.class文件,在.fxml文件中找到
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1">
这一代码,改成
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.demo.HelloController">
就能在增加按钮等事件后编译运行了
之后的布局生成只需同样的方法,然后交给场景和布局就行了