JavaFX Starter:从主窗口修改其他窗口上的标签文本

时间:2016-10-25 20:17:44

标签: java javafx window label fxml

我是一个带有Scenebuilder和MVC启动器的新javaFx。

我遇到如下问题: 我试图建立一个主窗口来提醒一个新窗口。我试图在该警报窗口中化标签文本。但我不能这样做。我收到了这个错误:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(GlassViewEventHandler.java:388)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 48 more
Caused by: java.lang.NullPointerException
    at controller.AlertController.setAlertLabel(AlertController.java:36)
    at controller.MainController.onMainButtonClicked(MainController.java:24)
    ... 58 more

我有一个带有maincontroller的主窗口,alertController和main.fxml以及alert.fxml,如下所示:

主要:

package app;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("../view/Main.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

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

主控制器:

package controller;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

public class MainController {

    AlertController alertController = new AlertController();

    @FXML
    public Label mainLabel;

    @FXML
    public TextField mainTextField;

    @FXML
    public Button mainButton;

    @FXML
    public void onMainButtonClicked() {
        alertController.displayAlert();
        alertController.setAlertLabel("Hello from MainController!");
    }
}

Main.fxml:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.MainController">
   <children>
      <VBox prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <HBox alignment="CENTER" prefHeight="154.0" prefWidth="600.0">
               <children>
                  <Label fx:id="mainLabel" alignment="CENTER" contentDisplay="TOP" prefHeight="31.0" prefWidth="115.0" text="Main Text" />
               </children>
            </HBox>
            <HBox alignment="CENTER" centerShape="false" layoutX="10.0" layoutY="10.0">
               <children>
                  <TextField fx:id="mainTextField" alignment="TOP_LEFT" prefHeight="25.0" prefWidth="331.0" />
               </children>
            </HBox>
            <HBox alignment="CENTER" layoutX="10.0" layoutY="10.0" prefHeight="100.0" prefWidth="200.0">
               <children>
                  <Button fx:id="mainButton" mnemonicParsing="false" onAction="#onMainButtonClicked" text="Display Alert &amp;&amp; Set Message Text" />
               </children>
            </HBox>
         </children>
      </VBox>
   </children>
</AnchorPane>

AlertController:

package controller;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;

import java.io.IOException;

public class AlertController {
    Stage window;

    @FXML
    public Label alertLabel;

    @FXML
    Button alertButton;

    public void displayAlert() {
        try {
            window = new Stage();
            Parent root = FXMLLoader.load(getClass().getResource("../view/Alert.fxml"));
            Scene scene = new Scene(root);
            window.setScene(scene);
            window.setTitle("Alert");
            window.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setAlertLabel(String str) {
        alertLabel.setText(str);
    }

    @FXML
    public void onAlertButtonClicked() {
        window.close();
    }
}

和Alert.fxml:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="210.0" prefWidth="380.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.AlertController">
   <children>
      <VBox prefHeight="210.0" prefWidth="380.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <HBox alignment="BOTTOM_CENTER" prefHeight="100.0" prefWidth="200.0">
               <children>
                  <Label fx:id="alertLabel" text="Alert Message" />
               </children>
            </HBox>
            <HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
               <children>
                  <Button fx:id="alertButton" mnemonicParsing="false" onAction="#onAlertButtonClicked" text="Close" />
               </children>
            </HBox>
         </children>
      </VBox>
   </children>
</AnchorPane>

请帮助我解决这个问题并解释为什么这不起作用。谢谢你的建议。

1 个答案:

答案 0 :(得分:3)

AlertController有两个实例:您在MainController中使用

创建的实例
AlertController alertController = new AlertController();

以及FXMLLoaderAlert.fxml中加载displayAlert()时创建的内容。

@FXML - 带注释的字段由其创建的实例上的FXMLLoader初始化。但是,您在由setAlertLabel(...)创建的AlertController实例上调用FXMLLoader。所以当你打电话时

alertController.setAlertLabel("Hello from MainController!");

属于alertLabel的{​​{1}}尚未初始化,并且您获得空指针异常。

简单解决方案

最简单的解决方法是在alertController中加载Alert.fxml,并检索正确的控制器实例:

MainController

并从public class MainController { @FXML public Label mainLabel; @FXML public TextField mainTextField; @FXML public Button mainButton; @FXML public void onMainButtonClicked() { FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/Alert.fxml")); Parent root = loader.load(); AlertController alertController = loader.getController(); alertController.setAlertLabel("Hello from MainController!"); Scene scene = new Scene(root); window.setScene(scene); window.setTitle("Alert"); window.show(); } } 中删除displayAlert()方法。

自定义组件解决方案

另一种结构更接近原作的替代方法是将AlertController替换为custom component

Alert.fxml(注意对根元素的更改,并且AlertController已被删除):

fx:controller

AlertController.java:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<fx:root type="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="210.0" prefWidth="380.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" >
   <children>
      <VBox prefHeight="210.0" prefWidth="380.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <HBox alignment="BOTTOM_CENTER" prefHeight="100.0" prefWidth="200.0">
               <children>
                  <Label fx:id="alertLabel" text="Alert Message" />
               </children>
            </HBox>
            <HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
               <children>
                  <Button fx:id="alertButton" mnemonicParsing="false" onAction="#onAlertButtonClicked" text="Close" />
               </children>
            </HBox>
         </children>
      </VBox>
   </children>
</fx:root>

现在您的主控制器可能如下所示:

package controller;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;

import java.io.IOException;

public class AlertController extends AnchorPane {
    Stage window;

    @FXML
    public Label alertLabel;

    @FXML
    Button alertButton;


    public AlertController() {
        window = new Stage();
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/Alert.fxml"));
            loader.setController(this);
            loader.setRoot(this);
            loader.load();
            Scene scene = new Scene(this);
            window.setScene(scene);
            window.setTitle("Alert");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void displayAlert() {
        window.show();
    }

    public void setAlertLabel(String str) {
        alertLabel.setText(str);
    }

    @FXML
    public void onAlertButtonClicked() {
        window.close();
    }
}