首页 > 解决方案 > 如何从 javafx 控制器而不是 CSS 向按钮添加悬停属性

问题描述

假设我在 JavaFX CSS 中有一个这样定义的切换按钮。

.btn:hover{
    -fx-background-color: #ffffff;
}

我在 FlowPane 中有几个切换按钮,但它们都需要具有在控制器中确定的不同颜色。如何从控制器更改此悬停颜色?

标签: javafxjavafx-css

解决方案


在 CSS 文件中定义查找颜色:

.root {
    button-hover-color: #ffffff ;
}
.button:hover {
    -fx-background-color: button-hover-color ;
}

请注意,默认 CSS 实际上设置了-fx-color属性,背景是从该属性派生的。因此,如果您想设置它以使其以默认方式运行而无需进一步修改,请尝试

.root {
    button-hover-color: -fx-hover-base ;
}
.button:hover {
    -fx-color: button-hover-color ;
}

然后在您的控制器类中,您可以更改按钮上的查找颜色(或在任何容器上将其应用于容器中的所有按钮):

public class MyController {
    @FXML
    private Button button ;

    public void initialize() {
        button.setStyle("button-hover-color: red ;");
    }
}

这是一个完整的示例,使用上面的第二个 CSS 文件作为style.css.

主要.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<VBox alignment="CENTER" spacing="20.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.jamesd.examples.hover.Controller">
    <Button fx:id="firstButton" text="First"/>
    <Button fx:id="secondButton" text="Second"/>
    <Button fx:id="thirdButton" text="Third"/>
</VBox>

控制器.java:

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class Controller {

    @FXML
    private Button firstButton ;
    @FXML
    private Button secondButton ;
    @FXML
    private Button thirdButton ;

    public void initialize() {
        firstButton.setStyle("button-hover-color: #7fc97f;");
        secondButton.setStyle("button-hover-color: #beaed4;");
        thirdButton.setStyle("button-hover-color: #fdc086;");
    }
}

和 App.java:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class App extends Application {

    @Override
    public void start(Stage stage) throws IOException {
        Scene scene = new Scene(FXMLLoader.load(getClass().getResource("Main.fxml")), 640, 480);
        scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }


    public static void main(String[] args) {
        launch();
    }

}

请注意,您还可以直接在 FXML 中配置按钮:

<Button fx:id="firstButton" text="First" style="button-hover-color: #7fc97f;"/>

等等


推荐阅读