一、创建按键控件
按钮是一个矩形控件,它显示为一个按钮,在其表面写有一个标题。通常情况下,当用户点击Button控件时(用鼠标或在触摸屏上触摸它),会发生一个动作。
要创建一个Button控件,你将使用Button类,它位于JavaFX.scene.control包中。
Button myButton = new Button("Click Me");
下面的代码将显示一个按钮和一行文字,文字属于label控件:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.geometry.Pos;
/**
A Button Demo
*/
public class ButtonDemo extends Application
{
public static void main(String[] args)
{
// Launch the application.
launch(args);
}
@Override
public void start(Stage primaryStage)
{
// Create a Label control.
Label myLabel = new Label("Click the button to see a message.");
// Create a Button control.
Button myButton = new Button("Click Me");
// Put the Label and Button in a VBox with 10 pixels of spacing.
VBox vbox = new VBox(10, myLabel, myButton);
// Create a Scene with the VBox as its root node.
Scene scene = new Scene(vbox, 300, 100);
// Set the scene's alignment to center.
vbox.setAlignment(Pos.CENTER);
// Add the Scene to the Stage.
primaryStage.setScene(scene);
// Set the stage title.
primaryStage.setTitle("Button Demo");
// Show the window.
primaryStage.show();
}
}
二、处理事件
(1)处理事件的格式
事件是在程序运行时发生的动作。例如,每当用户点击一个 按钮控件,就会有一个事件发生。当一个事件发生时,负责该事件的控件创建 一个事件对象,其中包含关于该事件的信息。创建该事件对象的GUI控件被称为 被称为事件源event source。
事件对象是Event类(来自javafx.event包)的实例,或其子类之一。当一个Button控件被点击时,一个ActionEvent类(Event类的一个子类)的对象被创建,它也在javafx.event包中。
当一个event实例被创建时,我们应该连接到相应的event handler去处理这个事件,这个过程被称为event firing。