Как получить данные из базы данных Mariadb в таблицу через JavaFX? - PullRequest
0 голосов
/ 25 апреля 2019

Начал изучать язык Java.Мне очень понравилась технология Scene Builder.Я пытаюсь отобразить таблицу из базы данных MariaDB в графическом интерфейсе, но получаю ошибку, которая не может быть решена.Помогите пожалуйста, если вы понимаете.Я полностью сбросил код.

Main.java

package sample;

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

public class Main extends Application  {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("view/FXMLSample.fxml"));
        Scene scene = new Scene(root, 640,480);

        primaryStage.setScene(scene);
        primaryStage.setTitle("User list");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

controller / Controller.java

package sample.controller;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import sample.model.Person;
import sample.model.ConnectDB;

import javafx.scene.control.TableColumn;

import java.sql.*;

public class Controller implements Initializable {

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    private ObservableList<Person> usersData = FXCollections.observableArrayList();

    @FXML
    private TableView<Person> tableUsers;

    @FXML
    private TableColumn<Person, Integer> idColumn;

    @FXML
    private TableColumn<Person, String> usernameColumn;

    @FXML
    private TableColumn<Person, String> firstnameColumn;

    @FXML
    private TableColumn<Person, String> lastnameColumn;

    @FXML
    private TableColumn<Person, String> emailColumn;

    @FXML
    private TableColumn<Person, String> genderColumn;

    @FXML
    private TableColumn<Person, String> descColumn;

    @FXML
    private TableColumn<Person, String> createdonColumn;

    @FXML
    private TableColumn<Person, String> editedonColumn;

    @FXML
    private TableColumn<Person, String> activeColumn;

    @FXML
    public void initialize(URL location, ResourceBundle resources) {

        conn = ConnectDB.ConnectMariaDB();
        initData();

        tableUsers.setItems(usersData);

    }

    private void initData(ActionEvent event) throws SQLException {

        String sql = "SELECT * FROM test";
        rs = pst.executeQuery(sql);

        if(rs.next()) {
            int id = rs.getInt("id");
            String username = rs.getString("username");
            String firstname = rs.getString("firstname");
            String lastname = rs.getString("lastname");
            String email = rs.getString("email");
            String gender = rs.getString("gender");
            String description = rs.getString("description");
            String createdon = rs.getString("createdon");
            String editedon = rs.getString("editedon");
            String active = rs.getString("active");
            usersData.add(new Person(id, username, firstname, lastname, email, gender, description, createdon, editedon, active));
        }


    }


}

модель / ConnectDB.java

package sample.model;

import java.sql.*;

public class ConnectDB {

    Connection conn = null;

    public static Connection ConnectMariaDB() {
        try {
            Class.forName("org.mariadb.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost/test_new","root","123456");
            System.out.println("Connection success!");
            return conn;
        } catch(Exception e){
            System.out.println(e);
            return null;
        }
    }
}

модель / Person.java

package sample.model;

import javafx.beans.property.SimpleStringProperty;

public class Person {

    private int id;
    private String username;
    private String firstname;
    private String lastname;
    private String email;
    private String gender;
    private String description;
    private String createdon;
    private String editedon;
    private String active;

    public Person(int id, String username, String firstname, String lastname, String email, String gender, String description, String createdon, String editedon, String active) {
        this.id = id;
        this.username = username;
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.gender = gender;
        this.description = description;
        this.createdon = createdon;
        this.editedon = editedon;
        this.active = active;
    }

