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;
}
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.
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.
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 .
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With