2015-07-28 53 views
3

我怎麼能知道,如果在此對話框中的JavaFX按下確定或取消按鈕。JavaFX的 - 如何知道是否取消按下

對話框代碼:

public String delimiter; 

public void delimiterYES() throws IOException { 
    delimiter=new String(); 
    TextInputDialog dialog = new TextInputDialog(); 
    dialog.setTitle("Delimiter"); 
    dialog.setHeaderText("Enter the delimiter"); 

    Optional<String> result = dialog.showAndWait(); 
    if (result.isPresent()) { 
     delimiter=result.get(); 
    } 
} 
+0

的Javadoc並不清楚這一點。考慮到文件的問題:http://bugs.java.com – Puce

回答

3

如果結果存在,則用戶按下確定。如果沒有結果存在,則可能是按下用戶的取消,但他們可能剛剛關閉使用操作系統關閉窗口功能的對話窗口。

Optional<String> result = new TextInputDialog().showAndWait(); 
if (result.isPresent()) { 
    // ok was pressed. 
} else { 
    // cancel might have been pressed. 
} 

要真正知道,如果是按下按鈕,您可以使用過濾器作爲Dialog javadoc節「對話框驗證/攔截動作按鈕」指出。

final Button cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL); 
cancel.addEventFilter(ActionEvent.ACTION, event -> 
    System.out.println("Cancel was definitely pressed") 
); 

示例代碼:

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.scene.Scene; 
import javafx.scene.control.*; 
import javafx.stage.Stage; 

import java.util.Optional; 

public class DialogSample extends Application { 
    @Override 
    public void start(Stage stage) throws Exception { 
     Button showButton = new Button("show"); 
     showButton.setOnAction(event -> showDialog(stage)); 
     showButton.setPrefWidth(100); 
     stage.setScene(new Scene(showButton)); 
     stage.show(); 

     showButton.fire(); 
    } 

    private void showDialog(Stage stage) { 
     TextInputDialog dialog = new TextInputDialog(); 
     dialog.initOwner(stage); 
     dialog.setTitle("Delimiter"); 
     dialog.setHeaderText("Enter the delimiter"); 

     final Button ok = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK); 
     ok.addEventFilter(ActionEvent.ACTION, event -> 
      System.out.println("OK was definitely pressed") 
     ); 

     final Button cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL); 
     cancel.addEventFilter(ActionEvent.ACTION, event -> 
      System.out.println("Cancel was definitely pressed") 
     ); 

     Optional<String> result = dialog.showAndWait(); 
     if (result.isPresent()) { 
      System.out.println("Result present => OK was pressed"); 
      System.out.println("Result: " + result.get()); 
     } else { 
      System.out.println("Result not present => Cancel might have been pressed"); 
     }  
    } 

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

好吧,我發現這裏JavaFX Dialogs

的的answere的result.isPresent()將返回false,如果用戶取消了對話框。

相關問題