Moe
Moe

Reputation: 1527

Set Text Color in WebView using Java and JavaFX

Using JavaFX I created a button in a Scene that opens output.txt file. Now, the issue when I try to open the txt file from the webView I see the display color is light gray. How can I force the color to be black or anything else.

WebView web = new WebView();
 Scene helpScene = new Scene(web, 800, 750);
 Stage helpStage = new Stage();
 helpStage.setScene(helpScene);
 File readMe = new File("output.txt");
 web.getEngine().load(readMe.toURI().toString());
 helpStage.show();

Here is a screenshot of how the text looks like. enter image description here

Upvotes: 0

Views: 741

Answers (2)

fabian
fabian

Reputation: 82451

Create a stylesheet and add it as user stylesheet to the WebEngine.

E.g. to color the text blue:

body {
    color: blue;
}

Assuming the relative location to the class that contains the code is style.css you can add the stylesheet like this:

web.getEngine().setUserStyleSheetLocation(getClass().getResource("style.css").toString());

Upvotes: 2

Lakatos Gyula
Lakatos Gyula

Reputation: 4150

You can always inject a css into the WebView. Try something like this:

webView.getEngine().getLoadWorker().stateProperty().addListener(
    new ChangeListener<State>() {
        @Override
        public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
            if (newState == State.SUCCEEDED) {
                webView.requestFocus();

                //Maybe this
                //webView.getEngine().setUserStyleSheetLocation(getClass().getResource("style.css").toExternalForm());

                //Or this
                Element maincontainer = (Element) webView.getEngine().executeScript("document.getElementsByTagName('body')");
                maincontainer.setAttribute("style", "color: black"));
            }
        }
    });

It's untested so be aware of that.

Upvotes: 0

Related Questions