「最初のアプリケーション」の版間の差分

提供: tknotebook
移動: 案内検索
(FXMLファイルを編集する)
(ボタンにイベントハンドラを追加する)
48行: 48行:
  
 
[[ファイル:最初のアプリケーション0003.png|800px]]
 
[[ファイル:最初のアプリケーション0003.png|800px]]
 +
 +
右側に見えている [On Action] がボタンのクリックイベントで、この中に
 +
testButtonOnAction
 +
と記入して Enter を押してください。画面下部のタブをクリックして'''[text]'''へ切り替えると
 +
sample.fxml は以下のように書き換わっています。
 +
 +
<?xml version="1.0" encoding="UTF-8"?>
 +
 +
<?import javafx.scene.control.Button?>
 +
<?import javafx.scene.layout.ColumnConstraints?>
 +
<?import javafx.scene.layout.GridPane?>
 +
<?import javafx.scene.layout.RowConstraints?>
 +
 +
 +
<GridPane alignment="center" hgap="10" vgap="10" xmlns:fx="http://javafx.com/fxml/1"
 +
          xmlns="http://javafx.com/javafx/8.0.101" fx:controller="sample.Controller">
 +
    <columnConstraints>
 +
        <ColumnConstraints/>
 +
    </columnConstraints>
 +
    <rowConstraints>
 +
        <RowConstraints/>
 +
    </rowConstraints>
 +
    <children>
 +
        <Button mnemonicParsing="false" onAction="#testButtonOnAction" text="Button" />
 +
    </children>
 +
</GridPane>
 +
 +
エディタの中では '''testButtonOnAction''' が赤くなっているはずですが、カーソルを持って行って ALT+ENTER を押すと
 +
ポップアップメニューで[Create method void testButtonOnAction(ActionEvent)] が現れますので、これを選んでください。
 +
'''IntelliJ IDEA が イベントハンドラのひな型をコントローラ(Controller.java)に自動生成してくれます'''。
 +
 +
ファイル Controller.java
 +
 +
package sample;
 +
 +
import javafx.event.ActionEvent;
 +
 +
public class Controller {
 +
    public void testButtonOnAction(ActionEvent actionEvent) {
 +
    }
 +
}
 +
 +
 +
この中にコードを書けば、それはボタンクリック時に実行されます。
 +
挨拶を行うコードを書き込むと以下のようになります。
 +
 +
package sample;
 +
 +
import javafx.event.ActionEvent;
 +
import javafx.scene.control.Alert;
 +
 +
public class Controller {
 +
    public void testButtonOnAction(ActionEvent actionEvent) {
 +
        Alert dlg = new Alert(Alert.AlertType.INFORMATION);
 +
        dlg.setTitle("ご挨拶");
 +
        dlg.setHeaderText(null);
 +
        dlg.setContentText("こんにちは");
 +
        dlg.showAndWait();
 +
    }
 +
}
 +
 +
 +
==実行==
 +
 +
実行すると以下のようになります。
 +
 +
起動した直後
 +
[[ファイル:最初のアプリケーション0004.png]]
 +
 +
ボタンを押したとき
 +
[[ファイル:最初のアプリケーション0005.png]]

2016年9月17日 (土) 05:08時点における版