JavaFX中event.getSource()不符合预期的问题求助
JavaFX按钮点击无响应的解决方法
你的问题核心在于错误地将Button对象引用和字符串"btn"进行比较:event.getSource()返回的是创建的Button实例本身,而不是变量名"btn",用==比较对象引用和字符串永远不会相等,所以点击逻辑不会触发。
下面是几种可行的解决方法:
方法一:直接比较对象引用
将Button变量提升为类的成员变量,让handle方法能直接访问到它,通过对象引用来判断事件源:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.scene.layout.StackPane; import javafx.event.ActionEvent; import javafx.event.EventHandler; public class HelloWorld extends Application implements EventHandler<ActionEvent> { // 将Button改为类成员变量 private Button btn; public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { btn = new Button("Write"); btn.setOnAction(this); StackPane root = new StackPane(); root.getChildren().add(btn); Scene sc = new Scene(root, 200, 100); primaryStage.setScene(sc); primaryStage.show(); } @Override public void handle(ActionEvent event){ System.out.println(event.getSource()); // 直接比较对象引用 if(event.getSource() == btn){ System.out.println("Hello World"); } } }
方法二:通过按钮ID判断
给按钮设置唯一ID,在事件处理中先将事件源转为Button类型,再获取ID进行比较(注意用equals而非==比较字符串):
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.scene.layout.StackPane; import javafx.event.ActionEvent; import javafx.event.EventHandler; public class HelloWorld extends Application implements EventHandler<ActionEvent> { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { Button btn = new Button("Write"); // 设置按钮ID btn.setId("btn"); btn.setOnAction(this); StackPane root = new StackPane(); root.getChildren().add(btn); Scene sc = new Scene(root, 200, 100); primaryStage.setScene(sc); primaryStage.show(); } @Override public void handle(ActionEvent event){ System.out.println(event.getSource()); // 转为Button后获取ID,用equals比较字符串 if("btn".equals(((Button)event.getSource()).getId())){ System.out.println("Hello World"); } } }
方法三:使用Lambda表达式简化事件处理
如果不需要处理多个组件的事件,直接用Lambda表达式绑定事件逻辑,无需判断事件源:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.scene.layout.StackPane; public class HelloWorld extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { Button btn = new Button("Write"); // 直接用Lambda写点击逻辑 btn.setOnAction(e -> System.out.println("Hello World")); StackPane root = new StackPane(); root.getChildren().add(btn); Scene sc = new Scene(root, 200, 100); primaryStage.setScene(sc); primaryStage.show(); } }
内容的提问来源于stack exchange,提问作者rado_rud
相关产品推荐
相关产品推荐

