JavaFX - TableView已成功填充,但仍会发生NPE

时间:2015-06-06 06:55:34

标签: javafx nullpointerexception tableview

我使用数据库中的数据填充TableView。当我在TableView中选择一行(Tableview具有监听器),然后再次重新填充TableView时,数据填充成功但发生了NPE。

我希望我能表达清楚。

很抱歉这篇长篇文章。

的ActionEvent

@FXML
private void searchEmployee(ActionEvent event)
{
    Stage imageUploadStage = (Stage) ((Node) event.getSource()).getScene().getWindow();

    Alert alert = new Alert(Alert.AlertType.ERROR);
    alert.initOwner(imageUploadStage);

    if(employeeTextField.getText().isEmpty())
    {
        alert.setTitle("Insufficient Data");
        alert.setHeaderText("Lacking search input");
        alert.setContentText("Looks like you forgot to input in the search box!");

        alert.showAndWait();

        employeeTextField.requestFocus();
    }
    else
    {
        final Service<ObservableList<Employee>> service = new Service<ObservableList<Employee>>() 
        {
            @Override
            protected Task<ObservableList<Employee>> createTask() 
            {
                return new Task<ObservableList<Employee>>() 
                {
                    @Override
                    protected ObservableList<Employee> call() throws Exception 
                    {
                        ObservableList<Employee> items = FXCollections.observableArrayList();
                        try
                        {
                            Connection c;
                            PreparedStatement pst;
                            ResultSet rs;

                            c = connect();

                            String SQL = "SELECT " +
                                                    "B1_ID, " +
                                                    "Emp_Fname, " +
                                                    "Emp_Lname, " +
                                                    "Emp_Position, " +
                                                    "Emp_ContactNo, " +
                                                    "Emp_Address, " +
                                                    "Emp_BirthDate, " +
                                                    "Image " +
                                            "FROM pay_employee_tbl " +
                                            "WHERE pay_employee_tbl.Emp_Lname LIKE ?";

                            pst = c.prepareStatement(SQL);
                            pst.setString(1, employeeTextField.getText() + "%");
                            rs = pst.executeQuery();

                            while(rs.next())
                            {   
                                items.add(new Employee(rs.getString("B1_ID"),
                                                    rs.getString("Emp_Fname"), 
                                                    rs.getString("Emp_Lname"), 
                                                    rs.getString("Emp_Position"), 
                                                    rs.getString("Emp_ContactNo"), 
                                                    rs.getString("Emp_Address"), 
                                                    rs.getString("Emp_BirthDate")));
                            }

                            c.close();
                            pst.close();
                            rs.close();
                        }
                        catch(Exception e)
                        {
                            Logger.getLogger(FxmlControllerCLB.class.getName()).log(Level.SEVERE, null, e);
                        }

                        for (int i = 0; i < 250; i++) 
                        {
                            updateProgress(i, 250);
                            Thread.sleep(2);
                        }
                        return items;
                    }
                };
            }
        };

        progressIndicator.visibleProperty().bind(service.runningProperty());
        progressIndicator.progressProperty().bind(service.progressProperty());
        veil.visibleProperty().bind(service.runningProperty());
        employeeTextField.disableProperty().bind(service.runningProperty());
        uploadImageButton.disableProperty().bind(service.runningProperty());
        employeeTableView.itemsProperty().bind(service.valueProperty());

        service.start();
    }
}

数据模型

public class Employee 
{
    private SimpleStringProperty bioKeyID;
    private SimpleStringProperty Fname;
    private SimpleStringProperty Lname;
    private SimpleStringProperty position;
    private SimpleStringProperty contactNo;
    private SimpleStringProperty address;
    private SimpleStringProperty birthDate;

    private Employee()
    {
    }

    public Employee(String bioKeyID, String Fname, String Lname, 
                String position, String contactNo, String address,
                String birthDate)
    {
        this.bioKeyID = new SimpleStringProperty(bioKeyID);
        this.Fname = new SimpleStringProperty(Fname);
        this.Lname = new SimpleStringProperty(Lname);
        this.position = new SimpleStringProperty(position);
        this.contactNo = new SimpleStringProperty(contactNo);
        this.address = new SimpleStringProperty(address);
        this.birthDate = new SimpleStringProperty(birthDate);
    }

    public String getBioKeyID()
    {
        return bioKeyID.get();
    }

    public void setBioKeyID(String bioKeyID)
    {
        this.bioKeyID.set(bioKeyID);
    }

    public StringProperty bioKeyIDProperty()
    {
        return bioKeyID;
    }

    public String getFname()
    {
        return Fname.get();
    }

    public void setFname(String Fname)
    {
        this.Fname.set(Fname);
    }

    public StringProperty FnameProperty()
    {
        return Fname;
    }

    public String getLname()
    {
        return Lname.get();
    }

    public void setLname(String Lname)
    {
        this.Lname.set(Lname);
    }

    public StringProperty LnameProperty()
    {
        return Lname;
    }

    public String getPosition()
    {
        return position.get();
    }

    public void setPosition(String position)
    {
        this.position.set(position);
    }

    public StringProperty positionProperty()
    {
        return position;
    }

    public String getContactNo()
    {
        return contactNo.get();
    }

    public void setContactNo(String contactNo)
    {
        this.contactNo.set(contactNo);
    }

