简体   繁体   中英

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. 在此处输入图片说明

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

Eg 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());

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM