Reputation: 29
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.
Upvotes: -1
Views: 564
Reputation: 29
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);
}}
)
));
Upvotes: -2
Reputation: 1940
Preface:
You can't.
Solution:
Use TextFlow
instead:
TextFlow flow = new TextFlow();
Text text1 = new Text("Some Text");
text1.setStyle("-fx-font-weight: bold");
Text text2 = new Text("Some Text");
text2.setStyle("-fx-font-weight: regular");
flow.getChildren().addAll(text1, text2);
Alternative solution:
You can try to use the HTMLEditor
for this.
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/web/HTMLEditor.html
Upvotes: 2