2017-05-16 41 views
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"> 
+0

你在类中实现Initializable? – MattCom

+1

根据这篇文章,我已经做到了这一点应该工作http://stackoverflow.com/questions/34785417/javafx-fxml-controller-constructor-vs-initialize-method – Josh

回答

1

您必须FXML加载设置控制器

疗法e有两种方法可以做到这一点:

1º方式:在FXMLLoader类中设置控制器。而不是做

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

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> 
+1

尴尬,我忘了在视图中设置控制器,我想我一直盯着这个太久了。谢谢! – Josh

相关问题