初始化控制器时在标签对象上调用setText时出现NullPointerException

时间:2016-06-11 18:30:19

标签: model-view-controller javafx nullpointerexception label fxml

所以我开始创建我的第一个JavaFX应用程序。它目前所做的是显示左侧为TreeView的虚拟数据。我希望它在树上显示所选项目的名称和创建日期为Label在右侧。 问题是,当应用程序开始运行NullPointerException方法时,我收到initialize()错误。它不喜欢我在初始化控制器时运行的方法selectedTree.setText("");中的行setPropertyInfo(null)。任何人都可以建议我做错了什么?

我已将正确的fx:id设置为我的FXML文件并添加注释。

这是控制器类DBOverviewController.java:

import com.demo.xmldb.MainApp;
import com.demo.xmldb.model.Property;
import com.demo.xmldb.util.DateUtil;

import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

public class DBOverviewController {
@FXML
private Label selectedTree;
@FXML
private Label dateLabel;
@FXML
private TreeView<Property> treeView;

private MainApp mainApp;

public DBOverviewController() {
}

/**
 * Initializes the controller class. 
 */
@FXML
private void initialize() {
    setPropertyInfo(null);
    treeView.getSelectionModel().selectedItemProperty().addListener(
            (observable, oldValue, newValue) -> setPropertyInfo(newValue));
}

private void treeInitHelper(TreeItem<Property> root, ObservableList<Property> propertyData) {
    for (Property property : propertyData) {
        if (property.getType().equals("Root")) {
            makeBranch(property, root);
        }
    }

    treeView.setRoot(root);
    treeView.setShowRoot(true);
    root.setExpanded(true);
}

private void setPropertyInfo(TreeItem<Property> property) {
    if (property != null) {
        // Fill the labels with info from the Property object.
        selectedTree.setText(property.getValue().getPropertyName());
        dateLabel.setText(DateUtil.format(property.getValue().getCreationDate()));

    } else {
        // Project is null, remove all the text.
        selectedTree.setText("");
        dateLabel.setText("");
    }
}

private TreeItem<Property> makeBranch(Property title, TreeItem<Property> parent) {
    TreeItem<Property> item = new TreeItem<>(title);
    parent.getChildren().add(item);
    return item;
}

/**
 * Is called by the main application to give a reference back to itself.
 * 
 * @param mainApp
 */
public void setMainApp(MainApp mainApp) {
    this.mainApp = mainApp;
    treeInitHelper(mainApp.getRootNode(), mainApp.getTreePropertyData());
}
}

这是MainApp.java:

import java.io.IOException;

