想要只将投影添加到Grid面板的边框而不是内部子元素
这是屏幕上显示效果的图像。
使用StackPane并将您的GridPane放置在其中。
使用CSS为StackPane设置样式以应用背景颜色、插入和阴影效果。
请参见Drop Shadow in an undecorated Pane! JAVAFX,了解一些示例CSS。
这里是一个小型独立的示例应用程序(在OS X 10.9上使用Java 8b120),演示了该效果:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Shadowed extends Application {
public static void main(String[] args) { launch(args); }
@Override
public void start(Stage stage) throws Exception {
Label clear = new Label("Clear, with no shadow");
StackPane shadowedPane = new StackPane(clear);
shadowedPane.setStyle(
"-fx-background-color: palegreen; " +
"-fx-background-insets: 10; " +
"-fx-background-radius: 10; " +
"-fx-effect: dropshadow(three-pass-box, purple, 10, 0, 0, 0);"
);
shadowedPane.setPrefSize(200, 50);
stage.setScene(new Scene(shadowedPane));
stage.show();
}
}
回答额外的问题
CSS是唯一的选择吗?
不,也可以通过代码来实现,使用DropShadow效果。
shadowedPane.setEffect(new DropShadow(10, Color.PURPLE));
为什么这能起作用呢?因为设置背景色为节点提供了一个清晰的边界,应用阴影效果时也是以此为基础。import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Shadowed extends Application {
public static void main(String[] args) { launch(args); }
@Override
public void start(Stage stage) throws Exception {
// setUserAgentStylesheet(STYLESHEET_CASPIAN);
Label clear = new Label("Clear, with no shadow");
GridPane shadowedPane = new GridPane();
shadowedPane.add(clear, 0, 0);
GridPane.setHalignment(clear, HPos.CENTER);
GridPane.setValignment(clear, VPos.CENTER);
GridPane.setHgrow(clear, Priority.ALWAYS);
GridPane.setVgrow(clear, Priority.ALWAYS);
shadowedPane.setStyle(
// "-fx-background-color: transparent; " +
// "-fx-background-color: palegreen; " +
"-fx-background-insets: 10; " +
"-fx-background-radius: 10; "
);
shadowedPane.setPrefSize(200, 50);
shadowedPane.setEffect(new DropShadow(10, Color.PURPLE));
stage.setScene(new Scene(shadowedPane));
stage.show();
}
}
// explicitly transparent
-fx-background-color: transparent;
或者
// effectively transparent
-fx-background-color: #FFFFFF00;
DropShadow
在应用于根节点或嵌套容器时会有不同的效果? - Itai