创建按钮
Button有三种基本形式,分别为:
空按钮
带文字的按钮
带图片及文字的按钮
可以看到Button的三种基本形式跟Label的非常相似,事实上,Button就是间接继承自Label的父类Labeled的,所以可以简单的把Button看做一个天生能处理鼠标点击事件的Label。
空按钮
Button button1 = new Button();
带文字的按钮
Button button2 = new Button("Accept");
带图标及文字的按钮
Image imageOk = new Image(getClass().getResourceAsStream("ok.png"));
Button button3 = new Button("Accept", new ImageView(imageOk));
改变图标与文字的相对位置一样是通过setContentDisplay()方法来完成。
改变按钮组成成分
由于Button继承自Labeled,所以改变成分的方式也与之前看到的Label相同。
The setText(String text) – 指定文字
setGraphic(Node graphic)– 指定图标
Image imageDecline = new Image(getClass().getResourceAsStream("not.png"));
Button button5 = new Button();
button5.setGraphic(new ImageView(imageDecline));
图标不必须是一个外部图片文件,还可以是图形元素,比如说添加一个圆形(javafx.scene.shape.circle.Circle)
Button button = new Button();
button.setGraphic(new Circle(20)); //半径为20像素的圆形,默认填充颜色为黑色
效果:
非常的丑。ok,接下来看如何为按钮绑定点击动作。
处理点击按钮动作
当鼠标点击按钮时,按钮内部会产生一个事件,通过setOnAction()可以设置在单击事件产生后要做的事情:
button2.setOnAction((ActionEvent e) -> {
label.setText("Accepted");
});
处理其他事件
如果要让按钮可以监听处理其他事件,除了使用上一篇文章介绍的setOn...方法,还可以使用同样定义在Node类中的addEventHandler(final EventType<T> eventType,
final EventHandler<? super T> eventHandler)方法,这个方法允许绑定任何继承自javafx.event.Event类的事件,这意味着我们可以监听处理自定义事件。此方法的第一个参数指定事件类型,如按下键盘上某一个键的事件类型为KeyEvent.KEY_PRESSED;第二个参数指定事件处理动作。【应用视觉效果】小节有处理鼠标移入移出事件的例子可供参考。
应用视觉效果
可以为按钮应用各种视觉效果,常见的效果有阴影,光照等等。下面看一个当鼠标移入范围时产生一圈阴影的例子:
DropShadow shadow = new DropShadow();
//Adding the shadow when the mouse cursor is on
button.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
button.setEffect(shadow);
});
//Removing the shadow when the mouse cursor is off
button.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
button.setEffect(null);
});
效果: