JavaFX中的TableView不会从第二个控制器中的用户输入刷新

时间:2018-06-14 12:22:45

标签: java javafx

我正在尝试在Java和Scene Builder中构建我的第一个应用程序,并且在第二个窗口中更新表格中的所选项目(使用“保存”按钮)后,主控制器中的我的Tableview将不会更新。数据库得到更新,但不是表,我在提交保存按钮时遇到了一些错误。我正在使用mySql数据库,当我添加一个新条目时,它工作正常。我首先创建了没有数据库的项目,我没有遇到任何问题。 我不知道如何解决这个问题,我可能做错了什么。请帮忙!

我将代码放在下面。

谢谢!

Main window + Edit window

主要应用

package clients;

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

public class Clients extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Mainwindow.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.setTitle("Clients Table");
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

主要课程:

package clients;

import javafx.beans.property.SimpleStringProperty;

public class Client {

int id;
SimpleStringProperty fName;
SimpleStringProperty lName;
SimpleStringProperty email;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getfName() {
    return fName.get();
}

public void setfName(String fName) {
    this.fName = new SimpleStringProperty(fName);
}

public String getlName() {
    return lName.get();
}

public void setlName(String lName) {
    this.lName = new SimpleStringProperty(lName);
}

public String getEmail() {
    return email.get();
}

public void setEmail(String email) {
    this.email = new SimpleStringProperty(email);
}

public Client(int id, String fName, String lName, String email) {
    this.id = id;
    this.fName = new SimpleStringProperty(fName);
    this.lName = new SimpleStringProperty(lName);
    this.email = new SimpleStringProperty(email);
}

}

MainwindowController:

package clients;

import java.io.IOException; 
import java.net.URL; 
import java.sql.*; 
import java.util.ResourceBundle; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javafx.event.ActionEvent; 
import javafx.fxml.FXML; 
import javafx.fxml.FXMLLoader; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.scene.control.TableColumn; 
import javafx.scene.control.TableView; 
import javafx.scene.layout.AnchorPane; 
import javafx.stage.Modality; 
import javafx.stage.Stage;

public class MainwindowController {

    Connection cnx = null;

    int indexSelect;

    Stage addStage;
    AddController ctrlAdd;
    Stage editStage;
    EditController ctrlEdit;

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private TableView<Client> tclients;

    @FXML
    private TableColumn<Client, Integer> id;

    @FXML
    private TableColumn<Client, String> fname;

    @FXML
    private TableColumn<Client, String> lname;

    @FXML
    private TableColumn<Client, String> cemail;

    @FXML
    void addButton(ActionEvent event) {
        addStage.showAndWait();
    }

    @FXML
    void deleteButton(ActionEvent event) {

    }

    @FXML
    public void editButton(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Edit.fxml"));
        Parent root1 = (Parent) fxmlLoader.load();
        Stage stage = new Stage();
        stage.setTitle("Edit");
        stage.setScene(new Scene(root1));
        EditController controller = fxmlLoader.getController();
        controller.initData(tclients.getSelectionModel().getSelectedItem());
        stage.show();
    }

    @FXML
    void exit(ActionEvent event) {

    }

