I am making a JavaFX forums app, and want to know how to style specific portions of a Text Area, just like in any document program.
How to make a JavaFX Text Area with bold, italic, underlined, etc
159 views Asked by The Typholorian At
2
There are 2 answers
4
On
Requires javafx.web
Editor:
package net.typho.pnegative.launcher.fx;
import javafx.scene.web.HTMLEditor;
import java.util.function.Consumer;
public class TTextArea extends HTMLEditor {
public TTextArea(Consumer<String> out) {
super();
setOnKeyReleased(event -> out.accept(getHtmlText()));
}
public TTextArea(Consumer<String> out, String id) {
this(out);
getStyleClass().add(id);
}
}
Viewer:
package net.typho.pnegative.launcher.fx;
import javafx.application.Platform;
import javafx.scene.control.ScrollPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import java.util.function.Supplier;
public class TTextViewer extends ScrollPane {
private final WebView view;
private final WebEngine engine;
public TTextViewer() {
view = new WebView();
engine = view.getEngine();
setHbarPolicy(javafx.scene.control.ScrollPane.ScrollBarPolicy.NEVER);
setVbarPolicy(javafx.scene.control.ScrollPane.ScrollBarPolicy.NEVER);
setContent(view);
}
public TTextViewer(String id) {
this();
getStyleClass().add(id);
}
public void textListener(Supplier<String> html, int wait) {
new Thread(() -> {
while (true) {
Platform.runLater(() -> engine.loadContent(html.get()));
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
Usage:
AtomicReference<String> data = new AtomicReference<>();
stage.setScene(new Scene(
new FlowPane(
new TTextArea(data::set, "textField"),
new TTextViewer("textViewer"){{
textListener(data::get, 10);
}}
)
));
Preface:
You can't.
Solution:
Use
TextFlowinstead:Alternative solution:
You can try to use the
HTMLEditorfor this.https://docs.oracle.com/javase/8/javafx/api/javafx/scene/web/HTMLEditor.html