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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30829164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:43:03  来源:igfitidea点击:

How to display HTML in JavaFX Application

javajavafxjavafx-8

提问by Sai Upadhyayula

I am developing a FontViewer application which changes the font of the text based on the selected font style.

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

This is the controller class of my application

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

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);
    }
}

Screenshot of my application:

我的应用程序截图:

enter image description here

在此处输入图片说明

When I use a TextArea, it displays just the plain HTML code instead of converting the HTML to Text. Which control should I use to accomplish this?

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

P.S: I tried TextFlowbut it doesn't work, as I need to display different Styles and font-sizes for the required text.

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

I also looked at WebViewbut didn't understand how it could solve the mentioned problem.

我也看了WebView但不明白它如何解决提到的问题。

回答by James_D

Use a web view:

使用网络视图:

@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);
}