所以我的问题是我无法将数据显示到表格视图,我不明白为什么 我有一个表单使用 ProductController 和显示 tableview 方法,在另一个控制器 CardProductContrller 中,我在 addFcn 方法中调用 ProductController 中的方法,它返回错误:
无法调用
javafx.scene.control.TableColumn.setCellValueFactory(javafx.util.Callback)
,因为 this.colName
为 null
这里有更详细的错误:
java.lang.NullPointerException: Cannot invoke "javafx.scene.control.TableColumn.setCellValueFactory(javafx.util.Callback)" because "this.colName" is null
at application.ProductController.showOrderDetail(ProductController.java:409)
at application.CardProdController.addFcn(CardProdController.java:169)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:72)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at javafx.base@21/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:270)
at javafx.fxml@21/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:84)
at javafx.fxml@21/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1855)
at javafx.fxml@21/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1726)
at javafx.base@21/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base@21/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:232)
at javafx.base@21/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:189)
at javafx.base@21/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base@21/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base@21/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics@21/javafx.scene.Node.fireEvent(Node.java:8875)
at javafx.controls@21/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls@21/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:207)
at javafx.controls@21/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base@21/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at javafx.base@21/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base@21/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:232)
at javafx.base@21/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:189)
at javafx.base@21/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base@21/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base@21/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base@21/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base@21/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics@21/javafx.scene.Scene$MouseHandler.process(Scene.java:3984)
at javafx.graphics@21/javafx.scene.Scene.processMouseEvent(Scene.java:1890)
at javafx.graphics@21/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2708)
at javafx.graphics@21/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
at javafx.graphics@21/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
at javafx.graphics@21/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
at javafx.graphics@21/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
at javafx.graphics@21/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
at javafx.graphics@21/com.sun.glass.ui.View.handleMouseEvent(View.java:551)
at javafx.graphics@21/com.sun.glass.ui.View.notifyMouse(View.java:937)
at javafx.graphics@21/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics@21/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:185)
at java.base/java.lang.Thread.run(Thread.java:1583)
这里的代码: 卡产品控制器:
package application;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
public class CardProdController implements Initializable {
@FXML
private Button addBtn;
@FXML
private BorderPane cardForm;
@FXML
private ImageView imageView;
@FXML
private Label name;
@FXML
private Label price;
@FXML
private Spinner<Integer> quantity;
private productModel productM;
private Image image;
private String proId;
private String pro_image;
private String pro_date;
private SpinnerValueFactory<Integer> spin;
@FXML
private Connection connection;
private PreparedStatement prepare;
private ResultSet result;
private Alert alert;
private double pr;
private int cusId;
public void setData(productModel productM) {
this.productM = productM;
pro_image = productM.getProductImage();
pro_date = String.valueOf(productM.getDate());
proId = productM.getProductId();
name.setText(productM.getProductName());
price.setText(String.valueOf(productM.getProductPrice()));
String path = "File:" + productM.getProductImage();
image = new Image(path, 190, 130, false, true);
imageView.setImage(image);
pr = productM.getProductPrice();
}
private int qty;
private double totalP;
private String ordDID;
public void addFcn() throws SQLException {
ProductController pC = new ProductController();
pC.customerID();
pC.order_detailID();
qty = quantity.getValue();
String check = "";
String checkAvailable = "SELECT pro_status FROM product WHERE pro_id = '" + proId + "'";
connection = Database.connect();
try {
int checkS = 0;
String checkStock = "SELECT pro_quantity FROM product WHERE pro_id = '" + proId + "'";
prepare = connection.prepareStatement(checkStock);
result = prepare.executeQuery();
if(result.next()) {
checkS = result.getInt("pro_quantity");
}
if(checkS == 0){
String updateStock = "UPDATE product SET pro_status = 'Unavailable' WHERE pro_id = '"+proId+"'";
//update to database to mark it as unavailable
prepare = connection.prepareStatement(updateStock);
prepare.executeUpdate();
}
prepare = connection.prepareStatement(checkAvailable);
result = prepare.executeQuery();
if (result.next()) {
check = result.getString("pro_status");
}
if (!check.equals("Available") || qty == 0) {
alert = new Alert(AlertType.ERROR);
alert.setTitle("Error Message");
alert.setHeaderText(null);
alert.setContentText("Product currently unavalible or we run out");
alert.showAndWait();
} else {
if (checkS < qty) {
alert = new Alert(AlertType.ERROR);
alert.setTitle("Error Message");
alert.setHeaderText(null);
alert.setContentText("Invalid. This product is Out of stock");
alert.showAndWait();
} else {
pro_image = pro_image.replace("\\", "\\\\");
String insertData = "INSERT INTO order_detail "
+ "(cus_id, ord_id, pro_id ,pro_name, pro_price, pro_quantity, orderDate) "
+ "VALUES(?,?,?,?,?,?,?)";
prepare = connection.prepareStatement(insertData);
prepare.setString(1, String.valueOf(data.cusId));
ordDID = data.ordDiD;
prepare.setString(2, ordDID);
prepare.setString(3, proId);
prepare.setString(4, name.getText());
totalP = (qty * pr);
prepare.setString(5, String.valueOf(totalP));
prepare.setString(6, String.valueOf(qty));
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
prepare.setString(7, String.valueOf(sqlDate));
prepare.executeUpdate();
int upStock = checkS - qty;
String updateStock = "UPDATE product SET pro_quantity = " + upStock + " WHERE pro_id = '"+proId+"'";
//update product to mark it's quantity as decreased as being order by customer
prepare = connection.prepareStatement(updateStock);
prepare.executeUpdate();
alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Message");
alert.setHeaderText(null);
alert.setContentText("Successfully Added!");
Optional<ButtonType> option = alert.showAndWait();
if(option.get().equals(ButtonType.OK)) {
pC.showOrderDetail();
}
//pC.menuGetTotal();//tinh sau
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setQuantity() {
spin = new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 100, 0);
quantity.setValueFactory(spin);
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
setQuantity();
}
}
产品控制器:
package application;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import java.util.ResourceBundle;
import com.mysql.cj.x.protobuf.MysqlxCrud.Column;
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.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class ProductController implements Initializable{
@FXML
private GridPane gridProd;
@FXML
private Button clBtn;
@FXML
private Button doneBtn;
@FXML
private Button clrBtn;
@FXML
private TableColumn<order_detailModel, String> colName;
@FXML
private TableColumn<order_detailModel, String> colPrice;
@FXML
private TableColumn<order_detailModel, String> colQuantity;
@FXML
private TableView<order_detailModel> orderView;
@FXML
private Button payBtn;
@FXML
private Button printBillBtn;
@FXML
private Label totalBill;
@FXML
private Connection connection;
private PreparedStatement prepare;
private ResultSet result;
private Alert alert;
@FXML
private Stage sideStage;
private Scene scene;
private Parent root;
private int cID;
public void customerID() throws SQLException {
String sql = "SELECT MAX(cus_id) FROM customer";
connection = Database.connect();
try {
prepare = connection.prepareStatement(sql);
result = prepare.executeQuery();
if (result.next()) {
cID = result.getInt("MAX(cus_id)");
}
String checkCID = "SELECT MAX(cus_id) FROM receipt";
prepare = connection.prepareStatement(checkCID);
result = prepare.executeQuery();
int checkID = 0;
if (result.next()) {
checkID = result.getInt("MAX(cus_id)");
}
if (cID == 0) {
cID += 1;
} else if (cID == checkID) {
cID += 1;
}
data.cusId = cID;
} catch (Exception e) {
e.printStackTrace();
}
}
private String odID;
public void order_detailID() throws SQLException {
String sql = "SELECT MAX(ord_id) FROM order_detail";
connection = Database.connect();
try {
prepare = connection.prepareStatement(sql);
result = prepare.executeQuery();
if (result.next()) {
odID = result.getString("MAX(ord_id)");
}
String checkODID = "SELECT MAX(ord_id) FROM receipt ";
prepare = connection.prepareStatement(checkODID);
result = prepare.executeQuery();
String checkID = null;
if (result.next()) {
checkID = result.getString("MAX(ord_id)");
}
if (odID == null) {
String aIM = "ORD-" + 0;
odID = aIM + 1;
} else if (odID == checkID) {
String aIM = "ORD-" + 0;
odID = aIM + 1;
}
data.ordDiD = odID;
System.out.println(data.ordDiD);
} catch (Exception e) {
e.printStackTrace();
}
}
private ObservableList<productModel> cardDataList = FXCollections.observableArrayList();
public ObservableList<productModel> getData(){
ObservableList<productModel> ListData = FXCollections.observableArrayList();
String getData = "SELECT * FROM product";
try {
connection = Database.connect();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
prepare = connection.prepareStatement(getData);
result = prepare.executeQuery();
productModel productM;
while(result.next()) {
productM = new productModel(result.getInt("id")
,result.getString("pro_id")
, result.getString("pro_name")
, result.getDouble("pro_price")
, result.getInt("pro_quantity")
, result.getString("pro_image"));
ListData.add(productM);
}
}catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return ListData;
}
public void menuProd() {
cardDataList.clear();
cardDataList.addAll(getData());
int row = 0;
int column = 0;
gridProd.getChildren().clear();
gridProd.getRowConstraints().clear();
gridProd.getColumnConstraints().clear();
for(int i = 0; i < cardDataList.size(); i++) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("cardProduct.fxml"));
Pane pane = loader.load();
CardProdController cpC = loader.getController();
cpC.setData(cardDataList.get(i));
if(column == 3) {
column = 0;
row += 1;
}
gridProd.add(pane, column++, row);
GridPane.setMargin(pane, new Insets(10));
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public void clFcn(ActionEvent event) throws IOException {
root = FXMLLoader.load(getClass().getResource("StaffSection.fxml"));
sideStage = (Stage)((Node)event.getSource()).getScene().getWindow();
scene = new Scene(root);
sideStage.setScene(scene);
sideStage.setResizable(false);
sideStage.show();
}
public void doneFcn(ActionEvent event) throws IOException {
root = FXMLLoader.load(getClass().getResource("StaffSection.fxml"));
sideStage = (Stage)((Node)event.getSource()).getScene().getWindow();
scene = new Scene(root);
sideStage.setScene(scene);
sideStage.setResizable(false);
sideStage.show();
}
public ObservableList<order_detailModel> orderDList() throws SQLException {
ObservableList<order_detailModel> oList = FXCollections.observableArrayList();
String getData = "SELECT pro_name, pro_price, pro_quantity FROM order_detail";
connection = Database.connect();
try {
prepare = connection.prepareStatement(getData);
result = prepare.executeQuery();
order_detailModel ordDM;
while(result.next()) {
ordDM = new order_detailModel(result.getString("pro_name")
,result.getDouble("pro_price")
,result.getInt("pro_quantity"));
oList.add(ordDM);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return oList;
}
ObservableList<order_detailModel> listOrdD;
public void showOrderDetail() {
try {
listOrdD = orderDList();
colName.setCellValueFactory(new PropertyValueFactory<>("pro_name"));
colPrice.setCellValueFactory(new PropertyValueFactory<>("pro_price"));
colQuantity.setCellValueFactory(new PropertyValueFactory<>("pro_quantity"));
orderView.setItems(listOrdD);
}catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
getData();
menuProd();
}
}
FXML 文件使用 Productcontroller :
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<BorderPane prefHeight="700.0" prefWidth="1200.0" stylesheets="@CSS/TableServe.css" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ProductController">
<center>
<AnchorPane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<AnchorPane fx:id="acPane1" layoutX="15.0" layoutY="15.0" prefHeight="670.0" prefWidth="750.0">
<children>
<ScrollPane layoutX="15.0" layoutY="15.0" prefHeight="640.0" prefWidth="720.0">
<content>
<GridPane fx:id="gridProd" hgap="10.0" prefHeight="879.0" prefWidth="680.0" vgap="10.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints fillHeight="false" minHeight="10.0" prefHeight="100.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="100.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="100.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="100.0" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>
</content>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</ScrollPane>
</children>
</AnchorPane>
<AnchorPane fx:id="acPane2" layoutX="785.0" layoutY="15.0" prefHeight="670.0" prefWidth="400.0">
<children>
<Pane prefHeight="670.0" prefWidth="400.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<TableView fx:id="orderView" layoutX="15.0" layoutY="14.0" prefHeight="456.0" prefWidth="370.0">
<columns>
<TableColumn fx:id="colName" prefWidth="166.4000244140625" text="Name" />
<TableColumn fx:id="colPrice" prefWidth="108.800048828125" text="Price" />
<TableColumn fx:id="colQuantity" prefWidth="93.5999755859375" text="Quantity'" />
</columns>
</TableView>
<Button fx:id="payBtn" layoutX="10.0" layoutY="566.0" mnemonicParsing="false" prefWidth="120.0" text="Pay" />
<Button fx:id="printBillBtn" layoutX="270.0" layoutY="566.0" mnemonicParsing="false" prefWidth="120.0" text="Print BIll" />
<Button fx:id="clrBtn" layoutX="140.0" layoutY="566.0" mnemonicParsing="false" prefWidth="120.0" text="Clear" />
<Button fx:id="clBtn" layoutX="225.0" layoutY="629.0" mnemonicParsing="false" onAction="#clFcn" prefHeight="30.0" prefWidth="160.0" text="Cancel" />
<Button fx:id="doneBtn" layoutX="17.0" layoutY="629.0" mnemonicParsing="false" onAction="#doneFcn" prefHeight="30.0" prefWidth="160.0" text="Done" />
<Label fx:id="totalBill" layoutX="17.0" layoutY="489.0" prefHeight="30.0" prefWidth="173.0" text="Total: 00$$">
<font>
<Font size="20.0" />
</font>
</Label>
</children>
</Pane>
</children>
</AnchorPane>
</children>
</AnchorPane>
</center>
</BorderPane>
我几乎做了所有事情,使用chatgpt得到了ofc的帮助,但仍然不知道为什么,我认为我的sql是错误的?
切勿在 FXML 文件中指定的控制器上调用
new
。
此代码错误:
ProductController pC = new ProductController();
在控制器上调用
new
的唯一有效情况是如果这两个条件都为 true:
setController
。
来自
setController
的文档:
设置与根对象关联的控制器。传递给此方法的值用作只有
fx:controller
属性的值。如果文档中未指定fx:controller
属性,则在使用控制器事件处理程序时,必须在加载文档之前调用此方法。
FXMLLoader
才会将控制器中的
@FXML
带注释的字段初始化为 FXML 文件中配置的值。如果您只是在代码中创建一个新控制器,则控制器中所有带
@FXML
注释的字段都将是
null
。此外,如果您
也在其他地方加载了FXML,那么当您加载FXML时,加载程序将创建您在FXML中指定的控制器的实例。因此,如果您随后在控制器上调用 new,您将获得控制器的另一个实例,该实例与控制器创建的实例以及 load()