    void loadData() {
        tclients.getItems().clear();
        String cda = "select * from client order by fname";
        System.out.println("cda: " + cda);
        ResultSet rs;

        try {

            Statement stmt;
            stmt = cnx.createStatement();
            rs = stmt.executeQuery(cda);
            while (rs.next()) {

                int Id = rs.getInt("ID");
                String fName = rs.getString("fname");
                String lName = rs.getString("lname");
                String cEmail = rs.getString("email");

                Client c;
                c = new Client(Id, fName, lName, cEmail);
                tclients.getItems().add(c);
            }
            stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(MainwindowController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    void initialize() {

        fname.setCellValueFactory(cellData -> cellData.getValue().fName);
        lname.setCellValueFactory(cellData -> cellData.getValue().lName);
        cemail.setCellValueFactory(cellData -> cellData.getValue().email);

        tclients.getSelectionModel().selectedIndexProperty().
                addListener((object, oldValue, newValue) -> {

                    indexSelect = (int) newValue;
                });

        try {

            Class.forName("com.mysql.jdbc.Driver");
            cnx = DriverManager.getConnection("jdbc:mysql://localhost/client?characterEncoding=utf8", "root", "");

        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(MainwindowController.class
                    .getName()).log(Level.SEVERE, null, ex);

        }

        loadData();

        try {

            FXMLLoader loader = new FXMLLoader(this.getClass().getResource("Add.fxml"));
            AnchorPane container = (AnchorPane) loader.load();

            ctrlAdd = loader.getController();
            addStage = new Stage();
            addStage.setTitle("New Client");
            addStage.initModality(Modality.APPLICATION_MODAL);
            Scene scene = new Scene(container);
            addStage.setScene(scene);
            ctrlAdd.ctrl = this;

        } catch (IOException e) {

        }
    } }

EditController:

package clients;

import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class EditController {

    MainwindowController ctrl;
    Connection cnx;

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private TextField fName;
    @FXML
    private TextField lName;
    @FXML
    private TextField cEmail;

    private Client selectedClient;

    public void initData(Client client) {
        selectedClient = client;
        fName.setText(selectedClient.getfName());
        lName.setText(selectedClient.getlName());
        cEmail.setText(selectedClient.getEmail());

    }

    private String append(String s) {
        return "'" + s + "'";
    }

    @FXML
    private void save(ActionEvent event) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            cnx = DriverManager.getConnection("jdbc:mysql://localhost/client?characterEncoding=utf8", "root", "");

            int id = selectedClient.getId();
            String f_name = selectedClient.getfName();
            String l_name = selectedClient.getlName();
            String c_email = selectedClient.getEmail();

            String cda = "UPDATE client "
                    + "SET FNAME = " + append(fName.getText())
                    + ", LNAME = " + append(lName.getText())
                    + ", EMAIL = " + append(cEmail.getText())
                    + "WHERE ID = " + id;
            System.out.println(cda);
            Statement stmt = cnx.createStatement();
            stmt.executeUpdate(cda);

            fName.setText(null);
            lName.setText(null);
            cEmail.setText(null);
            ctrl.loadData();

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainwindowController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MainwindowController.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();

        }

    }

    @FXML
    private void cancel(ActionEvent event) {

        Stage stage = (Stage) fName.getScene().getWindow();
        stage.hide();
    }

}

AddController:

package clients;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class AddController  {

    MainwindowController ctrl;
    Connection cnx;

    @FXML
    private TextField fName;
    @FXML
    private TextField lName;
    @FXML
    private TextField cEmail;

    private String append(String s) {
        return "'" + s + "'";
    }


    @FXML
    private void addClient(ActionEvent event) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            cnx = DriverManager.getConnection("jdbc:mysql://localhost/client?characterEncoding=utf8", "root", "");

            String f_name = fName.getText();
            String l_name = lName.getText();
            String cemail = cEmail.getText();

            String cda = "INSERT INTO client "
                    + "VALUES (null,"
                    + append(fName.getText()) + ", " + append(lName.getText())
                    + ", " + append(cEmail.getText()) + ")";

            Statement stmt = cnx.createStatement();
            stmt.executeUpdate(cda);

            ResultSet rs = null;
            rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
            int idNew = -1;
            if (rs.next()) {
                idNew = rs.getInt(1);
            }

            Client c = new Client(idNew, fName.getText(), lName.getText(), cEmail.getText());
            stmt.close();

            ctrl.loadData();

            fName.setText(null);
            lName.setText(null);
            cEmail.setText(null);

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainwindowController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MainwindowController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @FXML
    private void close(ActionEvent event) {

        Stage stage = (Stage) fName.getScene().getWindow();
        stage.hide();
    }

}

Mainwindow.fxml:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>


<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="clients.MainwindowController">
   <top>
      <Label text="Clients table" BorderPane.alignment="CENTER">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
   </top>
   <center>
      <TableView fx:id="tclients" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
        <columns>
          <TableColumn fx:id="id" prefWidth="75.0" text="ID" />
          <TableColumn fx:id="fname" prefWidth="75.0" text="First Name" />
            <TableColumn fx:id="lname" prefWidth="75.0" text="Last Name" />
            <TableColumn fx:id="cemail" prefWidth="75.0" text="Email" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
   </center>
   <bottom>
      <ButtonBar prefHeight="40.0" prefWidth="200.0" BorderPane.alignment="CENTER">
        <buttons>
          <Button mnemonicParsing="false" onAction="#addButton" text="Add new..." />
            <Button layoutX="535.0" layoutY="18.0" mnemonicParsing="false" onAction="#editButton" text="Edit" />
            <Button layoutX="535.0" layoutY="18.0" mnemonicParsing="false" onAction="#deleteButton" text="Delete" />
            <Button layoutX="535.0" layoutY="18.0" mnemonicParsing="false" onAction="#exit" text="Exit" />
        </buttons>
      </ButtonBar>
   </bottom>
</BorderPane>

Edit.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.text.Font?>

<AnchorPane id="AnchorPane" prefHeight="284.0" prefWidth="484.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="clients.EditController">
   <children>
      <Label layoutX="186.0" layoutY="21.0" text="Edit client">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <Label layoutX="93.0" layoutY="98.0" text="First name:" />
      <Label layoutX="94.0" layoutY="153.0" text="Last name:" />
      <Label layoutX="93.0" layoutY="200.0" text="Email:" />
      <TextField fx:id="fName" layoutX="186.0" layoutY="94.0" />
      <TextField fx:id="lName" layoutX="186.0" layoutY="149.0" />
      <TextField fx:id="cEmail" layoutX="186.0" layoutY="196.0" />
      <Button layoutX="125.0" layoutY="239.0" mnemonicParsing="false" onAction="#save" text="Save" />
      <Button layoutX="238.0" layoutY="239.0" mnemonicParsing="false" onAction="#cancel" text="Cancel" />
   </children>
</AnchorPane>

Add.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.text.Font?>

<AnchorPane id="AnchorPane" prefHeight="305.0" prefWidth="498.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="clients.AddController">
   <children>
      <Label layoutX="180.0" layoutY="14.0" text="Add client">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <Label layoutX="92.0" layoutY="84.0" text="First name:" />
      <Label layoutX="92.0" layoutY="130.0" text="Last name:" />
      <Label layoutX="92.0" layoutY="177.0" text="Email:" />
      <TextField fx:id="fName" layoutX="180.0" layoutY="80.0" />
      <TextField fx:id="lName" layoutX="180.0" layoutY="126.0" />
      <TextField fx:id="cEmail" layoutX="180.0" layoutY="173.0" />
      <Button layoutX="142.0" layoutY="237.0" mnemonicParsing="false" onAction="#addClient" text="Add" />
      <Button layoutX="249.0" layoutY="237.0" mnemonicParsing="false" onAction="#close" text="Close" />
   </children>
</AnchorPane>

错误:

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: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(Thread.java:748)
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$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 48 more
Caused by: java.lang.NullPointerException
    at clients.EditController.save(EditController.java:72)
    ... 58 more

0 个答案:

没有答案