我在javafx、jdbc、postgresql、场景生成器中遇到空指针异常问题

问题描述 投票:0回答:1

我在修复 java.lang.NullPointerException 错误时遇到问题。 我能够连接到数据库,但无法获取数据并将它们放入表视图中。我总是收到:无法调用“javafx.scene.control.TableColumn.setCellValueFactory(javafx.util.Callback)”,因为“this.idMechanicy”为空。但我不知道该怎么办。我尝试了一些东西,但没有任何效果。当然,我得到了 postgresql.jar,连接没有问题。抱歉我的英语不好

这是我的代码:

package org.example.projekt;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;

public class HelloController implements Initializable {
    @FXML
    private Label welcomeText;
    @FXML
    private Button exit;
    @FXML
    protected void exit(MouseEvent e) {
        System.out.println("Wyjście z programu");
        System.exit(0);
    }

    @FXML
    private TableView<mechanicy> tableMechanicy;

    @FXML
    private TableColumn<mechanicy,Integer> idMechanicy;

    @FXML
    private TableColumn<mechanicy,String> nameMechanicy;

    @FXML
    private TableColumn<mechanicy,String> surnameMechanicy;

    @FXML
    private TableColumn<mechanicy,String> employmentMechanicy;

    @FXML
    private TableColumn<mechanicy,String> specialisationMechanicy;



    ObservableList<mechanicy> listMechanicy = FXCollections.observableArrayList();


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        String sqlGetMechanicy = "select * from mechanicy";
        String urlDB = "jdbc:postgresql://localhost:5432/warsztat";
        String username = "postgres";
        String password = "student";

        {
            try {
                Connection con = DriverManager.getConnection(urlDB,username,password);
                Statement st = con.createStatement();
                //resultGM - resultGetMechanicy
                ResultSet resultGM = st.executeQuery(sqlGetMechanicy);



                while (resultGM.next()) {

                    int id = resultGM.getInt("id");
                    String imie = resultGM.getString("imie");
                    String nazwisko = resultGM.getString("nazwisko");
                    String dataZatrudnienia = resultGM.getString("datazatrudnienia");
                    String specjalizacja = resultGM.getString("specjalizacja");

                    listMechanicy.add(new mechanicy(id,imie,nazwisko,dataZatrudnienia,specjalizacja));

                }

                idMechanicy.setCellValueFactory(new PropertyValueFactory<mechanicy,Integer>("id"));
                nameMechanicy.setCellValueFactory(new PropertyValueFactory<mechanicy,String>("name"));
                surnameMechanicy.setCellValueFactory(new PropertyValueFactory<mechanicy,String>("surname"));
                employmentMechanicy.setCellValueFactory(new PropertyValueFactory<mechanicy,String>("datazatrudnienia"));
                specialisationMechanicy.setCellValueFactory(new PropertyValueFactory<mechanicy,String>("specjalizacja"));

                tableMechanicy.setItems(listMechanicy);



            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @FXML
    private Stage stage;
    @FXML
    private Scene scene;
    @FXML
    private Parent root;

    @FXML
    protected void goToCars(ActionEvent e) throws IOException
    {
        root = FXMLLoader.load(getClass().getResource("auta.fxml"));
        stage = (Stage)((Node)e.getSource()).getScene().getWindow();
        scene = new Scene(root);
        stage.setScene(scene);
        stage.show();

    }

    @FXML
    protected void goToMechanics(ActionEvent e) throws IOException
    {
        root = FXMLLoader.load(getClass().getResource("mechanicy.fxml"));
        stage = (Stage)((Node)e.getSource()).getScene().getWindow();
        scene = new Scene(root);
        stage.setScene(scene);
        stage.show();

    }

    @FXML
    protected void goToMain(ActionEvent e) throws IOException
    {
        root = FXMLLoader.load(getClass().getResource("hello-view.fxml"));
        stage = (Stage)((Node)e.getSource()).getScene().getWindow();
        scene = new Scene(root);
        stage.setScene(scene);
        stage.show();

    }
}

机械类:

package org.example.projekt;

public class mechanicy {

    private int id;
    private String name;
    private String surname;
    private String employmentdate;
    private String specialisation;

    public mechanicy(int id, String name, String surname, String employmentdate, String specialisation) {
        this.id = id;
        this.name = name;
        this.surname = surname;
        this.employmentdate = employmentdate;
        this.specialisation = specialisation;
    }

    public String getSpecialisation() {
        return specialisation;
    }

    public String getEmploymentdate() {
        return employmentdate;
    }

    public String getSurname() {
        return surname;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public void setEmploymentdate(String employmentdate) {
        this.employmentdate = employmentdate;
    }

    public void setSpecialisation(String specialisation) {
        this.specialisation = specialisation;
    }

}

还有mechanicy.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?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/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.example.projekt.HelloController">
   <bottom>
      <TabPane prefHeight="346.0" prefWidth="600.0" tabClosingPolicy="UNAVAILABLE" BorderPane.alignment="CENTER">
        <tabs>
          <Tab text="Dodaj pracownika">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="314.0" prefWidth="600.0">
                     <children>
                        <Label layoutX="60.0" layoutY="71.0" text="Label" />
                     </children></AnchorPane>
            </content>
          </Tab>
          <Tab text="Edytuj pracownika">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                     <children>
                        <Button layoutX="220.0" layoutY="49.0" mnemonicParsing="false" text="Button" />
                     </children></AnchorPane>
            </content>
          </Tab>
            <Tab text="Usuń pracownika">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
               </content>
            </Tab>
            <Tab text="Wyświetl pracownika">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                     <children>
                        <TableView fx:id="tableMechanicy" layoutX="14.0" layoutY="14.0" prefHeight="265.0" prefWidth="573.0">
                          <columns>
                            <TableColumn fx:id="idMechanicy" prefWidth="45.0" text="ID" />
                            <TableColumn fx:id="nameMechanicy" prefWidth="117.0" text="Imie" />
                              <TableColumn fx:id="surnameMechanicy" prefWidth="112.0" text="Nazwisko" />
                              <TableColumn fx:id="employmentMechanicy" prefWidth="148.0" text="Data zatrudnienia" />
                              <TableColumn fx:id="specialisationMechanicy" minWidth="7.0" prefWidth="150.0" text="Specjalizacja" />
                          </columns>
                        </TableView>
                     </children></AnchorPane>
               </content>
            </Tab>
            <Tab text="Wyszukaj pracownika">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
               </content>
            </Tab>
        </tabs>
      </TabPane>
   </bottom>
   <top>
      <Button mnemonicParsing="false" onAction="#goToMain" prefHeight="84.0" prefWidth="620.0" text="Powrót" BorderPane.alignment="CENTER">
         <font>
            <Font size="40.0" />
         </font>
      </Button>
   </top>
</BorderPane>

错误:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:118)
    at java.base/java.lang.reflect.Method.invoke(Method.java:580)
    at javafx.graphics@21/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics@21/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
    at java.base/java.lang.reflect.Method.invoke(Method.java:580)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1135)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics@21/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:893)
    at javafx.graphics@21/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
    at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: javafx.fxml.LoadException: 
