Issue
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 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?
P.S: I tried TextFlow
but it doesn't work, 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 could solve the mentioned problem.
Solution
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);
}
Answered By - James_D
Answer Checked By - Katrina (JavaFixing Volunteer)