Folder structure
`-src/main/
|-java/
| `-sample/javafx/
| `-Main.java
|
`-resources/
|-main.fxml
`-main.css
main.css
.label {
-fx-font-size: 25pt;
-fx-text-fill: yellow;
-fx-underline: true;
-fx-padding: 10px;
-fx-background-color: skyblue;
-fx-font-family: consolas;
}
Main.java
package sample.javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/main.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<Label stylesheets="main.css" text="Style Sheet" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" />
Execution result
The style sheet is reflected properly.
** When viewed in Scene Budiler **
The style sheet settings are not reflected.
main.fxml
<Label stylesheets="main.css" ... />
--To specify a CSS file for a node Specify the path of the CSS file in the stylesheets
attribute
--This path will be ** relative to the root of the classpath **
getStyleSheets() | Scene (JavaFX 8)
The URL is a hierarchical URI in the form [scheme:] [// authority] [path]. If the URL does not have a [scheme:] component, the URL is considered to be the [path] component only. ** All "/" characters before [path] are ignored and [path] is treated as a relative path to the root of the application's classpath. ** **
--That is, at runtime you can find main.css
from the root of the classpath so the style is applied correctly
--But when viewed in Scene Builder, the style is not applied because main.css
cannot be found in the Scene Builder classpath.
――In this case, the merit of creating a screen graphically with Scene Builder has been lost.
main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<Label stylesheets="@main.css" text="Style Sheet" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" />
Execution result
** When viewed in Scene Budiler **
The style is also applied when viewed in Scene Builder.
main.fxml
<Label stylesheets="@main.css" ... />
--Specify the path specification of stylesheets
to start with@
--Then, this path will be treated as ** relative to the fxml file **
Location resolution|Overview of FXML| JavaFX 8.0
** The location resolution operator (represented by the
@
prefix to the attribute value) ** makes the attribute value a ** relative location relative to the current file, rather than a simple string. Used to specify ** what needs to be processed.
--As a result, you can find main.css
even from the viewpoint of Scene Builder, and the style will be applied.
Recommended Posts