Description of \"Figure 3-1 Types of Buttons\"
创建按钮
在JavaFX应用中有三种Button类的构造方法创建 Button 控件,见Example 3-1 . Example 3-1 Creating a 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\
由于 Button 类继承了Labeled 类,所以你可以用下面的方法为没有图标和标题的按钮指定内容。
setText(String text) 方法–为按钮指定标题 The setGraphic(Node graphic) 方法– 指定图标
Example 3-2展示了如何创建无标题的图标按钮。 Example 3-2 Adding an Icon to a Button
Image imageDecline = new Image(getClass().getResourceAsStream(\"not.png\")); Button button5 = new Button(); button5.setGraphic(new ImageView(imageDecline)); 将代码块加入应用后产生的效果如 Figure 3-2 . Figure 3-2 Button with Icon
Description of \"Figure 3-2 Button with Icon\"
Example 3-2 和Figure 3-2 中的图标是一个ImageView 对象。不过,也可以使用其他的图形对象,如javafx.scene.shape 包中的各种形状。当按钮同时具有文本和图形内容时,可以使用setGraphicTextGap方法在二者之间设置间隙。
Button类的默认皮肤有如下的视觉区别。Figure 3-3 用一个图标按钮展示了这种区别。 Figure 3-3 Button States
Description of \"Figure 3-3 Button States\"
分配行为
按钮的最基本功能就是在按下时处理行为。用Button 类的setOnAction方法定义用户按下按钮时会发生什么。 Example 3-3 是为button2定义行为的代码块。 Example 3-3 Defining an Action for a Button
button2.setOnAction(new EventHandler ActionEvent 是由EventHandler处理的一种事件类型。EventHandler对象提供了handle方法处理按钮触发的行为。Example 3-3展示了如何重写handle 方法,所以当用户按下button2 时label 的标题就变为了\"Accepted.\" 可以用Button 类设置任意多你需要引起特定行为或应用视效的事件处理方法。 应用特效 由于 Button类继承了Node 类,你可以使用javafx.scene.effect包中的任意特效改善按钮的视觉呈现。在Example 3-4中,当onMouseEntered 事件发生时为button3应用了DropShadow效果。 Example 3-4 Applying the DropShadow Effect DropShadow shadow = new DropShadow(); //Adding the shadow when the mouse cursor is on button3.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler EventHandler Description of \"Figure 3-4 Button with Drop Shadow\" 为Button造型 下面对按钮的美化工作是通过Skin 类定义的CSS风格来实现的。在JavaFX 2.0 中使用CSS和在HTML中使用很类似,因为它们都基于相同的CSS规范。 可以先定义一个单独的CSS文件,然后用 setStyleClass 方法在应用中使用它。这个方法也是继承自Node类的且对全部UI控件可用。当然你也可以使用setStyle方法直接在代码中定义按钮的风格。Example 3-5 和Figure 3-4演示了后面这种方法。 Example 3-5 Styling a Button button1.setStyle(\"-fx-font: 22 arial; -fx-base: #b6e7c9;\"); -fx-font属性为button1设置了字体大小,-fx-base属性改变了按钮默认的颜色。这样,button1就具有了浅绿色和大字体,如Figure 3-5 . Figure 3-5 Button Styled with CSS Description of \"Figure 3-5 Button Styled with CSS \" 因篇幅问题不能全部显示,请点此查看更多更全内容