【问题标题】:JavaFX Styling a Graphic-Node of a Button via CSSJavaFX 通过 CSS 为按钮的图形节点设置样式
【发布时间】:2015-10-23 10:32:11
【问题描述】:

我正在尝试重新创建我在 Swing 中使用的 LookAndFeel。

到目前为止一切正常,但我对按钮的图形节点进行样式设置失败了。

Java-代码:

Button btnAdd= new Button();
btnAdd.setGraphic(iconAdd); //iconAdd = ImageView

CSS:

.button:disabled, .button:default:disabled {
    -fx-opacity: 1.0;
    -fx-background-color: rgb(239, 239, 239);
    -fx-border-color: rgb(217, 217, 217);
}

.button:disabled > .graphic  {
    -fx-opacity: 0.1;
}

如您所见,我希望按钮在禁用时不透明(这可行!)。

我只希望图形节点,它是按钮的子节点,是透明的。

最好的问候,

强p

【问题讨论】:

    标签: java css button javafx styling


    【解决方案1】:

    按钮中的图形不会自动获取样式类graphic,所以需要添加:

    iconAdd.getStyleClass().add("graphic");
    

    SSCCE:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    
    public class ButtonGraphicCssTest extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            Button button = new Button();
            Image image = new Rectangle(20, 20, Color.CORNFLOWERBLUE).snapshot(null, null);
            ImageView imageView = new ImageView(image);
            imageView.getStyleClass().add("graphic");
            button.setGraphic(imageView);
    
            button.setOnAction(e -> button.setDisable(true));
    
            StackPane root = new StackPane(button);
            Scene scene = new Scene(root, 350, 120);
            scene.getStylesheets().add("button-graphic-disabled.css");
    
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    button-graphic-disabled.css:

    .button:disabled, .button:default:disabled {
        -fx-opacity: 1.0;
        -fx-background-color: rgb(239, 239, 239);
        -fx-border-color: rgb(217, 217, 217);
    }
    
    .button:disabled > .graphic  {
        -fx-opacity: 0.1;
    }
    

    【讨论】:

    • 我认为OP也可以使用默认的.image-view类。 .button:disabled > .image-view { -fx-opacity: 0.1; } 也应该完成这项工作。
    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 2016-02-29
    • 2011-09-17
    • 2014-09-22
    • 2012-08-24
    • 1970-01-01
    • 2017-03-25
    • 2012-02-14
    相关资源
    最近更新 更多