我有一个 Java 应用程序,其 View 是用 FXML 编写的。我想选择一个默认选项卡,因此当程序启动时,第一个选项卡显示为选定状态。我发现最好的方法是在 Controller 中创建一个 initialize()
方法,并使用应该加载的 @FXML
对其进行注释。但由于某种原因,该方法从未被执行。代码如下。
MainApp.java
import controller.Controller;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.*;
public class MainApp extends Application{
private String osName;
private Parent root;
@Override
public void start(Stage primaryStage) throws Exception {
osName = System.getProperty("os.name").toString();
if(osName.charAt(0) == 'W' || osName.charAt(0) == 'w') {
root = FXMLLoader.load(getClass().getResource("/view/WindowsView.fxml"));
} else if(osName.charAt(0) == 'M' || osName.charAt(0) == 'm'){
root = FXMLLoader.load(getClass().getResource("/view/MacView.fxml"));
}else{
root = null;
}
if(root != null){
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("main.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}else{
JOptionPane.showMessageDialog(null, "Could not find OS, exiting program.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
public static void main(String[] args){
launch(args);
}
}
Controller.java的相关部分
@FXML
private TabPane myTabPane;
@FXML
private Tab defaultTab;
@FXML
private void initialize() {
myTabPane.getSelectionModel().select(defaultTab);
}
相关FXML
<TabPane fx:id="myTabPane" cache="true" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" nodeOrientation="RIGHT_TO_LEFT" prefHeight="400.0" prefWidth="600.0" tabClosingPolicy="UNAVAILABLE" tabMinHeight="25.0" tabMinWidth="100.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
<Tab id="scanscleanup" fx:id="defaultTab" text="Scans/Cleanup">
最佳答案
您必须在FXML加载中设置 Controller
有两种方法可以做到这一点:
1°方式:在FXMLLoader类中设置 Controller 。而不是这样做
FXMLLoader.load(getClass().getResource("/view/WindowsView.fxml"));
这样做
FXMLLoader loader = new FXMLLoader();
loader.setController(new Controller());
loader.setLocation(getClass().getResource("/view/WindowsView.fxml"));
root = loader.load();
2°方式:在FXML中设置 Controller
WindowsView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.TextField?>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.Controller">
<Label text="This is my example in StackOverflow"/>
</AnchorPane>
关于java - 在 FXML 的 Controller 中使用初始化方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010909/