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

Moe
  • 1,427
  • 4
  • 34
  • 54
  • You might want to take a look at http://stackoverflow.com/questions/32783532/applying-css-file-to-javafx-webview. However as the content you are loading is not HTML, I am unsure if this will work. – hotzst Dec 17 '15 at 14:54
  • Why not load HTML? With html it's a simple CSS edit. (Just asking...) – Lakatos Gyula Dec 17 '15 at 15:00
  • I am redirecting the standard Err to that output.txt file. – Moe Dec 17 '15 at 15:14

2 Answers2

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());
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Thanks for pointing out the body syntax. my css had JavaFX css formate -fx-background-color.. which it didn't take effect. – Moe Dec 18 '15 at 10:08
  • @Moe: James_D explains this in his answer here: http://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. – fabian Dec 18 '15 at 10:17
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.

Lakatos Gyula
  • 3,949
  • 7
  • 35
  • 56
  • both of them are not working. maincontainer.setAttribute("style", "color: black")); setAttribute cannot find symbol – Moe Dec 17 '15 at 15:35