我是FXML的新手,我正嘗試使用switch
爲所有按鈕點擊創建一個處理程序。但是,爲了這樣做,我需要使用和id來獲取元素。我嘗試了以下,但由於某種原因(也許是因爲我在控制器類而不是主要),我得到一個堆棧溢出異常。如何使用ID在JavaFx中獲取元素?
public class ViewController {
public Button exitBtn;
public ViewController() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("mainWindow.fxml"));
Scene scene = new Scene(root);
exitBtn = (Button) scene.lookup("#exitBtn");
}
}
那麼我將如何讓使用它的ID作爲參考的元素(例如按鈕)?
該按鈕的FXML塊是:
<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />
使用[控制器類](http://docs.oracle.com/javase/8/javafx/api/類比你的控制器類(可能,但不一定,你
Application
類)其他javafx/fxml/doc-files/introduction_to_fxml.html#controllers) –你在混合'id'和'fx:id'標籤。 'lookup'基於'id'。 'fx:id'用於注入控制器類。 – Itai
@James_D這是一個控制器類 – Rakim