Issue
Help me with JavaFX CSS. I need to create a border width of 2 pixels:
Up pixel - #000
Down pixel - #5d5c5e
I think I need to use a linear-gradient, but I don't know how to do it.
Solution
It's not really clear what you're asking; but the standard way to put a border on something in JavaFX is to use "nested backgrounds". This technique involves creating different color backgrounds, one drawn over the other, with different insets so that you get the effect of a border.
For example, the following CSS in an external CSS file will give a four-pixel black (#000
) border around a four-pixel gray border (around the default background color defined in modena.css). (I used wider borders to make the effect clearer.)
style.css
:
.root {
-fx-background-color: #000, #5d5c5e, -fx-background ;
-fx-background-insets: 0, 4, 8 ;
}
This works by drawing a black background with no insets, and then drawing a gray background with 4 pixel insets over it (leaving four pixels of the black background visible), and finally drawing a background with the default color over the top of that, with 8 pixels insets (so four pixels of the gray border is visible).
Here's a quick test:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class BackgroundTest extends Application {
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(new StackPane(new Label("Nested backgrounds")), 400, 400);
scene.getStylesheets().add("style.css");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
which results in
This variation
.root {
-fx-background-color: #000, #5d5c5e, -fx-background ;
-fx-background-insets: 0, 4 0 0 0, 4 0 4 0 ;
}
leaves four pixels of the black background visible at the top, and four pixels of the gray background visible at the bottom:
And this has black at the top, grey at the bottom, and a linear gradient fading from black to grey down the sides:
.root {
-fx-background-color: #000, #5d5c5e, linear-gradient(to bottom, #000, #5d5c5e), -fx-background ;
-fx-background-insets: 0, 4 0 0 0, 4 0 4 0 , 4;
}
Answered By - James_D