#JavaFXでシーン遷移をしよう
CSGAdventCalendarの22日目ですわ.三回目です,終わりも見えてきたところで,今回も張り切って書いて行きましょう
はじめに
JavaFXってなんやねんって方のために...
JavaFXはJAVA8からSWINGに代わり標準GUIとされているあれです.導入等の詳しいことはCSGAdventCalendarで他の人が書いてくださっているので https://qiita.com/Kei_22/items/f54e6ba7cd4bf71b14c8 を参考にしてください.
じゃあ本編
・まずは色々importします
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
・シーンを作成します
public class Main extends Application{
//シーンの宣言
public static Scene scene1 = null;
public static Scene scene2 = null;
scene1が初めのシーンでscene2が変更した後のシーンとなります.
・startの中
@Override
public void start(Stage stage)throws Exception {
stage.setTitle("HelloJavaFX");
stage.setHeight(200);
stage.setWidth(150);
// ステージの作成
initScene1(stage);
initScene2(stage);
stage.setScene(scene1);
stage.show();
}
initScene1とinitScene2でsceneのGUIを作成します.
そしてまずはScene1をセットしておきます.ここはタイトル画面とかお好きにどうぞ
・initScene1の中
public static void initScene1(Stage stage) {
AnchorPane root = new AnchorPane();
scene1 = new Scene(root);
Button btn = new Button("シーン変更");
btn.setPrefWidth(100);
btn.setPrefHeight(50);
btn.setOnMouseClicked(event -> setScene(stage,scene2));
root.getChildren().add(btn);
}
とりあえず今回はボタンを押したらシーンが変わるってだけなのでボタンを配置しただけです.
setOnMouseClickedでsetSceneメソッドを呼び出します.
setSceneメソッドはあとで定義します.
・initScene2の中
public static void initScene2(Stage stage) {
AnchorPane root = new AnchorPane();
scene2 = new Scene(root);
Label lbl = new Label("シーン遷移完了!");
root.getChildren().add(lbl);
}
シーンが変わったことを示すためにLabelを用意しました.
・setSceneの中
public static void setScene(Stage stage,Scene changeScene) {
stage.setScene(changeScene);
stage.show();
}
}
引数として送られてきたsceneをsetして完了!
全体の閉めのかっこもお忘れなく
どんな感じか
これでシーン遷移が...できまあああああした!!!!!!!!!!!!!!!
全体図
小分けにしていたscriptを一括でお見せします
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
public class Main extends Application{
//シーンの宣言
public static Scene scene1 = null;
public static Scene scene2 = null;
@Override
public void start(Stage stage)throws Exception {
stage.setTitle("HelloJavaFX");
stage.setHeight(200);
stage.setWidth(150);
// ステージの作成
initScene1(stage);
initScene2(stage);
stage.setScene(scene1);
stage.show();
}
public static void initScene1(Stage stage) {
AnchorPane root = new AnchorPane();
scene1 = new Scene(root);
Button btn = new Button("シーン変更");
btn.setPrefWidth(100);
btn.setPrefHeight(50);
btn.setOnMouseClicked(event -> setScene(stage,scene2));
root.getChildren().add(btn);
}
public static void initScene2(Stage stage) {
AnchorPane root = new AnchorPane();
scene2 = new Scene(root);
Label lbl = new Label("シーン変更成功!");
root.getChildren().add(lbl);
}
public static void setScene(Stage stage,Scene changeScene) {
stage.setScene(changeScene);
stage.show();
}
}
終わりに
JavaFXの情報少ないから!!!みんな!!!書こう!!!!!!!!!!やろう!!!!!!!!!
以上シーン遷移の備忘録でした.