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
How to display HTML in JavaFX Application
提问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:
我的应用程序截图:
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 TextFlow
but it doesn't work, as I need to display different Styles and font-sizes for the required text.
PS:我试过TextFlow
但它不起作用,因为我需要为所需的文本显示不同的样式和字体大小。
I also looked at WebView
but 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);
}