JavaFX之對話框的創建

在JavaFX的官方API中,是沒有對話框相關的類。所以我們在需要使用對話框的時候,可以使用Swing的庫。但是由於風格相差較大,更多的時候我們需要用JavaFX來創建對話框。

  下面我們來看看怎麼用JavaFX來創建一個對話框吧。


  JavaFX用於創建對話框的類是Stage,沒錯。JavaFX程序的起始界面也是一個Stage。

  我們先用JavaFX Scene Builder來創建一個佈局文件。

  

  如圖所示,是一個簡單的提示框佈局,命名爲AlertDialog.fxml。

  然後修改XML文件如下圖所示:

  

  

  根部用fx:root標籤,然後指定根部的類型爲javafx.scene.layout.AnchorPane,注意,這裏要跟後面代碼裏相對應。然後把之前的佈局文件用<children>標籤包含起來。


  下面是我們事件代碼:

  

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import java.io.IOException;  
  2. import javafx.event.ActionEvent;  
  3. import javafx.fxml.FXML;  
  4. import javafx.fxml.FXMLLoader;  
  5. import javafx.scene.Scene;  
  6. import javafx.scene.control.Label;  
  7. import javafx.scene.control.TitledPane;  
  8. import javafx.scene.layout.AnchorPane;  
  9. import javafx.stage.Stage;  
  10. import javafx.stage.StageStyle;  
  11.   
  12. /** 
  13.  * 
  14.  * @author Wing 
  15.  */  
  16. public class WiAlertDialog  extends AnchorPane{  
  17.     @FXML  
  18.     Label alertMessage;  
  19.     @FXML  
  20.     TitledPane alertTitledPane;  
  21.       
  22.     private static WiAlertDialog wiAlertDialog;  
  23.     private static Stage  newAlertDialog ;  
  24.       
  25.     private  WiAlertDialog(String message) {  
  26.         FXMLLoader fXMLLoader = new FXMLLoader(getClass().getResource("AlertDialog.fxml"));  
  27.         fXMLLoader.setRoot(WiAlertDialog.this);  
  28.         fXMLLoader.setController(WiAlertDialog.this);  
  29.         try {  
  30.             fXMLLoader.load();  
  31.         } catch (IOException exception) {  
  32.             throw new RuntimeException(exception);  
  33.         }  
  34.         alertTitledPane.setFocusTraversable(false);  
  35.         alertMessage.setText(message);  
  36.     }  
  37.       
  38.     public static void showAlertDialog(String message) {  
  39.         newAlertDialog = new Stage(StageStyle.TRANSPARENT);  
  40.         newAlertDialog.setResizable(false);  
  41.         wiAlertDialog = new WiAlertDialog(message);  
  42.         newAlertDialog.setScene(new Scene(wiAlertDialog));  
  43.         newAlertDialog.show();  
  44.     }  
  45.       
  46.     public static void hideAlertDialog() {  
  47.         if(newAlertDialog != null) {  
  48.             newAlertDialog.hide();  
  49.         }  
  50.     }  
  51.   
  52.     @FXML  
  53.     private void onAlertOKClick(ActionEvent event) {  
  54.          WiAlertDialog.hideAlertDialog();  
  55.     }  
  56. }  

  我們先用FXMLLoader來載入FXML文件,然後設置根元素爲當前,也就是AnchorPane。接着設置Controller爲當前,也就是在FXML中指定的事件,我們可以在這裏實現(例如後面的onAlertOKClick事件)。


  然後我們用一個靜態的showAlertDialog來顯示對話框。

  在showAlertDialog中,我們創建一個Stage,和一個包含當前界面的Scene。通過Stage.show來顯示對話框,然後點擊"確定"按鈕後,執行onAlertOKClick來將Stage關閉。


  下面我們來看看效果:

  

  

  

  上下兩個對話框均是這樣實現的。

  大家可以在JavaFX開發中嘗試一下

發佈了1 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章