当两个按钮具有相同的onAction方法时,如何检查哪个按钮(在fxml中)调用了controller.java中的函数



如果一个fxml文件中有多个按钮,使用sam-onAction方法,如何检查哪个按钮调用了controller.java文件中的方法。

Fxml代码类似于

<Button fx:id="b12", onAction="#push">
<Button fx:id="b13", onAction="#push">

Controller.java看起来像这个

@FXML
Button   b12,  b13;

我想写一个函数,这样如果它被第一个按钮调用,那么它的id必须打印出来,否则就是第二个id。

正如Slaw在他们的评论中提到的,您希望使用EventObject.getSource()方法来确定是哪个对象触发了事件。

这里有一个简单的应用程序来演示细节。本例中有3个文件:

Main.java-只需启动应用程序

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Just loads the sample GUI
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout.fxml"));
loader.setController(new Controller());
primaryStage.setScene(new Scene(loader.load()));
primaryStage.setTitle("Event Source Sample");
primaryStage.setWidth(300);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Controller.java-提供处理与UI 交互的代码

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
public class Controller {
// Declare the controls used in the FXML file
@FXML
private Button button1;
@FXML
private Button button2;
@FXML
private Button button3;
@FXML
private Label lblSource;
// This method is called when any of the buttons in the FXML file is clicked
// The "ActionEvent" parameter includes all the details of the event that calls this method
@FXML
void handleClick(ActionEvent event) {
// Assuming only a Button will call this method, determine which button it was by retrieving the Source of
// the event.
Button sourceButton = (Button) event.getSource();
// We have the source, so let's update the label to show the text of the Button that was clicked.
lblSource.setText(sourceButton.getText());
}
}

布局.fxml-实际的fxml设计

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" spacing="10.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1">
<padding>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>
</padding>
<HBox alignment="CENTER" spacing="10.0">
<Button fx:id="button1" mnemonicParsing="false" onAction="#handleClick" text="Button 1"/>
<Button fx:id="button2" mnemonicParsing="false" onAction="#handleClick" text="Button 2"/>
<Button fx:id="button3" mnemonicParsing="false" onAction="#handleClick" text="Button 3"/>
</HBox>
<Label text="Source:"/>
<Label fx:id="lblSource"/>
</VBox>

要关注的主要代码在Controller.java类中。您将看到handleClick(ActionEvent event)方法,该方法由FXML文件中的每个Button节点调用。

当调用该方法时,它将接收一个ActionEvent对象。然后,我们可以通过调用ActionEvent.getSource()方法来确定是哪个Button创建了该事件。从那里,您可以根据源执行任何需要的处理。

最新更新