JavaFX 通过 CSS 为按钮的图形节点设置样式

标签 java css button javafx styling

我正在尝试重新创建我在 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;
}

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

我只希望作为 Button 子节点的 Graphic-Node 是透明的。

最好的问候,

最佳答案

按钮中的图形不会自动获取样式类graphic,因此您需要添加它:

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

中南合作:

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);
    }
}

按钮图形禁用.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;
}

关于JavaFX 通过 CSS 为按钮的图形节点设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33300256/

相关文章:

java - java中的socket编程问题

html - CSS 动画不工作(以前工作)

Android 使用图层列表作为按钮选择器

css - 段落中放表情符不影响 `line-height`

javascript - 回流/重绘问题?优化太慢的应用程序

javascript - 试图通过更改其类来更改元素行为。 -.在 ("Click"上)

iphone - 使用系统图标或图像图标的自定义导航栏按钮

java - Swing 的removeAll() 是否将所有删除的元素设置为null?

java - 将 LinearLayout 的方向作为参数发送给方法 - java Android Studio

java - 无法通过拖动调整 JTable 列的大小