IntelliJ IDEA創建JavaFX項目
阿新 • • 發佈:2017-08-30
alt star control new label extend insets hello div
點擊File>New>Project,選中Java FX,Next,填寫項目名稱和路徑,Finish
項目創建成功,目錄如下,src下為項目源碼,out目錄下為編譯結果。
Main為項目主入口,sample.fxml為資源文件,可以看到main方法選擇從sample.fxml加載窗口元素。
Main.java和sample.fxml初始代碼
public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root= FXMLLoader.load(getClass().getResource("sample.fxml")); primaryStage.setTitle("Hello World"); primaryStage.setScene(new Scene(root, 300, 275)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
<?import javafx.geometry.Insets?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"> </GridPane>
因為初始狀態sample.fxml中沒有元素,此時運行Main方法,項目啟動,只有一個默認窗口
我們給sample.fxml添加一些元素
<?import javafx.geometry.Insets?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.TextField?> <?import javafx.scene.control.PasswordField?> <?import javafx.scene.text.Text?> <GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"> <Label text="User Name:" GridPane.columnIndex="0" GridPane.rowIndex="1"/> <TextField GridPane.columnIndex="1" GridPane.rowIndex="1"/> <Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="2"/> <PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="2"/> </GridPane>
點擊運行
IntelliJ IDEA創建JavaFX項目