開発メモ

開発用のメモです。

JavaFX Confirm Dialog

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane prefHeight="100.0" prefWidth="300.0" xmlns:fx="http://javafx.com/fxml/1" fx:controller="jp.mirageworld.javafxexample01.ConfirmDialogController" fx:id="rootPane">
    <AnchorPane prefHeight="60" prefWidth="300" AnchorPane.topAnchor="5" AnchorPane.leftAnchor="0" style="-fx-background-color : #FFF" >
        <Label text="ここにメッセージが入ります" AnchorPane.leftAnchor="15" /> 
    </AnchorPane>
    <Button text="はい"   fx:id="yes"       prefHeight="30" prefWidth="80" onAction="#close" AnchorPane.bottomAnchor="5"  AnchorPane.rightAnchor="110" /> 
    <Button text="いいえ" fx:id="no"       prefHeight="30" prefWidth="80" onAction="#close" AnchorPane.bottomAnchor="5" AnchorPane.rightAnchor="10"  /> 
</AnchorPane>

ConfirmDialogController

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jp.mirageworld.javafxexample01;

import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * FXML Controller class
 *
 * @author numasawa
 */
public class ConfirmDialogController {
    
    public static boolean show(String message, Pane rootPane) throws Exception {
        FXMLLoader loader = new FXMLLoader(ConfirmDialogController.class.getResource("/fxml/confirm_dialog.fxml"));
        loader.load();
        
        Pane root = loader.getRoot();
        Scene scene = new Scene(root);

        Stage stage = new Stage(StageStyle.UTILITY);
        stage.setScene(scene);
        
        ConfirmDialogController controller = loader.getController();
        
        stage.initOwner(rootPane.getScene().getWindow());
        stage.setResizable(false);
        stage.initModality(Modality.WINDOW_MODAL);


        stage.showAndWait();
        
        return controller.result;
    }

    @FXML
    private AnchorPane rootPane;
    
    @FXML
    private Button yes;
    
    @FXML
    private Button no;
    
    private boolean result = false;
    
    @FXML
    void close(Event event) {
        result = event.getSource() == yes;
        rootPane.getScene().getWindow().hide();
    }
}

CALL

ConfirmDialogController .show("メッセージ", this.rootPane);
Twitter: @asahina_alice