簡體   English   中英

JavaFx:獲取單擊的按鈕值

[英]JavaFx: Get the clicked button value

以下代碼如何獲取按鈕的值?

String value = ((Button)event.getSource()).getText();

這是一個可以讓它更清晰的片段:

    Button button = new Button("Click Me");
    button.setOnAction(event -> {
        Object node = event.getSource(); //returns the object that generated the event
        System.out.println(node instanceof Button); //prints true. demonstrates the source is a Button
        //since the returned object is a Button you can cast it to one
        Button b = (Button)node;
        System.out.println(b.getText());//prints out Click Me
    });

上述詳細處理程序的實際簡寫形式可以是:

    button.setOnAction(event -> {
        System.out.println(((Button)event.getSource()).getText());//prints out Click Me
    });

如果處理程序用於特定按鈕,則此代碼段可能是:

    button.setOnAction(event -> {
        System.out.println(button.getText());//prints out Click Me
    });

我遇到了類似的問題,這有幫助。

private void loadWhenClicked(ActionEvent event){
    Button button = (Button) event.getSource();
    System.out.println(button.getText()); // prints out button's text
}

正如@Sedrick所提到的,event.getSource返回一個對象。 既然您知道該對象是一個Button對象,那么您將其轉換為一個對象。 (如果我沒有按照任何規則回答,我很抱歉,因為這是我的第一個回答:D)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM