Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package simpledatabasefx;
  2.  
  3.  
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10. import javafx.application.Application;
  11. import javafx.collections.FXCollections;
  12. import javafx.collections.ObservableList;
  13. import javafx.event.ActionEvent;
  14. import javafx.geometry.Insets;
  15. import javafx.geometry.Orientation;
  16. import javafx.geometry.Pos;
  17. import javafx.scene.Scene;
  18. import javafx.scene.control.Button;
  19. import javafx.scene.control.Label;
  20. import javafx.scene.control.SplitPane;
  21. import javafx.scene.control.TableColumn;
  22. import javafx.scene.control.TableView;
  23. import static javafx.scene.control.TableView.CONSTRAINED_RESIZE_POLICY;
  24. import javafx.scene.control.TextField;
  25. import javafx.scene.control.cell.PropertyValueFactory;
  26. import javafx.scene.input.KeyEvent;
  27. import javafx.scene.input.MouseEvent;
  28. import javafx.scene.layout.AnchorPane;
  29. import javafx.scene.layout.Background;
  30. import javafx.scene.layout.BackgroundFill;
  31. import javafx.scene.layout.Border;
  32. import javafx.scene.layout.BorderStroke;
  33. import javafx.scene.layout.BorderStrokeStyle;
  34. import javafx.scene.layout.BorderWidths;
  35. import javafx.scene.layout.CornerRadii;
  36. import javafx.scene.layout.GridPane;
  37. import javafx.scene.layout.HBox;
  38. import javafx.scene.layout.VBox;
  39. import javafx.scene.paint.Color;
  40. import javafx.scene.text.Font;
  41. import javafx.scene.text.FontWeight;
  42. import javafx.scene.text.Text;
  43. import javafx.stage.Stage;
  44. import simpledatabasefx.connectdb.DatabaseConnect;
  45. import simpledatabasefx.model.modelDatabase;
  46.  
  47. /**
  48.  *
  49.  * @author arief
  50.  */
  51.  
  52. /**
  53.  * Modifikasi dari kode sumber
  54.  * http://fx-007.blogspot.com/2014/11/crud-javafx.html (SceneBuilder 2.0)
  55.  **/
  56. public class SimpleDatabaseFX extends Application {
  57.     public TableView tblView;
  58.     private Text txtInfo;
  59.     private Label lblTitle,lblData,lblNIM,lblNAMA,lblJURUSAN,lblALAMAT,lblCari;
  60.     public TextField txtNIM,txtNAMA,txtJURUSAN,txtALAMAT,txtCARI;
  61.     public TableColumn tblColumn1,tblColumn2,tblColumn3,tblColumn4;
  62.     private SplitPane splitPaneH;
  63.     private VBox panevbox,panevbox2;
  64.     private AnchorPane pane;
  65.     private GridPane grid;
  66.     private HBox panehbox,searchbox;
  67.     private Button btnAdd,btnUpdate,btnDelete,btnClear,btnClose,btnRefresh;
  68.     modelDatabase modelDb;
  69.     ObservableList data = FXCollections.observableArrayList();
  70.    
  71.     public void initComponent(){
  72.       //========================================================================
  73.         lblData    = new Label("FORM DATA");
  74.         lblTitle   = new Label();
  75.         lblNIM     = new Label("NIM");
  76.         lblNAMA    = new Label("NAMA");
  77.         lblJURUSAN = new Label("JURUSAN");
  78.         lblALAMAT  = new Label("ALAMAT");
  79.         lblCari    = new Label("CARI DATA :");
  80.         txtInfo    = new Text("No data");
  81.         tblColumn1 = new TableColumn("NIM");
  82.         tblColumn2 = new TableColumn("NAMA");
  83.         tblColumn3 = new TableColumn("JURUSAN");
  84.         tblColumn4 = new TableColumn("ALAMAT");
  85.         txtNIM     = new TextField();
  86.         txtNAMA    = new TextField();
  87.         txtJURUSAN = new TextField();
  88.         txtALAMAT  = new TextField();
  89.         txtCARI    = new TextField();
  90.         splitPaneH = new SplitPane();
  91.         pane       = new AnchorPane();
  92.         panevbox   = new VBox();
  93.         panevbox2  = new VBox();
  94.         grid       = new GridPane();
  95.         panehbox   = new HBox(5);
  96.         searchbox  = new HBox(5);
  97.         tblView    = new TableView();
  98.         btnAdd     = new Button("ADD");
  99.         btnUpdate  = new Button("UPDATE");
  100.         btnDelete  = new Button("DELETE");
  101.         btnClear   = new Button("CLEAR");
  102.         btnClose   = new Button("CLOSE");
  103.         btnRefresh = new Button("REFRESH");
  104.       //========================================================================
  105.         tblColumn1.setCellValueFactory(new PropertyValueFactory("nim"));
  106.         tblColumn2.setCellValueFactory(new PropertyValueFactory("nama"));
  107.         tblColumn3.setCellValueFactory(new PropertyValueFactory("jurusan"));
  108.         tblColumn4.setCellValueFactory(new PropertyValueFactory("alamat"));
  109.        
  110.         txtNIM.setPromptText("Masukkan NIM Anda");
  111.         txtNAMA.setPromptText("Masukkan Nama Anda");
  112.         txtJURUSAN.setPromptText("Masukkan Jurusan Anda");
  113.         txtALAMAT.setPromptText("Masukkan Alamat Anda");
  114.         txtCARI.setPromptText("Masukkan data yang ingin dicari");
  115.        
  116.         lblCari.setPadding(new Insets(10));
  117.         lblCari.setFont(Font.font("Comic Sans MS", FontWeight.MEDIUM, 12));
  118.         lblCari.setAlignment(Pos.CENTER);
  119.         lblCari.setUnderline(true);
  120.        
  121.         lblData.setPadding(new Insets(10));
  122.         lblData.setFont(Font.font("Comic Sans MS", FontWeight.MEDIUM, 22));
  123.         lblData.setUnderline(true);
  124.         lblData.setAlignment(Pos.CENTER);
  125.        
  126.         lblTitle.setText("Database Universitas");
  127.         lblTitle.setUnderline(true);
  128.         lblTitle.setPadding(new Insets(10));
  129.         lblTitle.setFont(Font.font("Comic Sans MS", FontWeight.MEDIUM, 22));
  130.         lblTitle.setAlignment(Pos.CENTER);
  131.        
  132.         lblNIM.setPrefSize(100, 30);
  133.         lblNAMA.setPrefSize(100, 30);
  134.         lblJURUSAN.setPrefSize(100, 30);
  135.         lblALAMAT.setPrefSize(100, 30);
  136.        
  137.         txtNIM.setPrefSize(250, 30);
  138.         txtNAMA.setPrefSize(250, 30);
  139.         txtJURUSAN.setPrefSize(250, 30);
  140.         txtALAMAT.setPrefSize(250, 30);
  141.         txtCARI.setPrefSize(250, 30);
  142.        
  143.         tblView.setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY);
  144.         tblView.setPlaceholder(txtInfo);
  145.         tblView.setPadding(new Insets(10));
  146.         tblView.getColumns().addAll(tblColumn1,tblColumn2,tblColumn3,tblColumn4);
  147.         tblView.setPrefHeight(250);
  148.         tblView.setBackground(new Background(
  149.                 new BackgroundFill(Color.LIGHTBLUE,new CornerRadii(15),Insets.EMPTY)));
  150.        
  151.         panehbox.setAlignment(Pos.CENTER);
  152.         panehbox.setPadding(new Insets(10));
  153.         panehbox.setLayoutX(23);
  154.         panehbox.setLayoutY(194);
  155.         panehbox.getChildren().addAll(btnAdd,btnUpdate,btnDelete,btnClear,btnClose);
  156.         panehbox.setBackground(new Background(new BackgroundFill(
  157.                 Color.DARKGRAY, new CornerRadii(10), Insets.EMPTY)));
  158.        
  159.         searchbox.setAlignment(Pos.CENTER_LEFT);
  160.         searchbox.setPadding(new Insets(5));
  161.         searchbox.getChildren().addAll(lblCari,txtCARI,btnRefresh);
  162.         searchbox.setBackground(new Background(new BackgroundFill(
  163.                 Color.DARKGRAY, new CornerRadii(10), Insets.EMPTY)));
  164.        
  165.         grid.setHgap(10);
  166.         grid.setVgap(10);
  167.         grid.setLayoutX(5);
  168.         grid.setLayoutY(5);
  169.         grid.setAlignment(Pos.CENTER);
  170.         grid.setPadding(new Insets(10));
  171.         grid.addRow(0, lblNIM,txtNIM);
  172.         grid.addRow(1, lblNAMA,txtNAMA);
  173.         grid.addRow(2, lblJURUSAN,txtJURUSAN);
  174.         grid.addRow(3, lblALAMAT,txtALAMAT);
  175.         grid.setGridLinesVisible(false);
  176.        
  177.         pane.setBorder(new Border(new BorderStroke(
  178.                 Color.WHITESMOKE,BorderStrokeStyle.DASHED,
  179.                 new CornerRadii(15),new BorderWidths(5),Insets.EMPTY)));
  180.         pane.setBackground(new Background(new BackgroundFill(
  181.                 Color.LIGHTGRAY, new CornerRadii(15),Insets.EMPTY)));
  182.         pane.getChildren().addAll(grid,panehbox);
  183.        
  184.         panevbox.getChildren().addAll(lblTitle,tblView,searchbox);
  185.         panevbox.setPadding(new  Insets(5));
  186.         panevbox.setSpacing(5);
  187.         panevbox.minWidthProperty().bind(splitPaneH.widthProperty().multiply(0.70));
  188.         panevbox.maxWidthProperty().bind(splitPaneH.widthProperty().multiply(0.70));
  189.        
  190.         panevbox2.getChildren().addAll(lblData,pane);
  191.         panevbox2.setPadding(new Insets(5));
  192.         panevbox2.setSpacing(5);
  193.        
  194.         splitPaneH.setOrientation(Orientation.HORIZONTAL);
  195.         splitPaneH.getItems().addAll(panevbox,panevbox2);
  196.         splitPaneH.setPadding(new Insets(2));
  197.         splitPaneH.setBackground(new Background(
  198.                    new BackgroundFill(Color.GRAY,CornerRadii.EMPTY,Insets.EMPTY)));
  199.         splitPaneH.setDividerPositions(0.5);
  200.     }
  201.     /**=======================================================================================
  202.      *                       UNTUK MENAMPUNG DATA DARI DATABASE
  203.      * =======================================================================================
  204.      **/
  205.    
  206.     /**
  207.     * @return
  208.     **/
  209.     private ObservableList loadData(){
  210.             ObservableList listData = FXCollections.observableArrayList();
  211.             try {
  212.             Connection c    = DatabaseConnect.tryConnect();
  213.             String sql1     = "select * from mhs;";
  214.             ResultSet rs1   = c.createStatement().executeQuery(sql1);
  215.             while(rs1.next()){
  216.                 modelDb         = new modelDatabase(rs1.getString(1),rs1.getString(2),
  217.                                                     rs1.getString(3),rs1.getString(4));
  218.                 listData.add(modelDb);
  219.             }
  220.         } catch (SQLException ex) {
  221.             Logger.getLogger(SimpleDatabaseFX.class.getName()).log(Level.SEVERE, null, ex);
  222.         }
  223.             return listData;
  224.            
  225.     }
  226.    
  227.     private ObservableList searchByNIM(String n){
  228.         ObservableList listData = FXCollections.observableArrayList();
  229.         try {
  230.             Connection c = DatabaseConnect.tryConnect();
  231.             String sql2 = " select distinct * from mhs where nim like '%"+n+"%';";
  232.             ResultSet rs2 = c.createStatement().executeQuery(sql2);
  233.             while(rs2.next()){
  234.                 modelDb         = new modelDatabase(rs2.getString(1),rs2.getString(2),
  235.                                                     rs2.getString(3),rs2.getString(4));
  236.                 listData.add(modelDb);
  237.             }
  238.         } catch (SQLException ex) {
  239.             Logger.getLogger(SimpleDatabaseFX.class.getName()).log(Level.SEVERE, null, ex);
  240.         }
  241.         return listData;
  242.     }
  243.     //=======================================================================================
  244.    
  245.     /**======================================================================================
  246.      *                      UNTUK MELAKUKAN INSERT, DELETE DAN UPDATE
  247.      *              DIMANA DATA DIAMBIL DARI FORM KEMUDIAN DIKUMPULKAN DI MODEL
  248.      * ======================================================================================
  249.      **/
  250.     private void insert(modelDatabase m){
  251.         Connection c = DatabaseConnect.tryConnect();
  252.         PreparedStatement ps;
  253.         try {
  254.             String sql = "insert into mhs values (?,?,?,?);";
  255.             ps  = c.prepareStatement(sql);
  256.             ps.setString(1,m.getNim());
  257.             ps.setString(2,m.getNama());
  258.             ps.setString(3,m.getJurusan());
  259.             ps.setString(4,m.getAlamat());
  260.             ps.execute();
  261.         } catch (SQLException ex) {
  262.             Logger.getLogger(SimpleDatabaseFX.class.getName()).log(Level.SEVERE, null, ex);
  263.             System.out.println("Error");
  264.         }
  265.     }
  266.    
  267.     private void delete(modelDatabase m){
  268.         try {
  269.             Connection c = DatabaseConnect.tryConnect();
  270.             PreparedStatement ps;
  271.             String sql = "delete from mhs where nim = ?;";
  272.             ps = c.prepareStatement(sql);
  273.             ps.setString(1, m.getNim());
  274.             ps.execute();
  275.         } catch (SQLException ex) {
  276.             Logger.getLogger(SimpleDatabaseFX.class.getName()).log(Level.SEVERE, null, ex);
  277.         }
  278.        
  279.     }
  280.    
  281.     private void update(modelDatabase m){
  282.         try {
  283.             Connection c = DatabaseConnect.tryConnect();
  284.             PreparedStatement ps;
  285.             String sql = "update mhs set nama = ? ,jurusan = ? , alamat = ? where nim = ? ;";
  286.             ps = c.prepareStatement(sql);
  287.             ps.setString(1, m.getNama());
  288.             ps.setString(2, m.getJurusan());
  289.             ps.setString(3, m.getAlamat());
  290.             ps.setString(4, m.getNim());
  291.             ps.execute();
  292.         } catch (SQLException ex) {
  293.             Logger.getLogger(SimpleDatabaseFX.class.getName()).log(Level.SEVERE, null, ex);
  294.         }
  295.     }
  296.     //=======================================================================================
  297.    
  298.     /**======================================================================================
  299.      *                                   ACTIONEVENT  
  300.      * ======================================================================================
  301.      **/
  302.     private void selectData(){
  303.         modelDb = (modelDatabase) tblView.getSelectionModel().getSelectedItems().get(0);
  304.         txtNIM.setText(modelDb.getNim());
  305.         txtNAMA.setText(modelDb.getNama());
  306.         txtJURUSAN.setText(modelDb.getJurusan());
  307.         txtALAMAT.setText(modelDb.getAlamat());
  308.         txtNIM.setDisable(true);
  309.     }
  310.    
  311.     private void deleteData(){
  312.         modelDb = new modelDatabase(txtNIM.getText(), "", "", "");
  313.         delete(modelDb);
  314.         clearData();
  315.         showData();
  316.     }
  317.    
  318.     private void updateData(){
  319.         modelDb = new modelDatabase(txtNIM.getText(),txtNAMA.getText(),
  320.                                     txtJURUSAN.getText(),txtALAMAT.getText());
  321.         update(modelDb);
  322.         clearData();
  323.         showData();
  324.     }
  325.    
  326.     private void searchbyNIM(){
  327.         data.clear(); // <- menghapus data pada penampung data
  328.         data = searchByNIM(txtCARI.getText().trim());
  329.         tblView.setItems(data); // <- menaruh data pada tabel agar bisa tampil
  330.         tblView.getSelectionModel().clearSelection(); // <- menghapus seleksi baris pada tabel
  331.     }
  332.    
  333.     private void refresh(){
  334.         showData();
  335.         clearData();
  336.         txtCARI.clear();
  337.     }
  338.    
  339.     private void showData(){
  340.         data.clear();
  341.         data = loadData();
  342.         tblView.setItems(data);
  343.         tblView.getSelectionModel().clearSelection();
  344.     }
  345.    
  346.     private void clearData(){
  347.         txtNIM.clear();
  348.         txtNAMA.clear();
  349.         txtJURUSAN.clear();
  350.         txtALAMAT.clear();
  351.         txtNIM.setDisable(false);
  352.         tblView.getSelectionModel().clearSelection();
  353.     }
  354.    
  355.     private void addData(){
  356.         // mengambil data dari form, kemudian disusun seperti array
  357.         modelDb = new modelDatabase(txtNIM.getText(),txtNAMA.getText(),
  358.                                     txtJURUSAN.getText(),txtALAMAT.getText());
  359.         insert(modelDb); //<- data dikirim ke SQL
  360.         showData();
  361.         clearData();
  362.     }
  363.   //====================================================================================    
  364.     @Override
  365.     public void start(Stage primaryStage) {
  366.         initComponent(); // <- VIEW
  367.         showData();     // <- MENAMPILKAN DATA
  368.         tblView.setOnMousePressed((MouseEvent event) -> {
  369.             selectData(); // <- EVENT BARIS KETIKA DIPILIH
  370.         });
  371.         btnAdd.setOnAction((ActionEvent e) -> {
  372.             addData(); // <- INSERT DATA
  373.         });
  374.         btnClear.setOnAction((ActionEvent e) -> {
  375.             clearData(); // <- CLEAR FIELD INPUT DATA
  376.         });
  377.         btnClose.setOnAction((ActionEvent e) -> {
  378.             primaryStage.close(); // <- CLOSE SCENE WINDOW
  379.         });
  380.         btnUpdate.setOnAction((ActionEvent e) -> {
  381.             updateData(); // <- UPDATE DATA
  382.         });
  383.         btnDelete.setOnAction((ActionEvent e) -> {
  384.             deleteData(); // <- DELETE DATA
  385.         });
  386.         btnRefresh.setOnAction((ActionEvent e) -> {
  387.             refresh(); // <- MENGEMBALIKAN TAMPILAN SEPERTI SEMULA
  388.         });
  389.         txtCARI.setOnKeyTyped((KeyEvent ke) -> {
  390.             searchbyNIM(); // <- SEARCH DATA BY NIM
  391.         });
  392.         Scene scene = new Scene(splitPaneH, 1366, 768);
  393.         primaryStage.setTitle("APLIKASI SIMPLE DATABASE FX");
  394.         primaryStage.setScene(scene);
  395.         primaryStage.show();
  396.     }
  397.  
  398.     /**
  399.      * @param args the command line arguments
  400.      */
  401.     public static void main(String[] args) {
  402.        
  403.         launch(args);
  404.        
  405.     }
  406.    
  407. }