package fxdemo; import java.io.File; import java.net.URL; import javafx.scene.layout.BorderPane; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class ui extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { BorderPane root = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene scene = new Scene(root); stage.setTitle("Menu Test"); stage.setScene(scene); stage.show(); } }
<?xml version="1.0" encoding="UTF-8"?> <?import java.lang.*?> <?import java.util.*?> <?import javafx.scene.*?> <?import javafx.scene.control.*?> <?import javafx.scene.layout.*?> <BorderPane prefHeight="150.0" prefWidth="300.0" xmlns:fx="http://javafx.com/fxml" fx:controller="fxdemo.Controller" > <top> <MenuBar> <menus> <Menu text="松" > <MenuItem text="五葉松" fx:id="oomine" onAction="#handle_goyou" /> <MenuItem text="黒松" fx:id="okutyou" onAction="#handle_kuro" /> <MenuItem text="赤松" fx:id="chichibu" onAction="#handle_aka" /> </Menu> </menus> </MenuBar> </top> </BorderPane>
package fxdemo; import javafx.fxml.FXML; import javafx.fxml.Initializable; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; public class Controller implements Initializable { @FXML public void handle_goyou(ActionEvent event) { System.out.println( "五葉松" ); } @FXML public void handle_kuro(ActionEvent event) { System.out.println( "黒松" ); } @FXML public void handle_aka(ActionEvent event) { System.out.println( "赤松" ); } @Override public void initialize(URL url, ResourceBundle rb) { } }
コンパイル
javac fxdemo\ui.java fxdemo\Controller.java
実行
java fxdemo.ui
各メニュー項目をクリックするとコンソールに文字列が表示される