How to display HTML in JavaFX Application

2019-06-19 00:17发布

问题:

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

Screenshot of my application:

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 ?

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

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

回答1:

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