我在 FXML 文档中定义了两个对象。我希望其中一个能够对另一个具有引用(也在 FXML 中定义)。具有其他对象的对象的 FXML 元素在文档中排在第一位。当通过 javafx.fxml.FXMLLoader 加载时,该属性保持未分配状态。如果拥有另一个对象的对象排在第二位,它确实会分配该属性。有没有办法将对象引用分配给 FXML 文档中较早出现的对象的属性?
这是一个最小的完整可验证示例。引用另一个对象并且在它之前出现的对象没有分配其属性,并且在测试时它为空。它引用的对象后面的那个确实会分配其属性并打印出该对象的 toString() 。
问题.fxml:
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import test.control.*?>
<HBox xmlns:fx="http://javafx.com/fxml/1" id="pane1" prefHeight="400.0" prefWidth="600.0">
<FriendlyButton fx:id="priorObjectReference" friend="$normalButton" />
<Button fx:id="normalButton" />
<FriendlyButton fx:id="subsequentObjectReference" friend="$normalButton" />
</HBox>
FXMLIssue.java,加载 FXML 并尝试打印对象引用:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import test.control.FriendlyButton;
public class FXMLIssue extends Application {
@Override
public void start(Stage stage) {
Parent container = null;
try {
container = FXMLLoader.load(Paths.get("issue.fxml").toUri().toURL());
} catch (IOException ex) {
Logger.getLogger(FXMLIssue.class.getName()).log(Level.SEVERE, "Failed to load file.", ex);
Platform.exit();
}
FriendlyButton priorObjectReference = (FriendlyButton) container.lookup("#priorObjectReference");
System.out.println(priorObjectReference.getFriend() == null ? "priorObjectReference's friend property wasn't loaded from FXML" : "priorObjectReference's friend is: " + priorObjectReference.getFriend().toString());
FriendlyButton subsequentObjectReference = (FriendlyButton) container.lookup("#subsequentObjectReference");
System.out.println(subsequentObjectReference.getFriend() == null ? "subsequentObjectReference's friend property wasn't loaded from FXML" : "subsequentObjectReference's friend is: " + subsequentObjectReference.getFriend().toString());
Platform.exit();
}
public static void main(String[] args) {
launch(args);
}
}
FriendlyButton.java,只是一个具有引用 FXML 中另一个对象的属性的类:
package test.control;
import javafx.scene.control.Button;
public class FriendlyButton extends Button {
private Button mFriend;
public Button getFriend() {
return mFriend;
}
public void setFriend(Button friend) {
mFriend = friend;
}
}
最佳答案
<HBox xmlns:fx="http://javafx.com/fxml/1" id="pane1" prefHeight="400.0" prefWidth="600.0">
<fx:define>
<Button fx:id="normalButton" />
</fx:define>
<FriendlyButton fx:id="priorObjectReference" friend="$normalButton" />
<fx:reference source="normalButton" />
<FriendlyButton fx:id="subsequentObjectReference" friend="$normalButton" />
</HBox>
关于javafx - 如何在 FXML 中的对象元素之前创建对对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493537/