如何获取JavaFX tableview数据并保存到Mysql数据库

时间:2017-02-12 18:51:42

标签: java mysql javafx tableview fxml

我在FXML中使用javafx创建了一个表,它连接到我的数据库并填充值,我还有两个下拉列表,选择下拉值后,我在同一列中创建了一个按钮。我需要将已填充的值和下拉值保存到另一个数据库中。有没有办法做到这一点。

我附上了tableview和控件的图片。

我想按下“Just Save it”按钮。按下按钮我希望将相应按钮列中的列数据保存到数据库中。

enter image description here

package javafxapplication4;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;

    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.time.LocalDate;
    import java.util.ResourceBundle;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javafx.application.HostServices;
    import javafx.beans.property.ReadOnlyObjectWrapper;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.DatePicker;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.TablePosition;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.web.WebEngine;
    import javafx.scene.web.WebView;
    import javafx.util.Callback;
    import javafx.scene.control.Label;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.Button;
    import javafx.scene.control.Hyperlink;
    import javafx.scene.control.ListView;
    import javafx.scene.control.TextField;
    import javafx.scene.control.cell.TextFieldTableCell;

    /**
     * FXML Controller class
     *
     * @author ammydeen
     */
    public class FXMLController implements Initializable {

        public TableView tableView;
        public TableColumn col_id;
        public TableColumn date_column;
        public TableColumn task_column;
        public TableColumn bs_column;
        public TableColumn cold_column;
        public TableColumn sub_column;
        public TableColumn er_column;
        public TableColumn comp_column;
        ObservableList<Record> data = FXCollections.observableArrayList();
        @FXML
        public TableColumn error_sub_column;
        @FXML
        private DatePicker fdPicker;
        @FXML
        private DatePicker tdPicker;
        @FXML
        private TextField textFiel;
        public String fromDate;
        public String toDate;
        public String User_Id;
        public Hyperlink hyperlink;
        public ResultSet rs;
        public Connection conn;
        public WebView ewv;

        public WebEngine engine1;

        public ListView listView;

        public HostServices hos;
        @FXML
        public Label hiddenlable;
        @FXML
        private Button bluebutton;
        @FXML
        private Button coldbutton;

        public void initialize(URL url, ResourceBundle rb) {

            tableView.setEditable(true);

            tableView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
                    //Check whether item is selected and set value of selected item to Label
                    if (tableView.getSelectionModel().getSelectedItem() != null) {
                        TableView.TableViewSelectionModel selectionModel = tableView.getSelectionModel();
                        ObservableList selectedCells = selectionModel.getSelectedCells();
                        TablePosition tablePosition = (TablePosition) selectedCells.get(0);
                        Object val = tablePosition.getTableColumn().getCellData(newValue);
                        hiddenlable.setText((String) val);
                    }
                }
            });

            tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
            tableView.setSortPolicy((param) -> {
                return null; //To change body of generated lambdas, choose Tools | Templates.
            });

            bluebutton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    try {

                        String utt = hiddenlable.getText();
                        try {
                            Desktop.getDesktop().browse(new URI("https://www.google.com"));
                        } catch (URISyntaxException ex) {
                            Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            );
            coldbutton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    try {

                        String utt = hiddenlable.getText();
                        try {
                            Desktop.getDesktop().browse(new URI("www.google.com"));
                        } catch (URISyntaxException ex) {
                            Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            );

        }

        @FXML
        public void onAction(ActionEvent event) {

            LocalDate fDate = fdPicker.getValue();
            LocalDate tDate = tdPicker.getValue();
            fromDate = fDate.toString();
            toDate = tDate.toString();

            User_Id = textFiel.getText();
            System.out.println(User_Id);

            tableView.getSelectionModel().setCellSelectionEnabled(true);
            tableView.setEditable(true);
            data = FXCollections.observableArrayList();
            String s = "'";
            String d = "'";
            String frDate = s + fromDate + d;
            String trDate = s + toDate + d;
            String uId = s + User_Id + d;

            String query = "SELECT * FROM ecdb.ec_upload WHERE Transcriber_ID = " + uId + " and Date between " + frDate + " AND " + trDate;

            System.out.println(query);
            try {

                String u = "jdbc:mysql://localhost/ecdb";
                String use = "root";
                String pass = "root";

                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(u, use, pass);

                System.out.println("Test1");

                PreparedStatement st = conn.prepareStatement(query);
                ResultSet rs = st.executeQuery(query);
                while (rs.next()) {
                    data.add(new Record(rs.getString(2), rs.getString(3), rs.getString(6), rs.getString(7), rs.getString(8)));
                }
            } catch (Exception e) {
                System.out.println("Error in DB" + e);
            }

            tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
            col_id.setCellValueFactory(new Callback<CellDataFeatures<Record, String>, ObservableValue<String>>() {
                @Override
                public ObservableValue<String> call(CellDataFeatures<Record, String> p) {
                    return new ReadOnlyObjectWrapper(tableView.getItems().indexOf(p.getValue()) + "");
                }
            });

            col_id.setSortable(false);

            date_column.setCellValueFactory(new PropertyValueFactory<>("value_0"));

            task_column.setCellValueFactory(new PropertyValueFactory<>("value_1"));

            bs_column.setCellValueFactory(new PropertyValueFactory<>("value_2"));
            cold_column.setCellValueFactory(new PropertyValueFactory<>("value_3"));

            sub_column.setCellValueFactory(new PropertyValueFactory<>("Trial"));

            er_column.setCellValueFactory(new PropertyValueFactory<>("Trial"));

            error_sub_column.setCellValueFactory(new PropertyValueFactory<>("Trial"));

            comp_column.setCellValueFactory(new PropertyValueFactory<>("value_4"));

            comp_column.setCellFactory(TextFieldTableCell.<Record>forTableColumn());

            Callback<TableColumn<Record, String>, TableCell<Record, String>> errorFactory
                    = //
                    new Callback<TableColumn<Record, String>, TableCell<Record, String>>() {
                @Override
                public TableCell call(final TableColumn<Record, String> param) {
                    final TableCell<Record, String> cell = new TableCell<Record, String>() {

                        ObservableList<String> options
                                = FXCollections.observableArrayList(
                                        "Option 1",
                                        "Option 2",
                                        "Option 3"
                                );

                        final ComboBox comb = new ComboBox(options);

                        @Override
                        public void updateItem(String item, boolean empty) {
                            super.updateItem(item, empty);
                            if (empty) {
                                setGraphic(null);
                                setText(null);
                            } else {

                                //  System.out.println("This is working");
                                comb.setMaxWidth(Double.MAX_VALUE);
                                setGraphic(comb);
                                setText(null);
                            }
                        }
                    };
                    cell.setStyle("-fx-alignment: CENTER;");
                    return cell;
                }
            };

            Callback<TableColumn<Record, String>, TableCell<Record, String>> sub_errorFactory
                    = //
                    new Callback<TableColumn<Record, String>, TableCell<Record, String>>() {
                @Override
                public TableCell call(final TableColumn<Record, String> param) {
                    final TableCell<Record, String> cell = new TableCell<Record, String>() {

                        ObservableList<String> options
                                = FXCollections.observableArrayList(
                                        "Option 4",
                                        "Option 5",
                                        "Option 6"
                                );

                        public ComboBox comb = new ComboBox(options);

                        @Override
                        public void updateItem(String item, boolean empty) {
                            super.updateItem(item, empty);
                            if (empty) {
                                setGraphic(null);
                                setText(null);
                            } else {
                                String cmb = comb.getSelectionModel().getSelectedItem().toString();
                                System.out.println(cmb);
                                //System.out.println("This is working");
                                comb.setMaxWidth(Double.MAX_VALUE);
                                setGraphic(comb);
                                setText(null);
                            }
                        }
                    };

                    cell.setStyle("-fx-alignment: CENTER;");

                    return cell;
                }
            };

            Callback<TableColumn<Record, String>, TableCell<Record, String>> trialFactory
                    = //
                    new Callback<TableColumn<Record, String>, TableCell<Record, String>>() {
                @Override
                public TableCell call(final TableColumn<Record, String> param) {
                    final TableCell<Record, String> cell = new TableCell<Record, String>() {

                        final Button btn1 = new Button("Just Save It");

                        @Override
                        public void updateItem(String ite, boolean empty) {
                            super.updateItem(ite, empty);
                            if (empty) {
                                setGraphic(null);
                                setText(null);
                            } else {
                                btn1.setOnAction((ActionEvent t)
                                        -> {

                                    int selectdIndex = getTableRow().getIndex();
                                    System.out.println(selectdIndex);

                                    Record selectedRecord = (Record) tableView.getItems().get(selectdIndex);
                                    ObservableList<SubRecord> subDataList
                                            = FXCollections.observableArrayList(
                                                    new SubRecord(selectedRecord.getvalue_0(), selectedRecord.getvalue_1(), selectedRecord.getvalue_2(), selectedRecord.getvalue_3(), selectedRecord.getvalue_4()));

                                });
                                btn1.setMaxWidth(Double.MAX_VALUE);
                                setGraphic(btn1);
                                setText(null);
                            }
                        }
                    };
                    cell.setStyle("-fx-alignment: CENTER;");
                    return cell;
                }
            };

            error_sub_column.setCellFactory(sub_errorFactory);
            er_column.setCellFactory(errorFactory);
            sub_column.setCellFactory(trialFactory);
            tableView.setItems(data);

        }

    }

0 个答案:

没有答案