1

I am trying to make a project on JavaFx and SQL. First the login screen will open ,if the username and password typed by user matches with the one in databases then 'enter record' window will pop up.In this window user can add customer details using 'save' button and also display the data using 'display table'. Problem is though I can store data in database but when I click of displaytable button no data is shown.

My Main Class package sample;

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

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("login1.fxml"));
            primaryStage.setTitle("NOVOTEL HOTEL ");
            primaryStage.setScene(new Scene(root, 500, 475));
            primaryStage.show();
        }
        catch(Exception e )
        {
            e.printStackTrace();
        }
    }


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

My LOginMOdel Class

package sample;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;

import java.sql.*;

public class LoginModel {
    int flag=0;

    @Nullable
    @NotNull
    Connection connection;

    public LoginModel() {
        connection = MysqlConnector.Connector();
    }

    public boolean isDBConnected() {
        try {
            boolean b = !connection.isClosed();
            return b;
        } catch (SQLException e) {
            e.printStackTrace();
            boolean c = false;
            return c;


        }

    }

    public boolean isLogin(String user, String pass) throws SQLException {
        PreparedStatement preparedstatement = null;
        ResultSet resultSet = null;
        String query = "select * from employee where employeename=? and employeepassword = ?";
        try {
            preparedstatement = connection.prepareStatement(query);
            preparedstatement.setString(1, user);
            preparedstatement.setString(2, pass);
            resultSet = preparedstatement.executeQuery();
            if (resultSet.next()) {
                flag=1;
                return true;
            }
            else{
                return false;
            }


        } catch (Exception e) {
            return false;
        } finally {
            preparedstatement.close();
            resultSet.close();
        }
    }
}

My LoginSCreen Class

package sample;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.*;
public class Controller  implements Initializable {
    @NotNull
    @Nullable
    public LoginModel loginModel = new LoginModel();
    @FXML

    private Label isConnected,db;
    @FXML
    private TextField txtUsername;
    @FXML
    private TextField txtpassword;

    @FXML
    Button abutton = new Button("Login");

    private AddCustomer  addCustomer;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
        if (loginModel.isDBConnected()) {
            db.setText("Connected to DATABASE");
        } else {
            db.setText("Not Connected");
        }
    }

    public void Login (ActionEvent event ) {
        try {
            if (loginModel.isLogin(txtUsername.getText(), txtpassword.getText())) {
                isConnected.setText("Correct");
                try {
                    FXMLLoader addCustomer= new FXMLLoader(getClass().getResource("/sample/addcustomer.fxml"));
                    Parent root1 = (Parent)addCustomer.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root1));
                    stage.setTitle("ENTRY RECORD");
                    stage.show();
                }
                catch (Exception e){
                    e.printStackTrace();
                }

            } else {
                Alert alert=new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("YOU ARE NOT AUTHENTICATED");
                alert.show();


            }
        } catch (SQLException e) {

            isConnected.setText("Incorrect");
            e.printStackTrace();
        }
    }

MysqlConnector Class

package sample;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import javafx.fxml.FXML;

import java.sql.*;


public class MysqlConnector {
    @FXML
    public static Statement stmt;
    @FXML
    public static Connection conn;




    public MysqlConnector() {
        conn=Connector();
        String TableName = "Customer_Details";
        try {
            stmt = conn.createStatement();
            DatabaseMetaData dbm = conn.getMetaData();
            ResultSet tables = dbm.getTables(null, null, TableName.toUpperCase(), null);
            if (tables.next()) {
                System.out.println("Ready to go");

            } else {
                stmt.execute("CREATE TABLE " + TableName + "("
                        + " customername varchar(45) primary key,"
                        + " customernumber varchar(45),\n"
                        + "  customerstay int,\n"
                        + "  customerguests varchar(45)"
                        + ")");
            }
        } catch (SQLException e1) {
            System.err.println(e1.getMessage());
        }
    }


