javafX初探(按钮)

47 篇文章 3 订阅
46 篇文章 66 订阅

button是为了让开发者在开发javaFX应用过程中处理点击的事件。Button类是Labeled类的扩展,他的内容可以是文本,也可以是图片,或者两者皆有。下图展示了不同效果的Button。这章节我们会学会如何创建这些Button

]

创建一个button

你可以使用Button类的构造函数创建一个Button实例。代码如下:

//A button with an empty text caption.
Button button1 = new Button();
//A button with the specified text caption.
Button button2 = new Button("Accept");
//A button with the specified text caption and icon.
Image imageOk = new Image(getClass().getResourceAsStream("ok.png"));
Button button3 = new Button("Accept", new ImageView(imageOk));

因为Button是扩展子Labeled类的,所以一个Button实例创建后,我们可以通过setTextsetGraphic来为Button设置文本或图片,就像下面的代码:

Image imageDecline = new Image(getClass().getResourceAsStream("not.png"));
Button button5 = new Button();
button5.setGraphic(new ImageView(imageDecline));

添加事件

代码如下:

button2.setOnAction((ActionEvent e) -> {
    button2.setText("Accepted");
});

当你点击button2的时候,button2的内容会变成Accepted

应用效果

我们让鼠标移动到按钮上的时候,按钮显示出阴影效果,代码如下:

DropShadow shadow = new DropShadow();
//Adding the shadow when the mouse cursor is on
button3.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    button3.setEffect(shadow);
});
 
//Removing the shadow when the mouse cursor is off
button3.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    button3.setEffect(null);
});


 

运行如下图所示:

添加样式

我们使用css给按钮添加样式,前面已经提到过如何给组件添加css样式,这里就不再赘述。代码如下:

//Code added to the CSS file
.button1{
    -fx-font: 22 arial; 
    -fx-base: #b6e7c9;    
}
button1.getStyleClass().add("button1");


 

如下图所示:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值