当用户单击按钮时,JavaFX Button类可以触发事件。Button类扩展了Labeled类,可以显示文本,图像或两者都可以。
以下代码显示了如何向Button添加单击操作侦听器。
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
上面的代码生成以下结果。
创建按钮
我们使用以下构造函数在JavaFX中创建一个Button。
创建带有空文本标题的按钮。
Button button = new Button();
创建具有指定文本的按钮。
Button button = new Button("OK");</