在JavaFX中,可以使用CSS样式来实现按钮悬停和按下效果。以下是一个示例代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ButtonHoverExample extends Application {
@Override
public void start(Stage primaryStage) {
Button button = new Button("按钮");
// 设置按钮的CSS样式
button.getStyleClass().add("custom-button");
StackPane root = new StackPane();
root.getChildren().add(button);
Scene scene = new Scene(root, 200, 150);
// 加载CSS样式文件
scene.getStylesheets().add(getClass().getResource("buttonStyle.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
在上面的代码中,我们创建了一个自定义样式的按钮,并将其添加到StackPane
容器中。然后,我们创建了一个Scene
对象,并将样式文件buttonStyle.css
加载到场景中。
接下来,我们需要创建buttonStyle.css
文件并定义按钮的悬停和按下效果。以下是一个示例的CSS样式代码:
.custom-button {
-fx-background-color: #4286f4;
-fx-text-fill: white;
-fx-font-size: 14px;
-fx-padding: 8px 16px;
}
.custom-button:hover {
-fx-background-color: #005cbf;
-fx-cursor: hand;
}
.custom-button:pressed {
-fx-background-color: #002d5d;
}
在上面的CSS样式代码中,我们定义了按钮的基本样式,包括背景颜色、文本颜色、字体大小和内边距。然后,我们使用:hover
伪类选择器来定义按钮的悬停效果,当鼠标悬停在按钮上时,背景颜色会变为另一种颜色,并且鼠标指针会变为手型。最后,我们使用:pressed
伪类选择器来定义按钮的按下效果,当按钮被按下时,背景颜色会变为另一种颜色。
将上述代码保存为ButtonHoverExample.java
和buttonStyle.css
文件,并运行ButtonHoverExample
类,即可看到按钮具有悬停和按下效果的效果。
上一篇:按钮悬停过渡持续时间
下一篇:按钮悬停没有任何操作