Advertisement
Guest User

hehehe

a guest
Jan 27th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.76 KB | None | 0 0
  1.  
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import javax.swing.JOptionPane;
  8. import javax.swing.table.DefaultTableModel;
  9. import javax.swing.table.TableModel;
  10.  
  11.  
  12.  
  13.  
  14. /*
  15.  * To change this license header, choose License Headers in Project Properties.
  16.  * To change this template file, choose Tools | Templates
  17.  * and open the template in the editor.
  18.  */
  19.  
  20. /**
  21.  *
  22.  * @author ASUS
  23.  */
  24. public class databuku extends javax.swing.JFrame {
  25.  
  26.     /**
  27.      * Creates new form databuku
  28.      */
  29.     public databuku() {
  30.         initComponents();
  31.         Show_Users_In_JTable();
  32.     }
  33.    
  34.     public Connection getConnection()
  35.     {
  36.        Connection con;
  37.        
  38.        try {
  39.            con = DriverManager.getConnection("jdbc:mysql://localhost/mylibrary","root","");
  40.            return con;
  41.        }catch(Exception e){
  42.            e.printStackTrace();
  43.            return null;
  44.        }
  45.     }
  46.    
  47.     public ArrayList<User> getUsersList()
  48.     {
  49.         ArrayList<User> usersList = new ArrayList<User>();
  50.         Connection connection = getConnection();
  51.        
  52.         String query = "SELECT * FROM databuku";
  53.         Statement st;
  54.         ResultSet rs;
  55.        
  56.         try{
  57.             st = connection.createStatement();
  58.             rs = st.executeQuery(query);
  59.             User user;
  60.             while(rs.next())
  61.             {
  62.                 user = new User(rs.getInt("id"),rs.getString("judul"),rs.getString("pengarang"),rs.getInt("stok"));
  63.                 usersList.add(user);
  64.             }
  65.         } catch (Exception e){
  66.             e.printStackTrace();
  67.         }
  68.         return usersList;
  69.     }
  70.    
  71.     //Execute the Sql Query
  72.    
  73.     public void executeSQLQuery(String query, String message)
  74.     {
  75.         Connection con = getConnection();
  76.         Statement st;
  77.         try{
  78.             st = con.createStatement();
  79.             if ((st.executeUpdate(query)) == 1)
  80.             {
  81.                 //refresh jtable data
  82.                 DefaultTableModel model = (DefaultTableModel)tabeldatabuku.getModel();
  83.                 model.setRowCount(0);
  84.                
  85.                 Show_Users_In_JTable();
  86.  
  87.                 JOptionPane.showMessageDialog(null , "Data "+message+" Successfully");
  88.             }else{
  89.                 JOptionPane.showMessageDialog(null, "Data Not "+message);
  90.             }
  91.         }catch (Exception ex){
  92.             ex.printStackTrace();
  93.         }
  94.     }
  95.    
  96.    
  97.     //display data from sql to jtable
  98.    
  99.     public void Show_Users_In_JTable(){
  100.         ArrayList<User> list = getUsersList();
  101.         DefaultTableModel model = (DefaultTableModel)tabeldatabuku.getModel();
  102.  
  103.         Object[] row = new Object[4];
  104.         for(int i = 0; i < list.size(); i++)
  105.         {
  106.             row[0] = list.get(i).getId();
  107.             row[1] = list.get(i).getJudulBuku();
  108.             row[2] = list.get(i).getPengarang();
  109.             row[3] = list.get(i).getStok();
  110.            
  111.             model.addRow(row);
  112.         }
  113.     }
  114.  
  115.  
  116.    
  117.    
  118.     /**
  119.      * This method is called from within the constructor to initialize the form.
  120.      * WARNING: Do NOT modify this code. The content of this method is always
  121.      * regenerated by the Form Editor.
  122.      */
  123.     @SuppressWarnings("unchecked")
  124.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  125.     private void initComponents() {
  126.  
  127.         id = new javax.swing.JTextField();
  128.         jPanel1 = new javax.swing.JPanel();
  129.         jLabel1 = new javax.swing.JLabel();
  130.         jLabel2 = new javax.swing.JLabel();
  131.         jLabel3 = new javax.swing.JLabel();
  132.         judulbuku_field = new javax.swing.JTextField();
  133.         pengarang_field = new javax.swing.JTextField();
  134.         stok_field = new javax.swing.JTextField();
  135.         insert = new javax.swing.JButton();
  136.         update = new javax.swing.JButton();
  137.         delete = new javax.swing.JButton();
  138.         jScrollPane1 = new javax.swing.JScrollPane();
  139.         tabeldatabuku = new javax.swing.JTable();
  140.  
  141.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  142.  
  143.         jPanel1.setBackground(new java.awt.Color(0, 204, 255));
  144.  
  145.         jLabel1.setText("Judul Buku : ");
  146.  
  147.         jLabel2.setText("Pengarang :");
  148.  
  149.         jLabel3.setText("Stok           :");
  150.  
  151.         pengarang_field.addActionListener(new java.awt.event.ActionListener() {
  152.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  153.                 pengarang_fieldActionPerformed(evt);
  154.             }
  155.         });
  156.  
  157.         insert.setText("INSERT");
  158.         insert.addActionListener(new java.awt.event.ActionListener() {
  159.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  160.                 insertActionPerformed(evt);
  161.             }
  162.         });
  163.  
  164.         update.setText("UPDATE");
  165.         update.addActionListener(new java.awt.event.ActionListener() {
  166.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  167.                 updateActionPerformed(evt);
  168.             }
  169.         });
  170.  
  171.         delete.setText("DELETE");
  172.         delete.addActionListener(new java.awt.event.ActionListener() {
  173.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  174.                 deleteActionPerformed(evt);
  175.             }
  176.         });
  177.  
  178.         tabeldatabuku.setModel(new javax.swing.table.DefaultTableModel(
  179.             new Object [][] {
  180.  
  181.             },
  182.             new String [] {
  183.                 "id", "judul", "pengarang", "stok"
  184.             }
  185.         ) {
  186.             boolean[] canEdit = new boolean [] {
  187.                 false, false, false, false
  188.             };
  189.  
  190.             public boolean isCellEditable(int rowIndex, int columnIndex) {
  191.                 return canEdit [columnIndex];
  192.             }
  193.         });
  194.         tabeldatabuku.addMouseListener(new java.awt.event.MouseAdapter() {
  195.             public void mouseClicked(java.awt.event.MouseEvent evt) {
  196.                 tabeldatabukuMouseClicked(evt);
  197.             }
  198.         });
  199.         jScrollPane1.setViewportView(tabeldatabuku);
  200.         if (tabeldatabuku.getColumnModel().getColumnCount() > 0) {
  201.             tabeldatabuku.getColumnModel().getColumn(0).setResizable(false);
  202.             tabeldatabuku.getColumnModel().getColumn(1).setResizable(false);
  203.             tabeldatabuku.getColumnModel().getColumn(2).setResizable(false);
  204.             tabeldatabuku.getColumnModel().getColumn(3).setResizable(false);
  205.         }
  206.  
  207.         javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
  208.         jPanel1.setLayout(jPanel1Layout);
  209.         jPanel1Layout.setHorizontalGroup(
  210.             jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  211.             .addGroup(jPanel1Layout.createSequentialGroup()
  212.                 .addGap(18, 18, 18)
  213.                 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  214.                     .addGroup(jPanel1Layout.createSequentialGroup()
  215.                         .addComponent(insert)
  216.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  217.                         .addComponent(update)
  218.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  219.                         .addComponent(delete))
  220.                     .addGroup(jPanel1Layout.createSequentialGroup()
  221.                         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  222.                             .addComponent(jLabel2)
  223.                             .addComponent(jLabel1)
  224.                             .addComponent(jLabel3))
  225.                         .addGap(29, 29, 29)
  226.                         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  227.                             .addComponent(judulbuku_field)
  228.                             .addComponent(pengarang_field)
  229.                             .addComponent(stok_field, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE))))
  230.                 .addGap(18, 18, 18)
  231.                 .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  232.                 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  233.         );
  234.         jPanel1Layout.setVerticalGroup(
  235.             jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  236.             .addGroup(jPanel1Layout.createSequentialGroup()
  237.                 .addGap(22, 22, 22)
  238.                 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  239.                     .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  240.                     .addGroup(jPanel1Layout.createSequentialGroup()
  241.                         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  242.                             .addComponent(jLabel1)
  243.                             .addComponent(judulbuku_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  244.                         .addGap(18, 18, 18)
  245.                         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  246.                             .addComponent(jLabel2)
  247.                             .addComponent(pengarang_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  248.                         .addGap(18, 18, 18)
  249.                         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  250.                             .addComponent(jLabel3)
  251.                             .addComponent(stok_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  252.                         .addGap(18, 18, 18)
  253.                         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  254.                             .addComponent(insert)
  255.                             .addComponent(update)
  256.                             .addComponent(delete))))
  257.                 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  258.         );
  259.  
  260.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  261.         getContentPane().setLayout(layout);
  262.         layout.setHorizontalGroup(
  263.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  264.             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  265.                 .addContainerGap()
  266.                 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  267.                 .addContainerGap())
  268.         );
  269.         layout.setVerticalGroup(
  270.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  271.             .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  272.         );
  273.  
  274.         pack();
  275.     }// </editor-fold>                        
  276.  
  277.     private void pengarang_fieldActionPerformed(java.awt.event.ActionEvent evt) {                                                
  278.         // TODO add your handling code here:
  279.     }                                              
  280.  
  281.     private void tabeldatabukuMouseClicked(java.awt.event.MouseEvent evt) {                                          
  282.  
  283.         int i = tabeldatabuku.getSelectedRow();
  284.         TableModel model = tabeldatabuku.getModel();
  285.        
  286.         id.setText(model.getValueAt(i,0).toString());
  287.         judulbuku_field.setText(model.getValueAt(i,1).toString());
  288.         pengarang_field.setText(model.getValueAt(i,2).toString());
  289.         stok_field.setText(model.getValueAt(i,3).toString());
  290.     }                                          
  291.  
  292.     private void insertActionPerformed(java.awt.event.ActionEvent evt) {                                      
  293.          String query = "INSERT INTO `databuku`(`judul`, `pengarang`, `stok`) VALUES ('"+judulbuku_field.getText()+"',"
  294.                 + "                                                                '"+pengarang_field.getText()+"',"
  295.                 + "                                                                '"+stok_field.getText()+"')";
  296.        
  297.         executeSQLQuery(query, "Inserted!");
  298.     }                                      
  299.  
  300.     private void updateActionPerformed(java.awt.event.ActionEvent evt) {                                      
  301.         String query = "UPDATE `databuku` SET `judul`='"+judulbuku_field.getText()+"',`pengarang`='"+pengarang_field.getText()+"',`stok`="+stok_field.getText()+" WHERE id="+id.getText();
  302.        
  303.         executeSQLQuery(query, "Updated!");
  304.         judulbuku_field.setText("");
  305.         pengarang_field.setText("");
  306.         stok_field.setText("");
  307.     }                                      
  308.  
  309.     private void deleteActionPerformed(java.awt.event.ActionEvent evt) {                                      
  310.         String query = "DELETE FROM `databuku` WHERE id="+id.getText();
  311.        
  312.         executeSQLQuery(query, "Deleted!");
  313.     }                                      
  314.  
  315.     /**
  316.      * @param args the command line arguments
  317.      */
  318.     public static void main(String args[]) {
  319.         /* Set the Nimbus look and feel */
  320.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  321.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  322.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  323.          */
  324.         try {
  325.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  326.                 if ("Nimbus".equals(info.getName())) {
  327.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  328.                     break;
  329.                 }
  330.             }
  331.         } catch (ClassNotFoundException ex) {
  332.             java.util.logging.Logger.getLogger(databuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  333.         } catch (InstantiationException ex) {
  334.             java.util.logging.Logger.getLogger(databuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  335.         } catch (IllegalAccessException ex) {
  336.             java.util.logging.Logger.getLogger(databuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  337.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  338.             java.util.logging.Logger.getLogger(databuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  339.         }
  340.         //</editor-fold>
  341.  
  342.         /* Create and display the form */
  343.         java.awt.EventQueue.invokeLater(new Runnable() {
  344.             public void run() {
  345.                 new databuku().setVisible(true);
  346.             }
  347.         });
  348.     }
  349.  
  350.     // Variables declaration - do not modify                    
  351.     private javax.swing.JButton delete;
  352.     private javax.swing.JTextField id;
  353.     private javax.swing.JButton insert;
  354.     private javax.swing.JLabel jLabel1;
  355.     private javax.swing.JLabel jLabel2;
  356.     private javax.swing.JLabel jLabel3;
  357.     private javax.swing.JPanel jPanel1;
  358.     private javax.swing.JScrollPane jScrollPane1;
  359.     private javax.swing.JTextField judulbuku_field;
  360.     private javax.swing.JTextField pengarang_field;
  361.     private javax.swing.JTextField stok_field;
  362.     private javax.swing.JTable tabeldatabuku;
  363.     private javax.swing.JButton update;
  364.     // End of variables declaration                  
  365. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement