Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying CSS file to JavaFX WebView

I am trying to apply a CSS file to a JavaFX WebView object. From what I've read, this should do the trick, but evidently I'm missing something because the WebView displays without any styling.

package net.snortum.play;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class WebviewCssPlay extends Application {

    @Override
    public void start(Stage stage) {
        stage.setTitle("CSS Styling Test");
        stage.setWidth(300);
        stage.setHeight(200);

        WebView browser = new WebView();
        WebEngine webEngine = browser.getEngine();
        webEngine.loadContent("<html><body><h1>Hello!</h1>This is a <b>test</b></body></html>");

        VBox root = new VBox(); 
        root.getChildren().addAll(browser);
        root.getStyleClass().add("browser");
        Scene scene = new Scene(root);
        stage.setScene(scene);
        scene.getStylesheets().add("/net/snortum/play/web_view.css");
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

My CSS file looks like this:

.browser {
    -fx-background-color: #00ff80;
    -fx-font-family: Arial, Helvetica, san-serif;
}
like image 279
ksnortum Avatar asked Sep 25 '15 13:09

ksnortum


People also ask

How do I use CSS in SceneBuilder?

In the SceneBuilder view, click on the AnchorPane that was added first. In the Properties tab, under the 'JavaFX CSS' section, click on the 'Stylesheets' option. Select the CSS file, and that's it.

Can you use HTML in JavaFX?

With the JavaFX HTMLEditor control, you can edit text and set the initial content. In addition, you can obtain the entered and edited text in HTML format.

What is WebView in JavaFX?

WebView is a Node that manages a WebEngine and displays its content. The associated WebEngine is created automatically at construction time and cannot be changed afterwards. WebView handles mouse and some keyboard events, and manages scrolling automatically, so there's no need to put it into a ScrollPane .


1 Answers

James_D already explained in his answer how to convert "JavaFx CSS" to "HTML CSS", but it may be more convenient to use WebEngine.setUserStylesheetLocation to set a stylesheet that contains the CSS:

webEngine.setUserStyleSheetLocation(getClass().getResource("style.css").toString());

style.css contains the css code:

body {
    background-color: #00ff80; 
    font-family: Arial, Helvetica, sans-serif;
}
like image 107
fabian Avatar answered Sep 20 '22 11:09

fabian