0

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

3
  • You might want to take a look at stackoverflow.com/questions/32783532/…. However as the content you are loading is not HTML, I am unsure if this will work. Commented Dec 17, 2015 at 14:54
  • Why not load HTML? With html it's a simple CSS edit. (Just asking...) Commented Dec 17, 2015 at 15:00
  • I am redirecting the standard Err to that output.txt file. Commented Dec 17, 2015 at 15:14

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing out the body syntax. my css had JavaFX css formate -fx-background-color.. which it didn't take effect.
@Moe: James_D explains this in his answer here: stackoverflow.com/a/32785852/2991525 . Unfortunately he does the code injection thing too in his code, which think is a bit ugly compared to just adding a user stylesheet.
0

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.

1 Comment

both of them are not working. maincontainer.setAttribute("style", "color: black")); setAttribute cannot find symbol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.