JavaFX-在表中不显示数据[更新的命名约定]

时间:2018-10-21 13:29:14

标签: java javafx

我正在尝试在JavaFx和SQL上创建项目。首先将打开登录屏幕,如果用户键入的用户名和密码与数据库中的用户名和密码相匹配,则将弹出``输入记录''窗口。在此窗口中,用户可以使用``保存''按钮添加客户详细信息并使用来显示数据“显示表”。 问题是虽然我可以将数据存储在数据库中,但是当我单击displaytable按钮时,没有显示数据。

我的主班 包装样品;

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);
    }
}

我的LOginMOdel类

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();
        }
    }
}

我的LoginSCreen类

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类

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;
        }
    }
}

我的AddRecord类

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类,我怀疑此类中存在问题。

   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();
        }


    }
}

用于ListCustomer类的FXML

<?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>

请帮助解决此问题。

0 个答案:

没有答案