我想为每个fxml设置一个Controller。这些控制器应该能够互动,但我总是NullPointerException
。我有一个带有Button
的fxml和一个带有TextField
的fxml。如果我按下Button
,则应添加TextField
。
我已经减少了一点代码。我知道很多次都会问这些问题,但对我来说没什么用。
这是我的代码:
LogStage.fxml
的控制器。这是我要设置文本的TextArea
。
public class LogController{
@FXML private TextArea logTextAreaFx;
public void handlelogTextAreaFX(ActionEvent event, String text){
logTextAreaFx.appendText(text);
}
}
MainStage.fxml
的控制器。主窗口,Button
,如果激活,则应设置TextArea
。
public class MainController{
@FXML LogController logController;
public void handleChatConsoleButton(ActionEvent event){
logController.handlelogTextAreaFX(event, "test");
}
}
LogStage.fxml:
<VBox prefWidth="500" prefHeight="300" id="logView" fx:controller="LogController" xmlns:fx="http://javafx.com/fxml" >
<TextArea text="-------- Log ---------" id="logTextArea" fx:id="logTextAreaFx"></TextArea>
</VBox>
MainStage.fxml:
<VBox minHeight="520" minWidth="1280" fx:controller="MainController" xmlns:fx="http://javafx.com/fxml">
<Button text="test Button" onAction="#handleChatConsoleButton"></Button>
</VBox>
主控制器。这些Controller应设置所有Controller并实例化并启动GameView
。
public class ClientController {
private ClientView clientView;
@FXML private MainController mainController;
@FXML private LogController logController;
public ClientController(){
this.clientView = new ClientView();
}
public void showView(){
this.clientView.startView();
}
public void setText(String text){
logController.handlelogTextAreaFX(null, "hello world");
}
}
这些类启动整个应用程序。
public class GameMain {
static ClientController controller;
public static void main(String[] args){
controller = new ClientController();
controller.showView();
}
}
ClientView设置所有框并启动fxml。
public class ClientView extends Application{
VBox root = new VBox();
VBox mainStage;
public void startView(){
launch();
}
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(root);
loadMainStage();
loadLogStage();
primaryStage.setScene(scene);
primaryStage.show();
}
@FXML Pane MainStage;
public void loadMainStage(){
mainStage = new VBox();
try {
mainStage = FXMLLoader.load(getClass().getClassLoader().getResource("MainStage.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
root.getChildren().add(mainStage);
}
@FXML VBox LogStage;
public void loadLogStage(){
//ClientController controller = new ClientController();
FXMLLoader loader = new FXMLLoader();
Pane root = new Pane();
Scene chatScene = new Scene(root);
Stage stage = new Stage();
stage.setTitle("Log View");
stage.setScene(chatScene);
stage.setResizable(true);
try {
//loader.setController(controller);
LogStage = loader.load(getClass().getClassLoader().getResource("LogStage.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
root.getChildren().add(LogStage);
stage.show();
}
}