    public StringProperty contactNoProperty()
    {
        return contactNo;
    }

    public String getAddress()
    {
        return address.get();
    }

    public void setAddress(String address)
    {
        this.address.set(address);
    }

    public StringProperty addressProperty()
    {
        return address;
    }

    public String getBirthDate()
    {
        return birthDate.get();
    }

    public void setBirthDate(String birthDate)
    {
        this.birthDate.set(birthDate);
    }

    public SimpleStringProperty birthDateProperty()
    {
        return birthDate;
    }
 }

TableColumn和TableView侦听器

public void initialize(URL url, ResourceBundle rb) 
{
    progressIndicator.setVisible(false);
    progressBar.setVisible(false);
    veil.setVisible(false);

    TableColumn bioKeyID = new TableColumn("BioKey ID");
    bioKeyID.setCellValueFactory(new PropertyValueFactory("bioKeyID"));

    TableColumn empFName = new TableColumn("First Name");
    empFName.setCellValueFactory(new PropertyValueFactory("Fname"));

    TableColumn empLName = new TableColumn("Last Name");
    empLName.setCellValueFactory(new PropertyValueFactory("Lname"));

    TableColumn empName = new TableColumn("Employee Name");
    empName.getColumns().addAll(empFName,empLName );

    TableColumn position = new TableColumn("Position");
    position.setCellValueFactory(new PropertyValueFactory("position"));

    TableColumn contactNo = new TableColumn("Contact No");
    contactNo.setCellValueFactory(new PropertyValueFactory("contactNo"));

    TableColumn address = new TableColumn("Address");
    address.setCellValueFactory(new PropertyValueFactory("Address"));

    TableColumn birthDate = new TableColumn("Birth Date");
    birthDate.setCellValueFactory(new PropertyValueFactory("birthDate"));

    employeeTableView.getColumns().addAll(bioKeyID, empName, position,
                                            contactNo, address, birthDate);



    employeeTableView.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Employee> observableValue, Employee oldValue, Employee newValue) -> 
    { //THIS IS LINE 415
        if(employeeTableView.getSelectionModel().selectedItemProperty() != null)
        {
            empBioKeyLabel.setText(newValue.getBioKeyID());
            empNameLabel.setText(newValue.getLname() + ", " + newValue.getFname());
            empPositionLabel.setText(newValue.getPosition());
            empContactNoLabel.setText(newValue.getContactNo());
        }
    }
}

栈跟踪

Executing D:\NetBeansProjects\PhotoUpload\dist\run1983452311\ImageUpload.jar using platform C:\Program Files\Java\jdk1.8.0_45\jre/bin/java
    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
        at controller.FxmlControllerHRLedger.lambda$initialize$0(FxmlControllerHRLedger.java:415)
        at controller.FxmlControllerHRLedger$$Lambda$240/27188331.changed(Unknown Source)
        at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
        at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
        at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyObjectWrapper.java:176)
        at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:142)
        at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
        at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
        at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102)
        at javafx.scene.control.MultipleSelectionModelBase.lambda$new$34(MultipleSelectionModelBase.java:67)
        at javafx.scene.control.MultipleSelectionModelBase$$Lambda$219/19068940.invalidated(Unknown Source)
        at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
        at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
        at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:176)
        at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:142)
        at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113)
        at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:147)
        at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68)
        at javafx.scene.control.TableView$TableViewArrayListSelectionModel.updateSelectedIndex(TableView.java:2900)
        at javafx.scene.control.TableView$TableViewArrayListSelectionModel.clearSelection(TableView.java:2694)
        at controller.FxmlControllerHRLedger.searchEmployee(FxmlControllerHRLedger.java:274)
        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:1765)
        at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
        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.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:8390)
        at com.sun.javafx.scene.control.behavior.TextFieldBehavior.fire(TextFieldBehavior.java:179)
        at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callAction(TextInputControlBehavior.java:178)
        at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
        at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callActionForEvent(TextInputControlBehavior.java:127)
        at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$75(BehaviorBase.java:135)
        at com.sun.javafx.scene.control.behavior.BehaviorBase$$Lambda$140/32767196.handle(Unknown Source)
        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.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$KeyHandler.process(Scene.java:3965)
        at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3911)
        at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
        at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2502)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:197)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:147)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$349(GlassViewEventHandler.java:228)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$199/17650609.get(Unknown Source)
        at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:227)
        at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
        at com.sun.glass.ui.View.notifyKey(View.java:956)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
        at com.sun.glass.ui.win.WinApplication$$Lambda$36/17230114.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:1)

我在searchEmployee事件结束时添加了employeeTableView.requestFocus();,并将employeeTableView侦听器中的条件从if(employeeTableView.getSelectionModel().selectedItemProperty() != null)更改为if(employeeTableView.isFocused() == true)

employeeTableView.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) ->
{
    //if(employeeTableView.getSelectionModel().selectedItemProperty() != null)
    if(employeeTableView.isFocused() == true)
    {
        empBioKeyLabel.setText(newValue.getBioKeyID());
        empNameLabel.setText(newValue.getLname() + ", " + newValue.getFname());
        empPositionLabel.setText(newValue.getPosition());
        empContactNoLabel.setText(newValue.getContactNo());
    }
}
相关问题