Canvas
is a direct subclass of Node
, so it only supports the CSS properties defined for Node
. These do not include the standard ways to apply borders, such as -fx-background-color
or -fx-border-color
.
However, Node
supports the -fx-effect
property, so you could use that. Here is a "quick-and-dirty" example using inline styles (in a real app I would recommend using an external stylesheet; perhaps, depending on your requirements, subclassing Canvas
to provide the "selection" behavior):
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class CanvasCSSEffect extends Application {
@Override
public void start(Stage primaryStage) {
Canvas canvas1 = new Canvas(400, 400);
Canvas canvas2 = new Canvas(400, 400);
GraphicsContext gc1 = canvas1.getGraphicsContext2D();
gc1.setFill(Color.CORNSILK);
gc1.fillRect(0, 0, 400, 400);
GraphicsContext gc2 = canvas2.getGraphicsContext2D();
gc2.setFill(Color.ANTIQUEWHITE);
gc2.fillRect(0, 0, 400, 400);
ObjectProperty<Canvas> selectedCanvas = new SimpleObjectProperty<>();
selectedCanvas.addListener((obs, oldCanvas, newCanvas) -> {
if (oldCanvas != null) {
oldCanvas.setStyle("");
}
if (newCanvas != null) {
newCanvas.setStyle("-fx-effect: innershadow(gaussian, #039ed3, 10, 1.0, 0, 0);");
}
});
canvas1.setOnMouseClicked(e -> selectedCanvas.set(canvas1));
canvas2.setOnMouseClicked(e -> selectedCanvas.set(canvas2));
HBox root = new HBox(10, canvas1, canvas2);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}