Button有三种基本形式,分别为:java
空按钮spa
带文字的按钮code
带图片及文字的按钮继承
能够看到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相同。ci
The setText(String text) – 指定文字
get
setGraphic(Node graphic)– 指定图标
it
Image imageDecline = new Image(getClass().getResourceAsStream("not.png")); Button button5 = new Button(); button5.setGraphic(new ImageView(imageDecline));
图标没必要须是一个外部图片文件,还能够是图形元素,好比说添加一个圆形(javafx.scene.shape.circle.Circle)io
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); });
效果: