setstyle+java_javafx 2和css伪类:在setStyle方法中设置悬停属性

正如您在问题中注意到的那样,从JavaFX 2.2开始,css伪类不会被公开为公共API的一部分,可用于Java代码中的样式操作.

如果要从Java代码中更改样式属性,而不使用样式表,则需要根据事件或更改列表设置样式.下面的示例中有几个选项.

import javafx.application.Application;

import javafx.beans.binding.*;

import javafx.beans.property.SimpleStringProperty;

import javafx.event.EventHandler;

import javafx.geometry.Pos;

import javafx.scene.*;

import javafx.scene.control.Button;

import javafx.scene.input.MouseEvent;

import javafx.scene.layout.*;

import javafx.stage.Stage;

/** Changing button styles on hover without a css stylesheet. */

public class ButtonBackgroundChanger extends Application {

private static final String STANDARD_BUTTON_STYLE = "-fx-background-color: #DDFFA4;";

private static final String HOVERED_BUTTON_STYLE = "-fx-background-color: #9ACD32;";

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

@Override public void start(final Stage stage) throws Exception {

Button configure = new Button("Configure");

changeBackgroundOnHoverUsingBinding(configure);

Button update = new Button("Update");

changeBackgroundOnHoverUsingEvents(update);

VBox layout = new VBox(10);

layout.setAlignment(Pos.CENTER);

layout.setStyle("-fx-padding: 10;");

layout.getChildren().addAll(configure, update);

stage.setScene(new Scene(layout));

stage.show();

}

private void changeBackgroundOnHoverUsingBinding(Node node) {

node.styleProperty().bind(

Bindings

.when(node.hoverProperty())

.then(

new SimpleStringProperty(HOVERED_BUTTON_STYLE)

)

.otherwise(

new SimpleStringProperty(STANDARD_BUTTON_STYLE)

)

);

}

public void changeBackgroundOnHoverUsingEvents(final Node node) {

node.setStyle(STANDARD_BUTTON_STYLE);

node.setOnMouseEntered(new EventHandler() {

@Override public void handle(MouseEvent mouseEvent) {

node.setStyle(HOVERED_BUTTON_STYLE);

}

});

node.setOnMouseExited(new EventHandler() {

@Override public void handle(MouseEvent mouseEvent) {

node.setStyle(STANDARD_BUTTON_STYLE);

}

});

}

}

如果颜色需要真正动态,那么我只会在代码而不是样式表中使用预定义的颜色和样式的样式表有问题,或者如果还有其他的厌恶使用css样式表.

示例程序输出(更新按钮悬停):

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值