2017-02-28 45 views
0

我有一個描述我的GUI的fxml。我想改變gui的文本,並在任何地方按任何按鍵啓動任務。使用fxml在Javafx中添加事件監聽器到mainScene

FXML

<Text fx:id="barcodeText"/> 

控制器

@FXML 
    Text barcodeText; 

    public void start(Stage primaryStage) throws IOException { 
     this.primaryStage=primaryStage; 
     Scene mainScene =new Scene(root); 
     primaryStage.setScene(mainScene); 
     primaryStage.setResizable(false); 
     primaryStage.show(); 
     Parent root = FXMLLoader.load(getClass().getResource("/view/foo.fxml")); 
     mainScene.addEventHandler(KeyEvent.KEY_PRESSED,new KeyboardEventHandler(){ 
       @Override 
       public void handle(KeyEvent event) { 
        barcodeText.setText("foo"); 
       } 
     }); 

這給了我NullPointerException(JavaFX應用程序線程內)的barcodeText指針,當我觸發事件。

我做錯了什麼?

我看了看用不用FXML這種方法的例子,我必須使用註釋來定義處理器?我在哪裏可以在fxml中放置「onAction」場景?

+0

'@FXML Text textBox;'或'@FXML Text barcodeText;'? – pzaenger

+1

FXML加載器在* controller *中初始化'@ FXML'-annotated字段,而不是在調用'start'的'Application'類的實例中。所以'barcodeText'(或者'textBox',或者其他你真正稱之爲的)在'Application'實例中將是空的。 –

+0

@pzaenger對不起,這是一個錯字 –

回答

2

(旁白:它看起來像你正在嘗試使用同一類的控制器,併爲應用Don't do that.。)

定義在控制器類的方法來設置條形碼文本:

public void setBarcodeText(String barcode) { 
    barcodeText.setText(barcode); 
} 

然後調用該方法從您的處理程序:

FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/foo.fxml")); 
Parent root = loader.load(); 

MyControllerClass controller = loader.getController(); 

Scene mainScene = new Scene(root); 
mainScene.addEventHandler(KeyEvent.KEY_PRESSED, new KeyboardEventHandler(){ 
     @Override 
     public void handle(KeyEvent event) { 
      controller.setBarcodeText("foo"); 
     } 
}); 

顯然,與控制器的實際名稱替換MyControllerClass類。

+0

謝謝,解決了我的問題。我也會從應用程序中提取和分離控制器。 –