    public Person() {
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmail() {
        return email;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCreatedon() {
        return createdon;
    }

    public void setCreatedon(String createdon) {
        this.createdon = createdon;
    }

    public String getEditedon() {
        return editedon;
    }

    public void setEditedon(String editedon) {
        this.editedon = editedon;
    }

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        this.active = active;
    }
}

view / FXMLSample.fxml

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

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.Controller">
  <children>
    <MenuBar VBox.vgrow="NEVER">
      <menus>
        <Menu mnemonicParsing="false" text="File">
          <items>
            <MenuItem mnemonicParsing="false" text="New" />
            <MenuItem mnemonicParsing="false" text="Open…" />
            <Menu mnemonicParsing="false" text="Open Recent" />
            <SeparatorMenuItem mnemonicParsing="false" />
            <MenuItem mnemonicParsing="false" text="Close" />
            <MenuItem mnemonicParsing="false" text="Save" />
            <MenuItem mnemonicParsing="false" text="Save As…" />
            <MenuItem mnemonicParsing="false" text="Revert" />
            <SeparatorMenuItem mnemonicParsing="false" />
            <MenuItem mnemonicParsing="false" text="Preferences…" />
            <SeparatorMenuItem mnemonicParsing="false" />
            <MenuItem mnemonicParsing="false" text="Quit" />
          </items>
        </Menu>
        <Menu mnemonicParsing="false" text="Edit">
          <items>
            <MenuItem mnemonicParsing="false" text="Undo" />
            <MenuItem mnemonicParsing="false" text="Redo" />
            <SeparatorMenuItem mnemonicParsing="false" />
            <MenuItem mnemonicParsing="false" text="Cut" />
            <MenuItem mnemonicParsing="false" text="Copy" />
            <MenuItem mnemonicParsing="false" text="Paste" />
            <MenuItem mnemonicParsing="false" text="Delete" />
            <SeparatorMenuItem mnemonicParsing="false" />
            <MenuItem mnemonicParsing="false" text="Select All" />
            <MenuItem mnemonicParsing="false" text="Unselect All" />
          </items>
        </Menu>
        <Menu mnemonicParsing="false" text="Help">
          <items>
            <MenuItem mnemonicParsing="false" text="About MyHelloApp" />
          </items>
        </Menu>
      </menus>
    </MenuBar>
    <AnchorPane id="AnchorPane" maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2">
         <children>
            <Label layoutX="20.0" layoutY="14.0" text="Table" />
            <TableView fx:id="tableUsers" layoutX="20.0" layoutY="37.0" prefHeight="285.0" prefWidth="600.0">
              <columns>
                  <TableColumn prefWidth="42.0" text="ID" fx:id="idColumn" />
                  <TableColumn prefWidth="67.0" text="Username" fx:id="usernameColumn" />
                  <TableColumn prefWidth="156.0" text="Fullname">
                     <columns>
                        <TableColumn prefWidth="75.0" text="First name" fx:id="firstnameColumn" />
                        <TableColumn prefWidth="75.0" text="Last name" fx:id="lastnameColumn" />
                     </columns>
                  </TableColumn>
                <TableColumn prefWidth="75.0" text="E-mail" fx:id="emailColumn" />
                <TableColumn prefWidth="69.0" text="Gender" fx:id="genderColumn" />
                  <TableColumn prefWidth="69.0" text="Description" fx:id="descColumn" />
                  <TableColumn prefWidth="63.0" text="Created" fx:id="createdonColumn" />
                  <TableColumn minWidth="0.0" prefWidth="57.0" text="Edited" fx:id="editedonColumn" />
                  <TableColumn minWidth="4.0" prefWidth="105.0" text="Active" fx:id="activeColumn" />
              </columns>
            </TableView>
            <Button layoutX="23.0" layoutY="336.0" mnemonicParsing="false" text="Create" />
            <Button layoutX="88.0" layoutY="336.0" mnemonicParsing="false" text="Update" />
            <Button layoutX="154.0" layoutY="336.0" mnemonicParsing="false" text="Delete" />
            <Button layoutX="219.0" layoutY="336.0" mnemonicParsing="false" text="Refresh" />
         </children>
    </AnchorPane>
  </children>
</VBox>

Ошибка:

Ошибка: (64, 9) java: метод initData в классе sample.controller.Controller не может быть применен к данномутипы;обязательно: javafx.event.ActionEvent найдено: нет аргументов причина: фактические и формальные списки аргументов различаются по длине

Сделано теперь так

private void initData() throws SQLException {
...
}

, а также

@FXML
    public void initialize(URL location, ResourceBundle resources) {

        conn = ConnectDB.ConnectMariaDB();
        try {
            initData();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        tableUsers.setItems(usersData);

    }

В конце я выдал ошибку.

"C: \ Program Files \ Java \ jdk1.8.0_211 \ bin \ java.exe" "-javaagent: C: \ ProgramФайлы \ JetBrains \ IntelliJ IDEA Community Edition 2019.1 \ lib \ idea_rt.jar = 50017: C: \ Program Files \ JetBrains \ IntelliJ IDEA Community Edition 2019.1 \ bin "-Dfile.encoding = UTF-8 -classpath" C: \ Program Files\ Java \ jdk1.8.0_211 \ jre \ lib \ charsets.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ deploy.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \jre \ lib \ ext \ access-bridge-64.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ cldrdata.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \jre \ lib \ ext \ dnsns.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ jaccess.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ext \ jfxrt.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ localedata.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ nashorn.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ sunec.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre\ lib \ ext \ sunjce_provider.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ sunmscapi.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext\ sunpkcs11.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ ext \ zipfs.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ javaws.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ jce.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ jfr.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ jfxswt.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ jsse.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \management-agent.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ plugin.jar; C: \ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ resources.jar; C:\ Program Files \ Java \ jdk1.8.0_211 \ jre \ lib \ rt.jar; C: \ Projects \ JavaFXTest \ out \ production \ JavaFXTest; C: \ Users \ ccpraktikant \ Downloads \ mariadb-java-client-2.4.1.jar "sample.Main Подключение успешно!Исключительная ситуация в методе запуска приложенияjava: 43) на java.lang.reflect.Method.invoke (Method.java:498) на com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs (LauncherImpl.java:389) на com.sun.javafx.application.LauncherImp.launchApplication (LauncherImpl.java:328) при sun.reflect.NativeMethodAccessorImpl.invoke0 (нативный метод) при sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke (Method.java:498) в sun.launcher.LauncherHelper $ FXHelper.main (LauncherHelper.java:767) Причина: java.lang.RuntimeException: Исключение в методе запуска приложения вcom.sun.javafx.applicaion.LauncherImpl.launchApplication1 (LauncherImpl.java:917) на com.sun.javafx.application.LauncherImpl.lambda $ launchApplication $ 159 (LauncherImpl.java:182)at java.lang.Thread.run (Thread.java:748) Причина: javafx.fxml.LoadException: /C:/Projects/JavaFXTest/out/production/JavaFXTest/sample/view/FXMLSample.fxml

в javafx.fxml.FXMLLoader.constructLoadException (FXMLLoader.java:2601) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:2579) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:2441) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:3214) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:3175) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:3148) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:3124) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:3104) в javafx.fxml.FXMLLoader.load (FXMLLoader.java:3097) в sample.Main.start (Main.java:13) в com.sun.javafx.application.LauncherImpl.lambda $ launchApplication1 $ 166 (LauncherImpl.java:863) в com.sun.javafx.application.PlatformImpl.lambda $ runAndWait $ 179 (PlatformImpl.java:326) в com.sun.javafx.application.PlatformImpl.lambda $ обнулить $ 177 (PlatformImpl.java:295) в java.security.AccessController.doPrivileged (собственный метод) в com.sun.javafx.application.PlatformImpl.lambda $ runLater $ 178 (PlatformImpl.java:294) в com.sun.glass.ui.InvokeLaterDispatcher $ Future.run (InvokeLaterDispatcher.java:95) в com.sun.glass.ui.win.WinApplication._runLoop (собственный метод) в com.sun.glass.ui.win.WinApplication.lambda $ обнулить $ 152 (WinApplication.java:177) ... еще 1 причина: java.lang.NullPointerException at sample.controller.Controller.initData (Controller.java:77) в sample.controller.Controller.initialize (Controller.java:65) в javafx.fxml.FXMLLoader.loadImpl (FXMLLoader.java:2548) ... еще 17 Пример запуска приложения исключения. Основное

