2017-05-02 70 views
0

我一直試圖顯示一個大字符串作爲警報失敗。JavaFX警報不能適合內容

public void customAlert(String header, String body, ButtonType customBtn) { 
    clearAlert(); 
    alert.setHeaderText(header); 
    //alert.setContentText(body); 
    String content = ""; 
    int counter = 1; 

    int y=0; 
    for (int x = 0; x < body.length(); ++x) { 
    // System.err.println("concat"); 
     if (x > counter * 50 && body.charAt(x) == ' ') { 
      // System.err.println("concat"); 
      ++counter; 
      for (; y < x; ++y) { 
       content.concat(Character.toString(body.charAt(y))); 

      } 
      content.concat(Character.toString('\n')); 
      // System.err.println(content); 
     } 
    } 
    alert.getDialogPane().setContent(new Label(content)); 

    alert.getDialogPane().setMaxWidth(500); 

    if (customBtn != null) { 
     alert.getButtonTypes().clear(); 
     alert.getButtonTypes().add(customBtn); 
    } 
    alert.showAndWait(); 
} 

首先我試着用setContentText(),它沒有顯示整個字符串。然後我使用了alert.getDialogPane()。setContent(new Label(body)); - 但警報框變得比屏幕大。然後我嘗試過濾String添加的換行符,並將maxWidth設置爲alert,但過濾不起作用。

+0

也許這將有助於:http://stackoverflow.com/questions/28937392/javafx-alerts-and-their-大小 – Mark

+0

使用[此處]的異常對話框(http://code.makery.ch/blog/javafx-dialogs- official /)。 – Sedrick

回答

0

對於長的文本,你關在一個TextArea呈現更好:

TextArea textArea = new TextArea(text); 
textArea.setPrefColumnCount(40); 
textArea.setPrefRowCount(20); 
textArea.setEditable(false); 
textArea.setWrapText(true); 
alert.getDialogPane().setContent(textArea); 
+0

這可以工作,但我使用Alert對象的一個​​實例用於多個警報。當我想從對話框中刪除文本區域時,我不能添加任何setContentText() – Robert

+0

如果先調用'getDialogPane().setContent(null)',則可以調用'setContentText'。有關此優先級的規則,請參見[文檔contentText](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/DialogPane.html#contentTextProperty)。 – VGR