繁体   English   中英

检查使用JavaFX单击哪个Button对象

[英]Check which Button object is clicked using JavaFX

我正在制作一个基本的计算器,但我不确定如何检查是否已点击某个Button 我想使用一个Button对象数组,然后检查单击的按钮是否与数组中的按钮对象匹配。 我的代码如下。

Button[] digitButtons = { bt0, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9 };

for (int index = 0; index < 9; index++) {
    int position = -1;
    if (buttonClicked == digitButtons[index]) {
        position = index;
        break;
    }
}

这是一个例子:

public class Main extends Application {
    private int lastClickedIndex = -1; 

    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root, 400, 400);


            Button[] digitButtons = new Button[10];
            for(int i = 0; i < 10; i++) {
                final int buttonInd = i;
                digitButtons[i] = new Button(Integer.toString(i));
                digitButtons[i].setOnAction(e -> {
                    System.out.println("Button pressed " + ((Button) e.getSource()).getText());
                    lastClickedIndex = buttonInd;
                });
            }

            root.setCenter(new HBox(digitButtons));

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

注意:由于Button被精确指定为事件源,因此无需获取索引: e.getSource()

一个简单的方式


FXML

创建2个按钮调用B1B2 ,并为每个按钮添加fx:id

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="ask.FXMLDocumentController">
    <children>
        <Button fx:id="B1" layoutX="94.0" layoutY="106.0" text="B1" />
        <Button fx:id="B2" layoutX="195.0" layoutY="106.0" text="B2" />
    </children>
</AnchorPane>

调节器

使用setOnAction方法更改值

按钮名称必须与fx:id设置相同

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;

public class FXMLDocumentController implements Initializable {

    @FXML Button B1;
    @FXML Button B2;
    int whichIsLastClicked = -1;

    public void initialize(URL url, ResourceBundle rb) 
    {
        B1.setOnAction(e->whichIsLastClicked=1);
        B2.setOnAction(e->whichIsLastClicked=2);
    }    

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM