2
我有一個用FXML編寫的視圖的Java應用程序。我想選擇一個默認選項卡,所以當程序啓動時,第一個選項卡顯示爲選中狀態。我已經看到了最好的方法是在控制器中創建一個initialize()
方法,並用@FXML
加註。由於某些原因,該方法從未執行。代碼如下。在FXML的控制器中使用初始化方法?
MainApp.java
Controller.java@FXML
private TabPane myTabPane;
@FXML
private Tab defaultTab;
@FXML
private void initialize() {
myTabPane.getSelectionModel().select(defaultTab);
}
相關FXML的
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);
}
}
相關部分
<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">
你在類中實現Initializable? – MattCom
根據這篇文章,我已經做到了這一點應該工作http://stackoverflow.com/questions/34785417/javafx-fxml-controller-constructor-vs-initialize-method – Josh