我想寻求有关 event.getSource() 的帮助。我已经开始学习 JavaFx,互联网上的所有教学视频都说这样做,请参阅基本代码。 但是, event.getSource() 生成的输出只是对 button(Button@4454de36[styleClass=button]'Write') 的引用,因此显然没有与 if 语句中的字符串进行比较。因此,单击 btn 不会执行任何操作。什么是有效的解决方案?
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 {
// TODO Auto-generated method stub
Button 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");
}
}
}
我尝试使用 event.getSource()。以某种方式分隔按钮的名称,但没有任何效果。输出还是一样。
视频中的代码之所以有效,是因为它不是将事件源与字符串进行比较,而是将其与按钮进行比较。
无论如何,这种方法并不是最理想的,不要编写这样的代码来实现开关或测试以在事件处理程序中查找源。
您正在按钮上设置事件处理程序,因此您已经知道该事件处理程序适用于哪个按钮,您不需要对此进行测试,也不需要为所有按钮使用一个事件处理程序,只需为每个按钮创建一个新的事件处理程序(这可以使用 lambda 表达式轻松完成。
写:
button.setOnAction(e -> doSomething());
其中
doSomething()
是执行操作时要执行的某些方法的名称。不要在低质量的教程上浪费时间。
Eden 教程很好地解释了如何处理按钮事件:
来自 eden 文章的示例代码(稍作修改):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ButtonEventExampleApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
//create Scene Graph
Button button = new Button("Press me!");
StackPane root = new StackPane(button);
Scene scene = new Scene(root, 300, 250);
//Define Button Action
Label label = new Label("Pressed!");
button.setOnAction(event ->
root.getChildren().setAll(label)
);
//Create Window
primaryStage.setTitle("Button Example App");
primaryStage.setScene(scene);
primaryStage.show();
}
}