import com.demo.xmldb.view.DBOverviewController;
import com.demo.xmldb.model.Property;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class MainApp extends Application {

private Stage primaryStage;
private BorderPane rootLayout;

private ObservableList<Property> treePropertyData = FXCollections.observableArrayList();
private TreeItem<Property> rootNode;
private Property projectName;

public MainApp() {
    // Sample data
    treePropertyData.add(new Property("Sienos", "Root", "1"));
    treePropertyData.add(new Property("Siena 500mm", "Sustambintas", "1.1"));
    treePropertyData.add(new Property("Siena 500mm", "Sustambintas", "1.1"));
    treePropertyData.add(new Property("Durys", "Root", "2"));
    treePropertyData.add(new Property("Lauko durys raudonos 500", "Sustambintas", "2.1"));
    treePropertyData.add(new Property("Lauko durys raudonos 500", "Smulkus", "2.1.1"));
    treePropertyData.add(new Property("Lauko durys raudonos 500", "Smulkus", "2.1.2"));
    treePropertyData.add(new Property("Langai", "Root", "3"));
    treePropertyData.add(new Property("Langas 200x500", "Sustambintas", "3.1"));
    treePropertyData.add(new Property("Varztai X Type", "Smulkus", "3.1.1"));
    treePropertyData.add(new Property("Darbo jega", "Smulkus", "3.1.2"));
    projectName = new Property("Projektas 1", null, null);
    rootNode = new TreeItem<Property>(projectName);
}

public ObservableList<Property> getTreePropertyData() {
    return treePropertyData;
}

public TreeItem<Property> getRootNode() {
    return rootNode;
}

@Override
public void start(Stage primaryStage) {
    this.primaryStage = primaryStage;
    this.primaryStage.setTitle("XML Tree Database App Demo");

    initRootLayout();
    showDBOverview();
}

/**
 * Initializes the root layout.
 */
public void initRootLayout() {
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
        rootLayout = (BorderPane) loader.load();

        Scene scene = new Scene(rootLayout);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Shows the DB overview inside the root layout.
 */
public void showDBOverview() {
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/DBOverview.fxml"));
        AnchorPane dbOverview = (AnchorPane) loader.load();

        rootLayout.setCenter(dbOverview);

        DBOverviewController controller = loader.getController();
        controller.setMainApp(this);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Returns the main stage.
 * @return
 */
public Stage getPrimaryStage() {
    return primaryStage;
}

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

这是DBOverview.fxml文件:

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

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TreeView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>

<AnchorPane prefHeight="500.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.demo.xmldb.view.DBOverviewController">
   <children>
      <SplitPane dividerPositions="0.23" prefHeight="500.0" prefWidth="1000.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
        <items>
          <AnchorPane minHeight="0.0" minWidth="0.0">
               <children>
                  <TreeView fx:id="treeView" editable="true" layoutX="38.0" layoutY="149.0" prefHeight="498.0" prefWidth="196.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
               </children>
            </AnchorPane>
          <AnchorPane minHeight="0.0" minWidth="0.0">
               <children>
                  <TableView editable="true" fixedCellSize="0.0" layoutX="158.0" layoutY="31.0" prefHeight="467.0" prefWidth="794.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="30.0">
                    <columns>
                      <TableColumn fx:id="idCol" prefWidth="75.0" text="ID" />
                        <TableColumn fx:id="bigIdCol" prefWidth="75.0" text="Sustambintas ID" />
                      <TableColumn fx:id="nameCol" prefWidth="75.0" text="Pavadinimas" />
                        <TableColumn fx:id="typeCol" prefWidth="75.0" text="Tipas" />
                        <TableColumn fx:id="unitCol" prefWidth="75.0" text="Mato vienetas" />
                        <TableColumn fx:id="quantityCol" prefWidth="75.0" text="Kiekis" />
                    </columns>
                     <columnResizePolicy>
                        <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
                     </columnResizePolicy>
                  </TableView>
                  <GridPane prefHeight="30.0" prefWidth="784.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="0.0">
                    <columnConstraints>
                      <ColumnConstraints hgrow="SOMETIMES" maxWidth="603.0" minWidth="10.0" prefWidth="365.0" />
                      <ColumnConstraints halignment="RIGHT" hgrow="SOMETIMES" maxWidth="372.0" minWidth="10.0" prefWidth="362.0" />
                    </columnConstraints>
                    <rowConstraints>
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                     <children>
                        <Label fx:id="selectedTree" text="Selected tree label">
                           <font>
                              <Font size="15.0" />
                           </font>
                        </Label>
                        <Label fx:id="dateLabel" text="Creation date of the tree" GridPane.columnIndex="1">
                           <font>
                              <Font size="12.0" />
                           </font>
                        </Label>
                     </children>
                  </GridPane>
               </children>
            </AnchorPane>
        </items>
      </SplitPane>
   </children>
</AnchorPane>

错误的堆栈跟踪:

Jun 11, 2016 8:49:47 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 8.0.65 by JavaFX runtime of version 8.0.60
javafx.fxml.LoadException: 
/home/vytautas/workspace/TreeXMLDBApp_V1/bin/com/demo/xmldb/view/RootLayout.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2571)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at com.demo.xmldb.MainApp.initRootLayout(MainApp.java:70)
    at com.demo.xmldb.MainApp.start(MainApp.java:59)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$106(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$119(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$117(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$118(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$450(GtkApplication.java:139)
    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:498)
    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:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2566)
    ... 13 more
Caused by: java.lang.NullPointerException
    at com.demo.xmldb.view.DBOverviewController.setPropertyInfo(DBOverviewController.java:56)
    at com.demo.xmldb.view.DBOverviewController.initialize(DBOverviewController.java:31)
    ... 23 more
Jun 11, 2016 8:49:48 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 8.0.65 by JavaFX runtime of version 8.0.60
Exception in Application start method
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:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    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:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$99(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.demo.xmldb.MainApp.showDBOverview(MainApp.java:91)
    at com.demo.xmldb.MainApp.start(MainApp.java:60)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$106(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$119(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$117(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$118(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$450(GtkApplication.java:139)
    ... 1 more
Exception running application com.demo.xmldb.MainApp

0 个答案:

没有答案