将滚动条添加到警报中

时间:2018-11-01 16:09:21

标签: javafx scrollbar alert

我有一种情况,我必须在javafx Alert

中输出一个巨大的字符串
 public static Optional<ButtonType> showAlertDialog(AlertType type, String title, String content) {
    TextArea textArea = new TextArea(content);
    textArea.setEditable(false);
    textArea.setWrapText(true);
    GridPane gridPane = new GridPane();
    gridPane.setMaxWidth(Double.MAX_VALUE);
    gridPane.add(textArea, 0, 0);

    Alert alert = new Alert(type);
    alert.setTitle(title);

    alert.setContentText(content);
    return alert.showAndWait();
}

当字符串大小超过屏幕大小时,我无法读取字符串的隐藏部分,如何将Scrollbar添加到Alert

1 个答案:

答案 0 :(得分:2)

当前,您没有将TextAreaGridPane添加到Alert中。您创建了它们,但是对它们什么也不做。相反,您只需设置contentText中的Alert。您实际上需要将具有内置滚动功能的TextArea添加到Alert

一种方法是设置DialogPane.content属性而不是contentText属性。

private Optional<ButtonType> showAlert(AlertType type, String title, String content) {
  Alert alert = new Alert(type);
  alert.setTitle(title);

  TextArea area = new TextArea(content);
  area.setWrapText(true);
  area.setEditable(false);

  alert.getDialogPane().setContent(area);
  alert.setResizable(true);

  return alert.showAndWait();
}

另一种方法是将TextArea添加为expandableContent,并使contentText为短消息。

private Optional<ButtonType> showAlert(AlertType type, String title, String shortMessage, String fullMessage) {
  Alert alert = new Alert(type);
  alert.setTitle(title);
  alert.setContentText(shortMessage);

  TextArea area = new TextArea(fullMessage);
  area.setWrapText(true);
  area.setEditable(false);

  alert.getDialogPane().setExpandableContent(area);

  return alert.showAndWait();
}