如何在 JavaFX 应用程序中显示 HTML

How to display HTML in JavaFX Application

我正在开发一个 FontViewer 应用程序,它根据所选的字体样式更改文本的字体。

这是我的应用程序class的控制器

public class FXMLDocumentController implements Initializable {

    @FXML
    private ListView fontListView;

    @FXML
    private TextArea fontTextArea;

    int[] fontSizes = {34, 28, 24, 20, 18, 16, 14, 12, 11, 10, 9, 8, 7, 6};

    String fontText = "";

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        ObservableList<String> fontsList = FXCollections.observableArrayList(Font.getFontNames());
        fontListView.setItems(fontsList);
    }

    @FXML
    public void handleMouseClickEvent(MouseEvent mouseEvent) {
        changeFont();
    }

    public void changeFont() {
        for (int i = 0; i < fontSizes.length; i++) {
            fontText += "<p style='font-family:" + fontListView.getSelectionModel().getSelectedItem() + ";font-size:" + fontSizes[i] + "'>" + "This is Sample Text</p>";
        }

        fontTextArea.setText(fontText);
    }
}

我的申请截图:

当我使用 TextArea 时,它只显示纯 HTML 代码,而不是将 HTML 转换为文本。我应该使用哪个控件来完成此操作?

P.S:我尝试了 TextFlow 但它不起作用,因为我需要为所需的文本显示不同的样式和字体大小。

我也看了WebView,但不明白它是如何解决上述问题的。

使用网络视图:

@FXML
private WebView fontWebView ;

// ...

public void changeFont() {
    StringBuilder sb = new StringBuilder(fontText);
    for (int i = 0; i < fontSizes.length; i++) {
        sb.append("<p style='font-family:")
          .append(fontListView.getSelectionModel().getSelectedItem())
          .append(";font-size:")
          .append( fontSizes[i])
          .append("'>This is Sample Text</p>");
    }
    fontText = sb.toString();
    fontWebView.getEngine().loadContent(fontText);
}

这是一个很晚的答案,但我想将它传递给那些需要将字体应用于各种 FX 控件的人(正如我需要做的那样):

您可以在不使用 WebView 的情况下显示字体,方法是使用 TextArea 的 setFont 方法。这具有适用于大多数文本显示 FX 控件的优点,包括 ButtonTextField 等...,并且可以与下载的 TTF 或 OTF 文件一起使用。

// examples create a 20 pt font
// system font
Font f = Font.font("SansSerif", Font.PLAIN, 20);
// TTF/OTF added to your project as a resource:
Font f = Font.loadFont(ClassLoader.getSystemClassLoader().getResourceAsStream("ResourceName"), 20);
// TTF/OTF loaded from a file dynamically... read the font file into an input stream, and:
Font f = Font.loadFont(inputStream, 20);
// to use:
fontTextArea.setFont(f);

注意:某些脚本 TTF/OTF 字体可以扩展到系统字体适合的区域上方或下方,因此在使用下载的字体时进行适当测试。