Процесс завершен с кодом выхода 1

Ответы [ 2 ]

2 голосов
/ 25 апреля 2019

Если вы посмотрите на

initData();

и ваш метод,

private void initData(ActionEvent event) throws SQLException {

, метод принимает параметры, а ваш вызов не имеет параметров.

Я предлагаю вам переписать свой метод без параметров.

private void initData() throws SQLException {
0 голосов
/ 26 апреля 2019

Я переписал контроллер следующим образом, и все заработало.

controller / Controller.java

package sample.controller;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import sample.model.Person;
import sample.model.ConnectDB;

import javafx.scene.control.TableColumn;

import java.sql.*;

public class Controller implements Initializable {

    Connection conn = null;
    ResultSet rs = null;
    Statement st = null;

    @FXML
    private URL location;

    @FXML
    private ResourceBundle resources;

    @FXML
    private TableView<Person> tableUsers;

    @FXML
    private TableColumn<Person, Integer> idColumn;

    @FXML
    private TableColumn<Person, String> usernameColumn;

    @FXML
    private TableColumn<Person, String> firstnameColumn;

    @FXML
    private TableColumn<Person, String> lastnameColumn;

    @FXML
    private TableColumn<Person, String> emailColumn;

    @FXML
    private TableColumn<Person, String> genderColumn;

    @FXML
    private TableColumn<Person, String> descColumn;

    @FXML
    private TableColumn<Person, String> createdonColumn;

    @FXML
    private TableColumn<Person, String> editedonColumn;

    @FXML
    private TableColumn<Person, String> activeColumn;

    @FXML
    public void initialize(URL location, ResourceBundle resources) {

        conn = ConnectDB.ConnectMariaDB();

        final ObservableList data = FXCollections.observableArrayList();

        String query = "SELECT * FROM test";

        Statement st = null;
        try {
            st = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        ResultSet rs = null;
        try {
            rs = st.executeQuery(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Person person;

        try {
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String firstname = rs.getString("firstname");
                String lastname = rs.getString("lastname");
                String email = rs.getString("email");
                String gender = rs.getString("gender");
                String description = rs.getString("description");
                String createdon = rs.getString("createdon");
                String editedon = rs.getString("editedon");
                String active = rs.getString("active");

                person = new Person(id,username,firstname,lastname,email,gender,description,createdon,editedon,active);
                data.add(person);
            }
            st.close();
        } catch(Exception  e) {
            System.out.println("There is an Exception.");
            System.out.println(e.getMessage());
        }
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        usernameColumn.setCellValueFactory(new PropertyValueFactory<>("username"));
        firstnameColumn.setCellValueFactory(new PropertyValueFactory<>("firstname"));
        lastnameColumn.setCellValueFactory(new PropertyValueFactory<>("lastname"));
        emailColumn.setCellValueFactory(new PropertyValueFactory<>("email"));
        genderColumn.setCellValueFactory(new PropertyValueFactory<>("gender"));
        descColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        createdonColumn.setCellValueFactory(new PropertyValueFactory<>("createdon"));
        editedonColumn.setCellValueFactory(new PropertyValueFactory<>("editedon"));
        activeColumn.setCellValueFactory(new PropertyValueFactory<>("active"));

        tableUsers.setItems(data);

    }

}
...