java 如何使用 id 在 JavaFx 中获取元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35067893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I get an element in JavaFx using an id?
提问by Rakim
I am new to FXML and I am trying to create a handler for all of the button clicks using a switch
. However, in order to do so, I need to get the elements using and id. I have tried the following but for some reason (maybe because I am doing it in the controller class and not on the main) I get a stack overflow exception.
我是 FXML 的新手,我正在尝试使用switch
. 但是,为了做到这一点,我需要使用 id 获取元素。我已经尝试了以下但出于某种原因(可能是因为我在控制器类中而不是在主类中这样做)我得到了一个堆栈溢出异常。
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");
}
}
So how will I get an element (for example a button) using it's id as a reference?
那么我将如何使用它的 id 作为参考来获取一个元素(例如一个按钮)?
The fxml block for the button is:
按钮的 fxml 块是:
<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false"
onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1"/>
回答by James_D
Use a controller class, so that you don't need to use a lookup. The FXMLLoader
will inject the fields into the controller for you. The injection is guaranteed to happen before the initialize()
method (if you have one) is called
使用控制器类,这样您就不需要使用查找。在FXMLLoader
将注入的字段到控制器为您服务。注入保证在initialize()
调用方法(如果你有的话)之前发生
public class ViewController {
@FXML
private Button exitBtn ;
@FXML
private Button openBtn ;
public void initialize() {
// initialization here, if needed...
}
@FXML
private void handleButtonClick(ActionEvent event) {
// I really don't recommend using a single handler like this,
// but it will work
if (event.getSource() == exitBtn) {
exitBtn.getScene().getWindow().hide();
} else if (event.getSource() == openBtn) {
// do open action...
}
// etc...
}
}
Specify the controller class in the root element of your FXML:
在 FXML 的根元素中指定控制器类:
<!-- imports etc... -->
<SomePane xmlns="..." fx:controller="my.package.ViewController">
<!-- ... -->
<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />
<Button fx:id="openBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Open" HBox.hgrow="NEVER" HBox.margin="$x1" />
</SomePane>
Finally, load the FXML from a class other than your controller class (maybe, but not necessarily, your Application
class) with
最后,从控制器类以外的类(可能但不一定是您的Application
类)加载 FXML
Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);
// etc...