我正在使用javaFX创建一个简单的ATM机GUI但我似乎不知道如何从按钮获取输入。例如,我创建了一个虚拟数字键盘,但我不知道如何从单击按钮获取输入。
public static void displayNumbers() {
Stage window2 = new Stage();
GridPane grid = new GridPane();
window2.setTitle("Enter Value");
Button one = new Button("1");
Button two = new Button("2");
Button three = new Button("3");
Button four = new Button("4");
Button five = new Button("5");
Button six = new Button("6");
Button seven = new Button("7");
Button eight = new Button("8");
Button nine = new Button("9");
Button zero = new Button("0");
Button enterButton = new Button("Enter");
grid.add(one, 0, 0);
grid.add(two, 1, 0);
grid.add(three, 2, 0);
grid.add(four, 0, 1);
grid.add(five, 1, 1);
grid.add(six, 2, 1);
grid.add(seven, 0, 2);
grid.add(eight, 1, 2);
grid.add(nine, 2, 2);
grid.add(zero, 1, 3);
grid.add(enterButton, 2, 4);
}
要使Button
在JavaFX中执行某些操作,您需要添加EventHandler
。例如,让我们告诉按钮one
将某些内容输出到控制台:
one.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("You just clicked Button #1!");
}
});
这可以通过JDK8 +中的lambda表达式简化:
one.setOnAction(event -> System.out.println("You just clicked Button #1!"));
如果在单击按钮时需要执行多行代码,则只需使用代码块:
one.setOnAction(event -> {
// Do lots of things
});