无法将新行添加到 javafx 中的表视图
cannot add new row to tableview in javafx
我正在创建一个应用程序作为我的家庭作业,它接收客户信息并使用 derby 数据库和 javafx 进行注册。注册后,新客户将出现在表格视图中。我一直在尝试向 tableview 添加行,但 java.lang.reflect.InvocationTargetException
不断弹出,我不知道发生了什么。我想从我的 derby 数据库中检索数据并将其显示在我的应用程序的表视图中。当您打开应用程序时,可以选择添加新客户。单击添加新客户的选项时,将弹出一个新的 window,要求提供新客户的信息。我为新客户条目 window 制作了一个单独的 FXML 文件,并为它制作了一个单独的控制器(此处均未显示)。在客户条目 window 上输入所有必需的信息后,单击提交按钮,输入的信息将被插入到 derby 数据库中,然后 NewCustomerEntryController class 将调用 "handleNewSubmit" "RetailSystemController" class 中的方法(如下所示)。请在下面查看我的代码和弹出的异常。
这是主要的 class,它覆盖了 javafx 的启动方法,我已经在这个 class
中为 derby 设置了我的驱动程序和 URL 连接
package retailsystem;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DatabaseMetaData;
public class main extends Application {
private static Connection conn;
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("retailsystem.fxml"));
primaryStage.setTitle("Retail System Management");
primaryStage.setScene(new Scene(root, 600, 400));
setUpDB();
primaryStage.show();
}
private void setUpDB() throws Exception {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String dbName = "RetailSystemDB";
String connectionURL = "jdbc:derby:" + dbName + ";create=true";
String createCustomerString = "CREATE TABLE Customer (FirstName VARCHAR (50) NOT "
+ "NULL, LastName VARCHAR(50) NOT NULL, StreetAddress VARCHAR(50) "
+ "NOT NULL, City VARCHAR(20) NOT NULL, State VARCHAR(12) NOT NULL, "
+ "Zipcode VARCHAR(5), Gender VARCHAR(6))";
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet checkCustomer = dbm.getTables(null, null, "CUSTOMER", null);
if (!checkCustomer.next()) {
stmt.executeUpdate(createCustomerString);
}
stmt.close();
}
public static Connection getConn() {
return conn;
}
public static void main(String[] args) {
launch(args);
}
}
下面的代码是新客户入口的控制器window:
package retailsystem;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javafx.scene.control.TableView;
public class CustomerInformationController implements Initializable {
@FXML
private TextField fEntry;
@FXML
private TextField lEntry;
@FXML
private TextField aEntry;
@FXML
private TextField cEntry;
@FXML
private ComboBox<String> sEntry;
@FXML
private RadioButton male;
@FXML
private RadioButton female;
@FXML
private TextField zEntry;
@FXML
private Button submitBTN;
@FXML
private Button cancelBtn;
private static person customer;
ToggleGroup group = new ToggleGroup();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
String[] stateList = getStateList();
for (int i = 0; i < stateList.length; i++) {
sEntry.getItems().add(stateList[i]);
}
sEntry.setValue(stateList[0]);
male.setToggleGroup(group);
female.setToggleGroup(group);
}
@FXML
private void handleSubmit(ActionEvent event) throws Exception {
RadioButton selectedBtn = (RadioButton) group.getSelectedToggle();
customer = new person(fEntry.getText(), lEntry.getText(),
aEntry.getText(), cEntry.getText(), sEntry.getValue(), zEntry.getText(),
selectedBtn.getText());
Connection conn = main.getConn();
PreparedStatement psInsert = conn.prepareStatement("INSERT INTO CUSTOMER "
+ "(FirstName, LastName, StreetAddress, City, State, Zipcode, "
+ "Gender) VALUES(?,?,?,?,?,?,?)");
psInsert.setString(1, customer.getFirstName());
psInsert.setString(2, customer.getLastName());
psInsert.setString(3, customer.getAddress());
psInsert.setString(4, customer.getCity());
psInsert.setString(5, customer.getState());
psInsert.setString(6, customer.getZipcode());
psInsert.setString(7, customer.getGender());
psInsert.executeUpdate();
RetailSystemController retailcontroller = new RetailSystemController();
retailcontroller.handleNewSubmit();
psInsert.close();
}
}
下面的代码是我的fxml文件
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="retailsystem.RetailSystemController">
<center>
<TableView fx:id="tView" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="fName" prefWidth="90.0" text="First Name" />
<TableColumn fx:id="lName" prefWidth="90.0" text="Last Name" />
<TableColumn fx:id="address" prefWidth="147.0" text="Street Address" />
<TableColumn fx:id="city" prefWidth="87.0" text="City" />
<TableColumn fx:id="state" prefWidth="64.0" text="State" />
<TableColumn fx:id="zip" prefWidth="62.0" text="Zip Code" />
<TableColumn fx:id="gender" prefWidth="70.0" text="Gender" />
</columns>
</TableView>
</center>
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="Customer">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleCustomerAddNew" text="Add New" />
<MenuItem mnemonicParsing="false" onAction="#handleCustomerListAll" text="List All" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Employee">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleEmployeeAddNew" text="Add New " />
<MenuItem mnemonicParsing="false" onAction="#handleEmployeeListAll" text="List All" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Merchandise">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleMerchandiseAddNew" text="Add New" />
<MenuItem mnemonicParsing="false" onAction="#handleMerchandiseListAll" text="List All" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
</BorderPane>
下面的代码是上面提到的 fxml 文件的控制器 class,这个 class 中有很多处理程序,但我只关注 "handleCustomerAddnew" 和 "handleNewSubmit" 目前我还没有为其他人编写太多代码。 问题出现在这个class:
中的handleNewSubmit方法
package retailsystem;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
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.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.stage.Window;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class RetailSystemController implements Initializable {
@FXML
private TableColumn fName;
@FXML
private TableColumn lName;
@FXML
private TableColumn address;
@FXML
private TableColumn city;
@FXML
private TableColumn state;
@FXML
private TableColumn zip;
@FXML
private TableColumn gender;
@FXML
private TableView<person> tView;
public void initialize(URL url, ResourceBundle rb) {
//ToDo
fName.setCellValueFactory(new PropertyValueFactory<person, String>("firstName"));
lName.setCellValueFactory(new PropertyValueFactory<person, String>("lastName"));
address.setCellValueFactory(new PropertyValueFactory<person, String>("address"));
city.setCellValueFactory(new PropertyValueFactory<person, String>("city"));
state.setCellValueFactory(new PropertyValueFactory<person, String>("state"));
zip.setCellValueFactory(new PropertyValueFactory<person, String>("Zipcode"));
gender.setCellValueFactory(new PropertyValueFactory<person, String>("gender"));
}
@FXML
private void handleCustomerAddNew(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("customerinformation.fxml"));
Stage stage = new Stage();
stage.setTitle("Customer Information");
stage.setScene(new Scene(root, 400, 340));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleNewSubmit() {
System.out.println("beginning of handleNewSubmit");
ArrayList<person> registeredPersons=new ArrayList<person>();
Connection conn = main.getConn();
String query = "SELECT * FROM CUSTOMER";
try{
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet resultset = stmt.executeQuery();
while(resultset.next()){
System.out.println(resultset.getString("FirstName")+" "+resultset.getString("LastName"));
registeredPersons.add(new person(resultset.getString("FirstName"),resultset.getString("LastName"), resultset.getString("StreetAddress"),
resultset.getString("City"),resultset.getString("State"),resultset.getString("Zipcode"),resultset.getString("Gender")));
}}
catch (Exception e){
e.printStackTrace();
}
ObservableList<person> items = FXCollections.observableArrayList(registeredPersons);
System.out.println("before adding to tView");
tView.setItems(items);
System.out.println("after adding to tView");
}
}
错误:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8885)
at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3890)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1885)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2618)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent(GlassViewEventHandler.java:447)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
at javafx.graphics/com.sun.glass.ui.mac.MacView.notifyMouse(MacView.java:127)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
... 44 more
Caused by: java.lang.NullPointerException
at retailsystem.RetailSystemController.handleNewSubmit(RetailSystemController.java:127)
at retailsystem.CustomerInformationController.handleSubmit(CustomerInformationController.java:102)
... 55 more
NullPointerException
发生在行
tView.setItems(items);
tView
是在您的 FXML 文件中定义的 TableView
;加载 FXML 文件时,它将在控制器中初始化。当您调用 handleNewSubmit()
时它为 null 的原因是您不是在控制器上调用该方法,而是在您创建的任意对象(与控制器相同 class )上调用该方法:
private void handleSubmit(ActionEvent event) throws Exception {
// ...
RetailSystemController retailcontroller = new RetailSystemController();
retailcontroller.handleNewSubmit();
// ...
}
解决这个问题的最好方法就是在显示 customerinformation.fxml
文件时将 table 的项目列表传递给 CustomerInformationController
。这样 CustomerInformationController
可以直接更新 table 数据。现在,当您添加一个新项目时,您正试图再次从数据库中加载所有数据:这似乎是不必要的;如果数据库更新成功,您需要做的就是将新项目添加到列表中。
所以你可以这样做:
public class RetailSystemController implements Initializable {
// ...
@FXML
private void handleCustomerAddNew(ActionEvent event) {
Parent root;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("customerinformation.fxml"));
root = loader.load();
CustomerInformationController ciController = loader.getController();
ciController.setDataList(tbl.getItems());
Stage stage = new Stage();
stage.setTitle("Customer Information");
stage.setScene(new Scene(root, 400, 340));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleNewSubmit() {
// you probably don't need this method any more
}
// ...
}
然后:
public class CustomerInformationController implements Initializable {
// ...
private ObservableList<person> dataList ;
public void setDataList(ObservableList<person> dataList) {
this.dataList = dataList();
}
// ...
@FXML
private void handleSubmit(ActionEvent event) throws Exception {
RadioButton selectedBtn = (RadioButton) group.getSelectedToggle();
customer = new person(fEntry.getText(), lEntry.getText(),
aEntry.getText(), cEntry.getText(), sEntry.getValue(), zEntry.getText(),
selectedBtn.getText());
Connection conn = main.getConn();
PreparedStatement psInsert = conn.prepareStatement("INSERT INTO CUSTOMER "
+ "(FirstName, LastName, StreetAddress, City, State, Zipcode, "
+ "Gender) VALUES(?,?,?,?,?,?,?)");
psInsert.setString(1, customer.getFirstName());
psInsert.setString(2, customer.getLastName());
psInsert.setString(3, customer.getAddress());
psInsert.setString(4, customer.getCity());
psInsert.setString(5, customer.getState());
psInsert.setString(6, customer.getZipcode());
psInsert.setString(7, customer.getGender());
psInsert.executeUpdate();
// RetailSystemController retailcontroller = new RetailSystemController();
// retailcontroller.handleNewSubmit();
psInsert.close();
dataList.add(customer) ;
}
// ...
}
显然,在实际应用程序中,您会将数据库代码移动到单独的 class,并适当地处理异常等。
如果你真的需要从数据库重新加载整个列表,在添加一个新条目之后,那么你可以在 handleSubmit()
方法中完成,只需使用 dataList.setAll(...)
替换现有项目等。但是同样,由于您知道刚刚对数据库进行了哪些更改,因此您可以对 table 的后备列表进行相同的更改。
我正在创建一个应用程序作为我的家庭作业,它接收客户信息并使用 derby 数据库和 javafx 进行注册。注册后,新客户将出现在表格视图中。我一直在尝试向 tableview 添加行,但 java.lang.reflect.InvocationTargetException
不断弹出,我不知道发生了什么。我想从我的 derby 数据库中检索数据并将其显示在我的应用程序的表视图中。当您打开应用程序时,可以选择添加新客户。单击添加新客户的选项时,将弹出一个新的 window,要求提供新客户的信息。我为新客户条目 window 制作了一个单独的 FXML 文件,并为它制作了一个单独的控制器(此处均未显示)。在客户条目 window 上输入所有必需的信息后,单击提交按钮,输入的信息将被插入到 derby 数据库中,然后 NewCustomerEntryController class 将调用 "handleNewSubmit" "RetailSystemController" class 中的方法(如下所示)。请在下面查看我的代码和弹出的异常。
这是主要的 class,它覆盖了 javafx 的启动方法,我已经在这个 class
中为 derby 设置了我的驱动程序和 URL 连接package retailsystem;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DatabaseMetaData;
public class main extends Application {
private static Connection conn;
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("retailsystem.fxml"));
primaryStage.setTitle("Retail System Management");
primaryStage.setScene(new Scene(root, 600, 400));
setUpDB();
primaryStage.show();
}
private void setUpDB() throws Exception {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String dbName = "RetailSystemDB";
String connectionURL = "jdbc:derby:" + dbName + ";create=true";
String createCustomerString = "CREATE TABLE Customer (FirstName VARCHAR (50) NOT "
+ "NULL, LastName VARCHAR(50) NOT NULL, StreetAddress VARCHAR(50) "
+ "NOT NULL, City VARCHAR(20) NOT NULL, State VARCHAR(12) NOT NULL, "
+ "Zipcode VARCHAR(5), Gender VARCHAR(6))";
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet checkCustomer = dbm.getTables(null, null, "CUSTOMER", null);
if (!checkCustomer.next()) {
stmt.executeUpdate(createCustomerString);
}
stmt.close();
}
public static Connection getConn() {
return conn;
}
public static void main(String[] args) {
launch(args);
}
}
下面的代码是新客户入口的控制器window:
package retailsystem;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javafx.scene.control.TableView;
public class CustomerInformationController implements Initializable {
@FXML
private TextField fEntry;
@FXML
private TextField lEntry;
@FXML
private TextField aEntry;
@FXML
private TextField cEntry;
@FXML
private ComboBox<String> sEntry;
@FXML
private RadioButton male;
@FXML
private RadioButton female;
@FXML
private TextField zEntry;
@FXML
private Button submitBTN;
@FXML
private Button cancelBtn;
private static person customer;
ToggleGroup group = new ToggleGroup();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
String[] stateList = getStateList();
for (int i = 0; i < stateList.length; i++) {
sEntry.getItems().add(stateList[i]);
}
sEntry.setValue(stateList[0]);
male.setToggleGroup(group);
female.setToggleGroup(group);
}
@FXML
private void handleSubmit(ActionEvent event) throws Exception {
RadioButton selectedBtn = (RadioButton) group.getSelectedToggle();
customer = new person(fEntry.getText(), lEntry.getText(),
aEntry.getText(), cEntry.getText(), sEntry.getValue(), zEntry.getText(),
selectedBtn.getText());
Connection conn = main.getConn();
PreparedStatement psInsert = conn.prepareStatement("INSERT INTO CUSTOMER "
+ "(FirstName, LastName, StreetAddress, City, State, Zipcode, "
+ "Gender) VALUES(?,?,?,?,?,?,?)");
psInsert.setString(1, customer.getFirstName());
psInsert.setString(2, customer.getLastName());
psInsert.setString(3, customer.getAddress());
psInsert.setString(4, customer.getCity());
psInsert.setString(5, customer.getState());
psInsert.setString(6, customer.getZipcode());
psInsert.setString(7, customer.getGender());
psInsert.executeUpdate();
RetailSystemController retailcontroller = new RetailSystemController();
retailcontroller.handleNewSubmit();
psInsert.close();
}
}
下面的代码是我的fxml文件
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="retailsystem.RetailSystemController">
<center>
<TableView fx:id="tView" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="fName" prefWidth="90.0" text="First Name" />
<TableColumn fx:id="lName" prefWidth="90.0" text="Last Name" />
<TableColumn fx:id="address" prefWidth="147.0" text="Street Address" />
<TableColumn fx:id="city" prefWidth="87.0" text="City" />
<TableColumn fx:id="state" prefWidth="64.0" text="State" />
<TableColumn fx:id="zip" prefWidth="62.0" text="Zip Code" />
<TableColumn fx:id="gender" prefWidth="70.0" text="Gender" />
</columns>
</TableView>
</center>
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="Customer">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleCustomerAddNew" text="Add New" />
<MenuItem mnemonicParsing="false" onAction="#handleCustomerListAll" text="List All" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Employee">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleEmployeeAddNew" text="Add New " />
<MenuItem mnemonicParsing="false" onAction="#handleEmployeeListAll" text="List All" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Merchandise">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleMerchandiseAddNew" text="Add New" />
<MenuItem mnemonicParsing="false" onAction="#handleMerchandiseListAll" text="List All" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
</BorderPane>
下面的代码是上面提到的 fxml 文件的控制器 class,这个 class 中有很多处理程序,但我只关注 "handleCustomerAddnew" 和 "handleNewSubmit" 目前我还没有为其他人编写太多代码。 问题出现在这个class:
中的handleNewSubmit方法package retailsystem;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
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.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.stage.Window;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class RetailSystemController implements Initializable {
@FXML
private TableColumn fName;
@FXML
private TableColumn lName;
@FXML
private TableColumn address;
@FXML
private TableColumn city;
@FXML
private TableColumn state;
@FXML
private TableColumn zip;
@FXML
private TableColumn gender;
@FXML
private TableView<person> tView;
public void initialize(URL url, ResourceBundle rb) {
//ToDo
fName.setCellValueFactory(new PropertyValueFactory<person, String>("firstName"));
lName.setCellValueFactory(new PropertyValueFactory<person, String>("lastName"));
address.setCellValueFactory(new PropertyValueFactory<person, String>("address"));
city.setCellValueFactory(new PropertyValueFactory<person, String>("city"));
state.setCellValueFactory(new PropertyValueFactory<person, String>("state"));
zip.setCellValueFactory(new PropertyValueFactory<person, String>("Zipcode"));
gender.setCellValueFactory(new PropertyValueFactory<person, String>("gender"));
}
@FXML
private void handleCustomerAddNew(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("customerinformation.fxml"));
Stage stage = new Stage();
stage.setTitle("Customer Information");
stage.setScene(new Scene(root, 400, 340));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleNewSubmit() {
System.out.println("beginning of handleNewSubmit");
ArrayList<person> registeredPersons=new ArrayList<person>();
Connection conn = main.getConn();
String query = "SELECT * FROM CUSTOMER";
try{
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet resultset = stmt.executeQuery();
while(resultset.next()){
System.out.println(resultset.getString("FirstName")+" "+resultset.getString("LastName"));
registeredPersons.add(new person(resultset.getString("FirstName"),resultset.getString("LastName"), resultset.getString("StreetAddress"),
resultset.getString("City"),resultset.getString("State"),resultset.getString("Zipcode"),resultset.getString("Gender")));
}}
catch (Exception e){
e.printStackTrace();
}
ObservableList<person> items = FXCollections.observableArrayList(registeredPersons);
System.out.println("before adding to tView");
tView.setItems(items);
System.out.println("after adding to tView");
}
}
错误:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8885)
at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3890)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1885)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2618)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent(GlassViewEventHandler.java:447)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
at javafx.graphics/com.sun.glass.ui.mac.MacView.notifyMouse(MacView.java:127)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
... 44 more
Caused by: java.lang.NullPointerException
at retailsystem.RetailSystemController.handleNewSubmit(RetailSystemController.java:127)
at retailsystem.CustomerInformationController.handleSubmit(CustomerInformationController.java:102)
... 55 more
NullPointerException
发生在行
tView.setItems(items);
tView
是在您的 FXML 文件中定义的 TableView
;加载 FXML 文件时,它将在控制器中初始化。当您调用 handleNewSubmit()
时它为 null 的原因是您不是在控制器上调用该方法,而是在您创建的任意对象(与控制器相同 class )上调用该方法:
private void handleSubmit(ActionEvent event) throws Exception {
// ...
RetailSystemController retailcontroller = new RetailSystemController();
retailcontroller.handleNewSubmit();
// ...
}
解决这个问题的最好方法就是在显示 customerinformation.fxml
文件时将 table 的项目列表传递给 CustomerInformationController
。这样 CustomerInformationController
可以直接更新 table 数据。现在,当您添加一个新项目时,您正试图再次从数据库中加载所有数据:这似乎是不必要的;如果数据库更新成功,您需要做的就是将新项目添加到列表中。
所以你可以这样做:
public class RetailSystemController implements Initializable {
// ...
@FXML
private void handleCustomerAddNew(ActionEvent event) {
Parent root;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("customerinformation.fxml"));
root = loader.load();
CustomerInformationController ciController = loader.getController();
ciController.setDataList(tbl.getItems());
Stage stage = new Stage();
stage.setTitle("Customer Information");
stage.setScene(new Scene(root, 400, 340));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleNewSubmit() {
// you probably don't need this method any more
}
// ...
}
然后:
public class CustomerInformationController implements Initializable {
// ...
private ObservableList<person> dataList ;
public void setDataList(ObservableList<person> dataList) {
this.dataList = dataList();
}
// ...
@FXML
private void handleSubmit(ActionEvent event) throws Exception {
RadioButton selectedBtn = (RadioButton) group.getSelectedToggle();
customer = new person(fEntry.getText(), lEntry.getText(),
aEntry.getText(), cEntry.getText(), sEntry.getValue(), zEntry.getText(),
selectedBtn.getText());
Connection conn = main.getConn();
PreparedStatement psInsert = conn.prepareStatement("INSERT INTO CUSTOMER "
+ "(FirstName, LastName, StreetAddress, City, State, Zipcode, "
+ "Gender) VALUES(?,?,?,?,?,?,?)");
psInsert.setString(1, customer.getFirstName());
psInsert.setString(2, customer.getLastName());
psInsert.setString(3, customer.getAddress());
psInsert.setString(4, customer.getCity());
psInsert.setString(5, customer.getState());
psInsert.setString(6, customer.getZipcode());
psInsert.setString(7, customer.getGender());
psInsert.executeUpdate();
// RetailSystemController retailcontroller = new RetailSystemController();
// retailcontroller.handleNewSubmit();
psInsert.close();
dataList.add(customer) ;
}
// ...
}
显然,在实际应用程序中,您会将数据库代码移动到单独的 class,并适当地处理异常等。
如果你真的需要从数据库重新加载整个列表,在添加一个新条目之后,那么你可以在 handleSubmit()
方法中完成,只需使用 dataList.setAll(...)
替换现有项目等。但是同样,由于您知道刚刚对数据库进行了哪些更改,因此您可以对 table 的后备列表进行相同的更改。