我只是尝试了一个小测验,并提出了以下问题。
以下哪项陈述属实?
我选择了前两个选项,但它说错了。按钮ActionEvent和MouseEvent可以放在按钮上,但不能放在KeyEvent上。
什么是正确答案?
答案 0 :(得分:2)
所有四个陈述都是正确的,因为您可以使用一些测试代码进行验证:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class EventTest extends Application {
@Override
public void start(Stage primaryStage) {
Button button = new Button("Click Me");
TextField textField = new TextField();
button.addEventHandler(KeyEvent.KEY_PRESSED, e -> System.out.println("Key press on button"));
button.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> System.out.println("Mouse press on button"));
button.addEventHandler(ActionEvent.ACTION, e -> System.out.println("Action on button"));
textField.addEventHandler(ActionEvent.ACTION, e -> System.out.println("Action on text field"));
VBox root = new VBox(10, textField, button);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(24));
primaryStage.setScene( new Scene(root) );
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
答案 1 :(得分:1)
所有这些答案都是正确的。您只需要在它们上映射正确的事件和操作。