javafx 的 TableView 报错 lang.NullPointerException

如果把含有 TableView 的 fxml ( personnel.fxml ),放在第一个 Stage 窗口显示,则 TableView 中的内容能够正常显示。但是如果放在其他 Stage 窗口,则会报 NullPointerException。

java.lang.NullPointerException
at view.MyController.showList(MyController.java:135)
at view.MyController.personnel(MyController.java:114)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
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:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
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$147(WinApplication.java:177)
at java.lang.Thread.run(Unknown Source)

TalbeView 定义:

Mycontroller.java

package view;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import model.*;
import control.*;

public class MyController implements Initializable {

@FXML
private Button login;

@FXML
private TextField user;

@FXML
private PasswordField password;

@FXML
private Button okay,personnel,department;

@FXML
private TableView<Person> PersonTable;
@FXML
private TableColumn ID;

@FXML
private TableColumn NAME;




@Override
public void initialize(URL location, ResourceBundle resources) {

// TODO (don't really need to do anything here).

}


// When user click on myButton
// this method will be called.
public void login(ActionEvent event) {//登录界面
if (false)
{

Stage LoginFailed = new Stage();
try {
// Read file fxml and draw interface.
Parent root = FXMLLoader.load(getClass()
.getResource("/view/LoginFailed.fxml"));
LoginFailed.setTitle("登陆失败");
LoginFailed.setScene(new Scene(root));
LoginFailed.show();
} catch(Exception e) {
e.printStackTrace();
}
}
else
{
Stage primaryStage = (Stage)login.getScene().getWindow();
primaryStage.close();
Stage ChooseTable = new Stage();
try {
// Read file fxml and draw interface.
Parent root = FXMLLoader.load(getClass()
.getResource("/view/ChooseTable.fxml"));

ChooseTable.setTitle("请选择您要管理的表格");
ChooseTable.setScene(new Scene(root));
ChooseTable.show();
} catch(Exception e) {
e.printStackTrace();
}
}

}
public void okay(ActionEvent event) {
Stage LoginFailed= (Stage)okay.getScene().getWindow();
LoginFailed.close();
}
public void personnel(ActionEvent event) {
Stage choose= (Stage)personnel.getScene().getWindow();
choose.close();




Stage personnel = new Stage();
try {
// Read file fxml and draw interface.

//showList();
Parent root = FXMLLoader.load(getClass()
.getResource("/view/Sample.fxml"));
personnel.setTitle("人员管理");
personnel.setScene(new Scene(root));
showList();//显示表格
personnel.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public void department(ActionEvent event) {
Stage choose= (Stage)okay.getScene().getWindow();
choose.close();

}
public void showList(){
ObservableList<Person> list = FXCollections.observableArrayList();
//ObservableList<User> list = FXCollections.observableArrayList();
Person p1 = new Person();
//User user = new User();//构建值对象

p1.setId("小六");
p1.setName("123");

//colUsername.setCellValueFactory(new PropertyValueFactory("id"));//映射
ID.setCellValueFactory(new PropertyValueFactory("id"));
NAME.setCellValueFactory(new PropertyValueFactory("name"));

list.add(p1); //list 添加值对象
PersonTable.setItems(list); //tableview 添加 list
}
}

Person.java
package model;
public class Person {
private String id;
private String name;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


Main.java

package control;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;
import model.Person;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
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) {
try {


// Read file fxml and draw interface.
Parent root = FXMLLoader.load(getClass()
.getResource("/view/MainScene.fxml"));
primaryStage.setTitle("My Application");
primaryStage.setScene(new Scene(root));
primaryStage.show();

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

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

}
}
package control;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;
import model.Person;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
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) {
try {


// Read file fxml and draw interface.
Parent root = FXMLLoader.load(getClass()
.getResource("/view/MainScene.fxml"));
primaryStage.setTitle("My Application");
primaryStage.setScene(new Scene(root));
primaryStage.show();

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

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

}
}


personnel.fmxl

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

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

<AnchorPane prefHeight="309.0" prefWidth="349.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.MyController">
<children>
<SplitPane dividerPositions="0.30547550432276654" layoutY="-4.0" prefHeight="315.0" prefWidth="349.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<Group>
<children>
<Button layoutX="24.0" layoutY="204.0" mnemonicParsing="false" text="delete" />
<Button layoutX="24.0" layoutY="157.0" mnemonicParsing="false" prefHeight="23.0" prefWidth="59.0" text="add" />
<Button layoutX="24.0" layoutY="116.0" mnemonicParsing="false" prefHeight="23.0" prefWidth="56.0" text="alter" />
<Button layoutX="24.0" layoutY="74.0" mnemonicParsing="false" text="lookup" />
</children>
</Group>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="204.0" prefWidth="266.0">
<children>
<TableView fx:id="PersonTable" prefHeight="313.0" prefWidth="238.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="ID" prefWidth="85.0" text="ID" />
<TableColumn fx:id="NAME" prefWidth="152.0" text="NAME" />
</columns>
</TableView>
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>

1个回答

//controller类点击事件
 @FXML
    public void okbtn(ActionEvent actionEvent) throws Exception {
        Context.setList(list);
        Parent root = FXMLLoader.load(ListsController.class.getResource("/sample/lists.fxml"));
        Scene scene = new Scene(root,1200,600); //创建场景;
        Stage stg=new Stage();//创建舞台;
        stg.initModality(Modality.WINDOW_MODAL);
        stg.setScene(scene); //将场景载入舞台;
        sample.Second s=new Second(stg);
        s.start(stg);
    }
//新窗口类,我这样子就不会报错了
public class Second extends Application {

    Stage stage;

    public Second(Stage stage) {
        this.stage = stage;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage=stage;
        primaryStage.show();
    }
}

//一开始我也是在第一个窗口setRowFactory就没问题但是第二个窗口这样子就报lang.NullPointerException(代码如下)
viewtable.setRowFactory((tv)-> {
            TableRow<UserInputEntity> row=new TableRow<UserInputEntity>(){
                @Override
                protected void updateItem(UserInputEntity item, boolean empty) {
                    super.updateItem(item, empty);
                    if(item!=null && item.getColor().equals("1")){
                        this.setStyle("-fx-control-inner-background: #AFF199");
                    }else if(item!=null && item.getColor().equals("2")){
                        this.setStyle("-fx-control-inner-background:#587A4C");
                    }else if(item!=null && item.getColor().equals("3")){
                        this.setStyle("-fx-control-inner-background: #6E6E6E");
                    }else if(item!=null && item.getColor().equals("4")){
                        this.setStyle("-fx-control-inner-background: #C4768E");
                    }
                }
            };
            return row;
        });

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!