Eclipse開發JavaFX項目入門
一、下載與安裝
Eclipse中添加新插件:
Name: e(fx)clipse
Location: http://download.eclipse.org/efxclipse/updates-released/2.3.0/site
下載JavaFX Scene Builder 2.0
URL:http://www.oracle.com/technetwork/java/javase/downloads/javafxscenebuilder-1x-archive-2199384.html
安裝很簡單,略過。
啓動eclipse:Window -> References->JavaFX
加入JavaFX Scene Builder 2.0.exe
第一步就完成了。
二、簡單JavaFX項目
1.創建項目
選擇javafx項目
輸入javafx名稱,(環境:JDK8以上)
自動生成的項目結構
application包下創建fxml文件
File -> New -> Other
輸入名稱。
2.進入JavaFX Scene Builder
打開JavaFX Scene Builder
點擊AnchorPane
鼠標放在+ 拉大
3.添加組件
Containers中選擇Button組件
點擊Button組件,在右邊設置其屬性(默認也行)
設置Button的fx:id (重點)
右邊->code->fx:id,輸入一個名稱
我們在添加一個文本框,設置fx:id
隨意拖動,縮放。也可以設置其屬性
保存
預覽
預覽結果:
關閉
三、引用fxml,編寫Java代碼
1.創建application.MyController類
打開fxml文件
添加內容:fx:controller=”application.MyController”,保存
預覽如下(MyController,可以自己命名)
鼠標放在追加的內容上,右鍵->source->GenerateController
然後自動生成MyController類和字段
2.MyController類中編寫代碼(事件)
例如給Button很簡單的一個事件,MyController類代碼如下
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class MyController {
@FXML
private Button btn_1;
@FXML
private TextField text_1;
public void eventButton(){
String text = text_1.getText();//獲取文本框輸入的內容
System.out.println(text);
}
}
再進入JavaFX Scene Builder 2.0添加Button的事件
選擇Button,右邊框->code->OnAction,選擇eventButton
保存
3.添加Main類中的代碼
Main類中自動生成的代碼如下
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Main類中修改如下
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("SceneDemo.fxml"));//修改了
//BorderPane root = new BorderPane();
//設置Scene的大小(SceneBuilder中點擊AnchorPane右邊Layout中會顯示大小,不一樣的可以)
Scene scene = new Scene(root,500,522);//修改了
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setResizable(false);//設置不能窗口改變大小
primaryStage.setTitle("一個簡單的JavaFX");//設置標題
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
保存,運行Main類
結束,如有錯誤,敬請指明。
到這裏就結束了,剛開始使用CSDN,截圖和排版不當,諒解。
喜歡JavaFx的同學可以看看易白教程,將就一下,JavaFx教程、視頻都很少。
易白教程 :http://www.yiibai.com/javafx/javafx-tutorial-for-beginners.html
JavaFx 2.0 API(英文):http://pan.baidu.com/s/1hsnFRTU