2017-10-10 34 views
0

爲了教育目的,我嘗試將熱鍵添加到我的javafx應用程序中。使用我的示例代碼,我無法通過熱鍵訪問我的標籤。使用按鈕我可以調用完全相同的方法更新我的標籤成功。通過熱鍵更新標籤時的Javafx NPE

的觀點:

<?xml version="1.0" encoding="UTF-8"?> 

<?import java.lang.*?> 
<?import java.util.*?> 
<?import javafx.scene.*?> 
<?import javafx.scene.control.*?> 
<?import javafx.scene.layout.*?> 

<AnchorPane id="AnchorPane" prefHeight="62.0" prefWidth="91.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fx.probleme.SampleViewController"> 
    <children> 
     <Label id="label" fx:id="label" layoutX="14.0" layoutY="45.0" text="Label" /> 
     <Button layoutX="20.0" layoutY="14.0" mnemonicParsing="false" onAction="#updateText" text="Button" /> 
    </children> 
</AnchorPane> 

而且控制器:

package fx.probleme; 

import javafx.application.Application; 
import javafx.fxml.FXML; 
import javafx.fxml.FXMLLoader; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.scene.control.Label; 
import javafx.scene.input.KeyCode; 
import javafx.scene.input.KeyEvent; 
import javafx.stage.Stage; 

public class SampleViewController extends Application { 

    @FXML 
    Label label; 

    @FXML 
    void updateText() { 
     label.setText(label.getText() + "+"); 
    } 

    @Override 
    public void start(Stage stage) throws Exception { 
     Parent parent = FXMLLoader.load(this.getClass().getResource("SampleView.fxml")); 
     Scene scene = new Scene(parent); 
     scene.setOnKeyPressed((final KeyEvent keyEvent) -> { 
      if (keyEvent.getCode() == KeyCode.NUMPAD0) { 
       updateText(); 
      } 
     }); 
     stage.setScene(scene); 
     stage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

回答

0

你得到NullPointerException,因爲在這個階段,Label沒有初始化,初始化在initialize完成。 首先你把你的主類和你的控制器類混合在一起,你可能想分開它們,設置一個控制器implements Initializable,然後在initialize方法中你可以調用組件的任何方法,因爲在其中註解了所有的組件由@FXML初始化。在你的情況下,在啓動方法尚未初始化。你也可能不想使用場景的方法,而不是你可以添加事件,動作到你的內容窗格,在你的情況下,到AnchorPane

我建議將控制器類與主類分開,並實現Initializable。這有助於您更好地瞭解應用程序,您可以看到組件的初始化位置,您確定要使用其方法,而無需NPE。

如果你不想做一個單獨的類(推薦),你可以在.fxml文件AnchorPane添加fx:id,那麼你可以將方法添加到onKeyPressed像你這樣的按鈕。

+0

感謝您的回答。我自己在教javafx,只知道我的'Application'類不應該是'Controller'類。你在使用前一個onKeyPressed事件的時候內容窗格也是有效的,但我仍然會分開'Controller'和'Application'以正確的方式進行操作。其他讀者:我發現這個很好的解釋爲什麼分開他們: https://stackoverflow.com/questions/33303167/javafx-can-application-class-be-the-controller-class –