【问题标题】:JavaFX Alert cannot fit contentJavaFX 警报无法容纳内容
【发布时间】:2017-05-02 14:29:52
【问题描述】:

我一直试图将一个大字符串显示为警报,但没有成功。

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)); - 但警告框变得比屏幕尺寸更宽。然后我尝试过滤添加换行符的字符串并将 maxWidth 设置为警报,但过滤不起作用。

【问题讨论】:

标签: java javafx alert


【解决方案1】:

对于长文本,最好在 TextArea 中显示它:

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

【讨论】:

  • 这可行,但我使用一个 Alert 对象的实例来处理多个警报。当我想从对话框窗格中删除文本区域时,我无法添加任何 setContentText()
  • 如果您先拨打getDialogPane().setContent(null),然后您可以拨打setContentText。此优先级的规则在documentation for contentText 中进行了描述。
猜你喜欢
  • 2016-06-12
  • 1970-01-01
  • 2021-05-03
  • 2013-07-10
  • 2016-06-30
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多