    @Nullable
    @NotNull
    public static Connection Connector() {


        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "password");
            return conn;
        } catch (Exception e) {
            return null;
        }

    }
    @NotNull
    @Nullable
    public   ResultSet executeQuery(String query) {

        ResultSet result ;

        try {
             stmt = conn.createStatement();
            result=stmt.executeQuery(query);



        } catch (SQLException e) {
            System.out.println("Error here");
            e.printStackTrace();
            return null;

        }
        return result;
    }
    @NotNull
    @Nullable
    public boolean executeAction(String qu) {
        try {
            stmt = conn.createStatement();
            stmt.execute(qu);
            return true;


        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}

My AddRecord Class

package sample;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public   class AddCustomer {
    @FXML
    public TextField number;
    @FXML
    public TextField name;
    @FXML
    public TextField stay;
    @FXML
    public TextField noofguests;
    @FXML
    public Button savebutton;
    @FXML
    public Button cancelbutton;
    @FXML
    @NotNull
    @Nullable
    public  void addcustomer(ActionEvent actionEvent) throws Exception {


            String customername = name.getText();
            String customernumber = number.getText();
            String customerstay = stay.getText();
            String customerguests = noofguests.getText();
            if (customername.isEmpty() || customerguests.isEmpty() || customernumber.isEmpty() || customerstay.isEmpty()) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("PLEASE ENTER ALL THE FIELDS");
                alert.show();
                return;

            }

            String qu = "INSERT INTO Customer_Details VALUES(" + "'" + customername + "'," +
                    "'" + customernumber + "'," +
                    "'" + customerstay + "'," +
                    "'" + customerguests + "'" + ")";
            System.out.println(qu);

        @NotNull
        @Nullable
        MysqlConnector mysqlConnector=new MysqlConnector();
        try {

            if (mysqlConnector.executeAction(qu)) {
                @NotNull
                @Nullable
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText(null);
                alert.setContentText("SUCCESS");
                alert.show();
            } else {
                @NotNull
                @Nullable
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("FAILED");
                alert.show();
            }
        }
        catch(Exception e)
        { e.printStackTrace();}

    }
    public void displaydata(ActionEvent actionEvent) {
        try {
            FXMLLoader addCustomer= new FXMLLoader(getClass().getResource("/sample/List View.fxml"));
            Parent root1 = (Parent)addCustomer.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root1));
            stage.setTitle("DISPLAY RECORD");
            stage.show();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

ListCustomer Class , I suspect issue in this class.

   package sample;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.awt.print.Book;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class ListCustomers implements Initializable {
    ObservableList<Hotel> list= FXCollections.observableArrayList();
    public TableView<Hotel> tableView;
    public TableColumn<Hotel, String> namecolumn;
    public TableColumn<Hotel, String> numbercolumn;
    public TableColumn<Hotel, String> staycolumn;
    public TableColumn<Hotel, String> guestscolumn;

    public void initialize(URL location, ResourceBundle resources) {
        initCol();

        loadData();
    }

    private void loadData() {
        MysqlConnector mysqlConnector=new MysqlConnector();
        String qu = "SELECT * FROM Customer_Details";
        ResultSet rs = mysqlConnector.executeQuery(qu);
        try {
            while (rs.next()) {
                String name = rs.getString("customername");
                String number = rs.getString("customernumber");
                String stay= rs.getString("customerstay");
                String guests = rs.getString("customerguests");

                list.add(new Hotel(name,number,stay,guests));

            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        tableView.getItems().setAll(list);
    }

    private void initCol(){
        namecolumn.setCellValueFactory(new PropertyValueFactory<Hotel, String>("Name"));
        numbercolumn.setCellValueFactory(new PropertyValueFactory<Hotel, String>("Number"));
        staycolumn.setCellValueFactory(new PropertyValueFactory<Hotel, String>("Stay Period"));
        guestscolumn.setCellValueFactory(new PropertyValueFactory<Hotel, String>("Guests"));

    }

    public static class Hotel {

        private final SimpleStringProperty CustomerName;
        private final SimpleStringProperty CustomerNumber;
        private final SimpleStringProperty CustomerStay;
        private final SimpleStringProperty CustomerGuests;


        public Hotel(String customername, String customernumber, String customerstay, String customerguests) {
            this.CustomerName = new SimpleStringProperty(customername);
            this.CustomerNumber = new SimpleStringProperty(customernumber);
            this.CustomerGuests = new SimpleStringProperty(customerstay);
            this.CustomerStay = new SimpleStringProperty(customerguests);

        }

        public String getCustomerName() {
            return CustomerName.get();
        }

        public String getCustomerNumber() {
            return CustomerNumber.get();
        }

        public void setCustomerName(String CustomerName) {
            this.CustomerName.set(CustomerName);
        }

        public void setCustomerNumber(String CustomerNumber) {
            this.CustomerNumber.set(CustomerNumber);
        }

        public void setCustomerStay(String CustomerStay) {
            this.CustomerStay.set(CustomerStay);
        }

        public void setCustomerGuests(String CustomerGuests) {
            this.CustomerGuests.set(CustomerGuests);
        }

        public String getCustomerStay() {
            return CustomerStay.get();
        }

        public String getCustomerGuests() {
            return CustomerGuests.get();
        }


    }
}

FXML for ListCustomer Class

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

<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.ListCustomers">
   <children>
      <TableView fx:id="tableView" layoutX="8.0" layoutY="6.0" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
        <columns>
          <TableColumn fx:id="namecolumn" prefWidth="75.0" text="Customer Name" />
          <TableColumn fx:id="numbercolumn" prefWidth="75.0" text="Contact Number" />
            <TableColumn fx:id="staycolumn" prefWidth="75.0" text="Stay Period (Days)" />
            <TableColumn fx:id="guestscolumn" prefWidth="75.0" text="Total Guests" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
   </children>
</AnchorPane>

PLease help with this issue.

ThatMan
  • 115
  • 8
  • Still can't get through answers ,a solution to the problem would be appreciated . – ThatMan Oct 21 '18 at 13:42
  • updated the question .Please Check – ThatMan Oct 21 '18 at 14:05
  • the PropertyValueFactory takes the name of the property (_not_ the title of the column) - and better not use it at all: instead, expose the property in your data class (vs. mere getters/setters) and use them in a custom cellValueFactory, have a look at some recent QAs that demonstrate how-to do it. – kleopatra Oct 21 '18 at 14:18
  • THANKS it WORKED!!!(changed "stay period" to "stay") I was literally searching all round the code for hours . – ThatMan Oct 21 '18 at 14:49

0 Answers0