如何在JavaFX应用程序中显示HTML [英] How to display HTML in JavaFX Application

查看:905
本文介绍了如何在JavaFX应用程序中显示HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我的申请截图:

当我使用TextArea时,它只显示纯HTML代码,而不是将HTML转换为Text。我必须使用哪种控件才能完成此操作?

When I am using TextArea it is displaying just the plain HTML code instead of converting the HTML to Text. Which control I must use to accomplish this ?

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

P.S: I tried TextFlow but its not working as I need to display different Styles and font-sizes for the required text.

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

I also looked at WebView but didn't understand how it can solve the mentioned problem.

推荐答案

使用网页浏览:

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

这篇关于如何在JavaFX应用程序中显示HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