javafX初探(按钮)
2015-01-28 14:03
218 查看
button是为了让开发者在开发javaFX应用过程中处理点击的事件。Button类是Labeled类的扩展,他的内容可以是文本,也可以是图片,或者两者皆有。下图展示了不同效果的Button。这章节我们会学会如何创建这些Button。
]
因为Button是扩展子Labeled类的,所以一个Button实例创建后,我们可以通过setText或setGraphic来为Button设置文本或图片,就像下面的代码:
当你点击button2的时候,button2的内容会变成Accepted。
运行如下图所示:
如下图所示:
]
创建一个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实例创建后,我们可以通过setText或setGraphic来为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");
如下图所示:
相关文章推荐
- javafX初探(单选按钮)
- javafX初探(开关按钮)
- JavaFX初探与MediaPlayer(1)
- javaFX初探(选择)
- 第九回 JavaFX2.0按钮Button
- javaFX初探(部署)
- javafx之CSS初探
- javaFX初探(3D图形)
- JavaFX初探(盘状图表)
- javaFX初探(使用画布 API)
- JavaFx初探(颜色选择器)
- JavaFx初探
- JavaFX 2 初探----Eclipse下运行Ensemble程序
- JavaFX初探(时间选择器)
- javaFX初探(Shape3D)
- javafx之CSS初探
- 自绘制按钮初探一
- javaFX初探(Camera)
- JavaFx初探 fxml
- javafx TableValue 添加按钮列,以及删除列功能