/C:/Users/Kamil/IdeaProjects/projekt/target/classes/org/example/projekt/hello-view.fxml

    at javafx.fxml@21/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2722)
    at javafx.fxml@21/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2700)
    at javafx.fxml@21/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2563)
    at javafx.fxml@21/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2531)
    at org.example.projekt/org.example.projekt.HelloApplication.start(HelloApplication.java:15)
    at javafx.graphics@21/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:839)
    at javafx.graphics@21/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:483)
    at javafx.graphics@21/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:456)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
    at javafx.graphics@21/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:455)
    at javafx.graphics@21/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    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)
    ... 1 more
Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.control.TableColumn.setCellValueFactory(javafx.util.Callback)" because "this.idMechanicy" is null
    at org.example.projekt/org.example.projekt.HelloController.initialize(HelloController.java:75)
    at javafx.fxml@21/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2670)
    ... 12 more
Exception running application org.example.projekt.HelloApplication

我看了很多关于连接数据库和如何使用Tableview的教程,我只用我的变量和名称编写了相同的代码,但我总是遇到相同的错误

postgresql javafx jdbc nullpointerexception scenebuilder
1个回答
0
投票

看来 TableColumn

idMechanicy
可能未正确初始化,从而导致 NullPointerException。确认为 FXML 文件中的
fx:id
TableColumn 准确分配
idMechanicy
属性至关重要,确保它与控制器类中相应的字段名称匹配。

在您的

mechanicy.fxml
文件中,确保每个 TableColumn 都正确设置了
fx:id
属性。它应该与控制器类中的相应字段精确匹配。

确认

fx:id
属性设置正确后,请验证您是否在控制器中准确加载 FXML 文件。您可以通过在
idMechanicy
方法中打印出
initialize
的值来检查它是否为空来调试此问题。

此外,请仔细检查 FXML 文件和控制器类是否有任何拼写错误或拼写错误。即使很小的差异也会妨碍

fx:id
正确注入控制器。

© www.soinside.com 2019 - 2024. All rights reserved.