2014-03-28 119 views
4
public void exitGame() { //pop up dialogue 
    Platform.exit(); 
} 

我已經嘗試了很多不同的東西,我在互聯網上看到過但我無法獲得任何工作。我所需要的只是一個簡單的對話框,當你點擊菜單中的退出按鈕時彈出,並詢問「你確定要退出嗎?」並提供了一個工作「是的,我敢肯定。」和「不,取消」按鈕。JavaFX對話框

+0

可能重複)在JavaFX 2.0?](http://stackoverflow.com/questions/8309981/how-to-create-and-show-common-dialog-error-warning-confirmation-in-javafx-2) – jewelsea

回答

6

下面是JavaFX對話框的示例。 JavaFx 2.x中沒有對話框api。所以你已經創建了自己的舞臺並在其中創建組件。

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.StackPane; 
import javafx.scene.layout.VBox; 
import javafx.stage.Modality; 
import javafx.stage.Stage; 

/** 
* @author JayaPrasad 
* 
*/ 
public class SampleDialog extends Application { 

    /* 
    * (non-Javadoc) 
    * 
    * @see javafx.application.Application#start(javafx.stage.Stage) 
    */ 
    @Override 
    public void start(Stage primaryStage) throws Exception { 
     primaryStage.setTitle("JavaFx Dialog"); 
     Button btn = new Button(); 
     btn.setText("Click me to display popup dialog"); 
     btn.setOnAction(new EventHandler<ActionEvent>() { 

      @Override 
      public void handle(ActionEvent event) { 
       final Stage dialogStage = new Stage(); 
       dialogStage.initModality(Modality.WINDOW_MODAL); 

       Label exitLabel = new Label("Are you sure you want to exit?"); 
       exitLabel.setAlignment(Pos.BASELINE_CENTER); 

       Button yesBtn = new Button("Yes"); 
       yesBtn.setOnAction(new EventHandler<ActionEvent>() { 

        @Override 
        public void handle(ActionEvent arg0) { 
         dialogStage.close(); 

        } 
       }); 
       Button noBtn = new Button("No"); 

       noBtn.setOnAction(new EventHandler<ActionEvent>() { 

        @Override 
        public void handle(ActionEvent arg0) { 
         dialogStage.close(); 

        } 
       }); 

       HBox hBox = new HBox(); 
       hBox.setAlignment(Pos.BASELINE_CENTER); 
       hBox.setSpacing(40.0); 
       hBox.getChildren().addAll(yesBtn, noBtn); 

       VBox vBox = new VBox(); 
       vBox.setSpacing(40.0); 
       vBox.getChildren().addAll(exitLabel, hBox); 

       dialogStage.setScene(new Scene(vBox)); 
       dialogStage.show(); 
      } 
     }); 

     StackPane root = new StackPane(); 
     root.getChildren().add(btn); 
     primaryStage.setScene(new Scene(root, 300, 250)); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 

} 
2

Lambda表達式是太好:

yesBtn.setOnAction (e -> dialogStage.close()); 
    noBtn.setOnAction (e -> dialogStage.close()); 

而且APPLICATION_MODAL可能是你想要什麼:

dialogStage.initModality (Modality.APPLICATION_MODAL); 
[如何創建和顯示通用對話框(錯誤,警告,確認的