JavaFX按钮

当用户单击按钮时,JavaFX Button类可以触发事件。Button类扩展了Labeled类,可以显示文本,图像或两者都可以。
以下代码显示了如何向Button添加单击操作侦听器。

 
  1. import javafx.application.Application;

  2. import javafx.event.ActionEvent;

  3. import javafx.event.EventHandler;

  4. import javafx.scene.Scene;

  5. import javafx.scene.control.Button;

  6. import javafx.scene.layout.StackPane;

  7. import javafx.stage.Stage;

  8. public class Main extends Application {

  9. public static void main(String[] args) {

  10. launch(args);

  11. }

  12. @Override

  13. public void start(Stage primaryStage) {

  14. primaryStage.setTitle("Hello World!");

  15. Button btn = new Button();

  16. btn.setText("Say 'Hello World'");

  17. btn.setOnAction(new EventHandler<ActionEvent>() {

  18. @Override

  19. public void handle(ActionEvent event) {

  20. System.out.println("Hello World!");

  21. }

  22. });

  23. StackPane root = new StackPane();

  24. root.getChildren().add(btn);

  25. primaryStage.setScene(new Scene(root, 300, 250));

  26. primaryStage.show();

  27. }

  28. }

创建按钮

我们使用以下构造函数在JavaFX中创建一个Button。
创建带有空文本标题的按钮。

Button button = new Button();

创建具有指定文本的按钮。

Button button = new Button("OK");

按钮操作

我们可以使用Button类的setOnAction方法为用户单击事件添加点击事件处理程序。

 
  1. button.setOnAction((ActionEvent e) -> {

  2. System.out.println("clicked");

  3. });

按钮鼠标事件

以下代码显示了如何处理Button的Mouse inMouse out(鼠标移入和移出)事件。

 
  1. import javafx.application.Application;

  2. import javafx.event.EventHandler;

  3. import javafx.scene.Group;

  4. import javafx.scene.Scene;

  5. import javafx.scene.control.Button;

  6. import javafx.scene.input.MouseEvent;

  7. import javafx.scene.layout.VBox;

  8. import javafx.stage.Stage;

  9. public class Main extends Application {

  10. public static void main(String[] args) {

  11. launch(args);

  12. }

  13. @Override

  14. public void start(Stage stage) {

  15. Group group = new Group();

  16. Scene scene = new Scene(group);

  17. stage.setWidth(300);

  18. stage.setHeight(190);

  19. VBox vbox = new VBox();

  20. vbox.setLayoutX(20);

  21. vbox.setLayoutY(20);

  22. final Button button1 = new Button("OK");

  23. button1.addEventHandler(MouseEvent.MOUSE_ENTERED,(e)->System.out.println("mouse entered"));

  24. button1.addEventHandler(MouseEvent.MOUSE_EXITED,(e)->System.out.println("mouse out"));

  25. vbox.getChildren().add(button1);

  26. vbox.setSpacing(10);

  27. group.getChildren().add(vbox);

  28. stage.setScene(scene);

  29. stage.show();

  30. }

  31. }

  • 15
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值