SUDI KASUS

Toko Ristanto yang di inisialkan TOKOKU, adalah toko yang menjual barang barang peralatan komputer. Toko memiliki karyawan dan persedian brang maka yang akan kita buat adalah input data barang dan input data karyawan menggunakan java netbeans yang terkoneksi ke data base.

Dari uraian di atas dapat di temukan bahwa didalam aplikasi terdapat menu input barang dan menu input karyawan. Maka didalam fram terdapat internal frame untuk masing masing menu. Menu Input Barang toko dasn menu input data karyawan.

Initnya adalah membuat input data kedalam databse sql dengan java netbeans

Gambar. 1. Form Tambah Barang

Rencananya kita akan membuat input data barang seperti terlihat pada gambar diatas.

Yuks Kita mulai, semoga sukses.

Tahapan Pembuatan Aplikasi

  1. Membuat Project Baru
  2. Membuat Packages
  3. Mebuat disain Layout
  4. JFrame
  5. JinternalFrame
  6. Membuat Database MySql dan table data
  7. Membuat Koneksi Database
  8. Coding Funsingsi Menu Item
  9. Coding Fungsi CRUD
  10. Ujicoba
  11. Selesai

Tahapan tahapn diatas itulah yang kiata kerjakan.

  1. Membuat New Project

Pastikan bahwa aplikasi Java Nerbean sudah running, lanjutkan dengan Klik ->File New Project -> Pilih Java Application -> Klik Next isikan nama project anda Pada Form ProjectName (UAS_Ristanto_171011400916) -> Klik Finish.

Gambar. 2 NewProject

  • Membuat Package

New Project sudah terbentuk, lanjutkan dengan membuat Package didalam project UAS_Ristanto_171011400916. Berikut langkahnya:

Klik kanan pada UAS_Ristanto_171011400916 –> New –> Java Packages à isi tokoku (nama package) –> klik Finish.

Gambar. 3 Create New Package

Isi nama Packages nya:

Gambar. 4 Packages name

Gambar. 5 Hasil

  • Mendisain Layout
  • JFrame

JFrame adalah salah satu class dalam java yang dapat digunakan untuk membuat frame sebagai top-level container. Di dalam JFrame kita memasukan berbagai macam komponen seperti tombol, teks, combobox, dan lain-lain.

Langkahnya sebagai berikut :

Klik kanan pada Package tokoku –> New à JFrame Form –>NewJFrame (ganti dengan RistantoToko) –> klik Finish.

Gambar. 6 Create JFrame

Gambar. 7 Tamilan JFrame

Labjutkan dengan menambahkan menu dengan drag and drop JMenu dari panel ke dalam JFrame. Kemudian rename menu Edit menjadi Menu Toko serta tambahkan menu toko tersebut menu item dan lakukan rename menu item menjadi Input Barang Berikut tampilannya :

  • JInternal Frame

JInternal Frame merupakan frame di dalam frame dimaksudkan untuk frame Input Barang. Berikut langkah nya:

Klik kanan Package toko –> New JInternal Frame isi Nama Jinterna Frame –> Finish.

Lanjukan dengan menambahkan jLabel, jTextField, Combobox dan jButton untuk membuat form input barang dan mengeksekusi tombol Save, Updatate, Delete, AddNew dan Cancel serta tambahkan JTable Berikut tampilannya :

Sampai disini disain sudah selesai, selanjutnya kita akan mulai membuat databse Sql dan table database untuk input barang toko. Berikut langkahnya :

  1. Pastikan komputer sudah terinstall aplikasi XAMPP Versi 7.2 atau lebih.
  2. Jalankan Aphace dan sql pada XAMPP
  3. Kase melalui browser dengan mengetik http://localhost/phpmyadmin.
  • Buat database : “tokoristanto”
  • Buat table : “produk”

Field table produk :

Library JDBC SQL

Library ini berfunsi sebagai connector java ke database kita, waka wajib ditambahkan. Berikut alngkahnya :

Klik kanan library –> AddLibraryàselect MySQL JDBC Driver –> klik Add Library.


JFrame
TokoRistanto.java
Fungsi direct menu Input Barang
Source code 
Fungsi dirct menu Input Barang
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

InputBarang ipb=new InputBarang();
jDesktopPane1.add(ipb);
ipb.setVisible(true);
dispose();
}
Source code 
Form Input Barang
Fungsi memanggil / include library java. Untuk koneksi database.
import java.sql.*; 
import javax.swing.table.DefaultTableModel;
import java.util.Scanner;
import java.sql.Connection;
import javax.swing.JOptionPane;

Menampikan data table

Menampilkan data ke form saat data pada tabel di klik

//menampilkan data ke form saat data pada tabel di klik    
void tblKeForm(){
jTextKodeProduk.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),0)+"");
jTextNama.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),1)+"");
jComboBoxSatuan.setSelectedItem(
tabModel.getValueAt(TabelProduk.getSelectedRow(),2)+"");
jTextHarga.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),3)+"");
jTextStok.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),4)+"");
 jButtonUpdate.setEnabled(true);

jButtonDelete.setEnabled(true);  
jButtonCancel.setEnabled(true);
jButtonSave.setEnabled(false);
}

Membersihkan form

private void BersihData(){
   jTextKodeProduk.setText("");
jTextNama.setText("");        
jComboBoxSatuan.setSelectedIndex(0);        
jTextHarga.setText("");        
jTextStok.setText("");
}

Disable dan Enable form

private void SetEditOff(){
        jTextKodeProduk.setEnabled(false);
        jTextNama.setEnabled(false);
        jComboBoxSatuan.setEnabled(false);
        jTextHarga.setEnabled(false);
        jTextStok.setEnabled(false);
   }

//mengidupkan form
   private void seteditOn(){
        jTextKodeProduk.setEnabled(true);
        jTextNama.setEnabled(true);
        jComboBoxSatuan.setEnabled(true);
        jTextHarga.setEnabled(true);
        jTextStok.setEnabled(true);
  }

Fungsi tombol AddNew

private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
BersihData();
jTextKodeProduk.requestFocus();       
jButtonSave.setEnabled(true);
jButtonUpdate.setEnabled(false);
jButtonDelete.setEnabled(false);       
seteditOn();   
}

 

Simpan data

private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {  
// TODO add your handling code here:    
String KodeProduk=jTextKodeProduk.getText();
String NamaProduk=jTextNama.getText();
String Satuan=jComboBoxSatuan.getSelectedItem().toString();
String Harga=jTextHarga.getText();
String Stok=jTextStok.getText();  
java.util.Date tanggal = new java.util.Date();  
java.text.SimpleDateFormat TanggalFormat=
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String CreateDate=TanggalFormat.format(tanggal);         
if (KodeProduk.isEmpty() ) {           
JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");
jTextKodeProduk.requestFocus();
}else if (NamaProduk.isEmpty()) {
JOptionPane.showMessageDialog(null,"Nama produk tidak boleh kosong");
jTextNama.requestFocus();       
}else if (Satuan.isEmpty()) {           
JOptionPane.showMessageDialog(null,"Satuan produk tidak boleh kosong");
jComboBoxSatuan.requestFocus();       
}else if (Harga.isEmpty()) {           
JOptionPane.showMessageDialog(null,"Harga produk tidak boleh kosong");
jTextHarga.requestFocus();
}else if (Stok.isEmpty()) {
JOptionPane.showMessageDialog(null,"Stok produk tidak boleh kosong");  
jTextStok.requestFocus();
}  else if (!(new Scanner(Harga).hasNextInt())) {   
JOptionPane.showMessageDialog(null,"Harga produk harus angka");
jTextHarga.requestFocus();
}else if (!(new Scanner(Stok).hasNextInt())) {   
JOptionPane.showMessageDialog(null,"Stok produk harus angka")
jTextStok.requestFocus();
}else{
try{
Connection conn=(Connection)koneksi.koneksiDB();               
Statement stt=conn.createStatement();               
stt.executeUpdate("insert into produk(KodeProduk,NamaProduk,
Satuan,Harga,Stok,CreateDate)"+
"VALUES('"+KodeProduk+"','"+NamaProduk+"','"+Satuan+"',
'"+Harga+"','"+Stok+"','"+CreateDate+"')");
BersihData();  
tampilData();
SetEditOff();
JOptionPane.showMessageDialog(this,
"Data berhasil disimpan","Success",
JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException e){
JOptionPane.showMessageDialog(this,"Simpan data gagal\n"+e.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
Update Data

Code:

private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) { 
// TODO add your handling code here:
String KodeProduk=jTextKodeProduk.getText();
String NamaProduk=jTextNama.getText();
String Satuan=jComboBoxSatuan.getSelectedItem().toString();
String Harga=jTextHarga.getText();
String Stok=jTextStok.getText();
java.util.Date tanggal = new java.util.Date();
java.text.SimpleDateFormat TanggalFormat= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String CreateDate=TanggalFormat.format(tanggal);
if (KodeProduk.isEmpty()) {
JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");
jTextKodeProduk.requestFocus();
}else if (NamaProduk.isEmpty()) {
JOptionPane.showMessageDialog(null,"Nama produk tidak boleh kosong");
jTextNama.requestFocus();
}else if (Satuan.isEmpty()){
JOptionPane.showMessageDialog(null,"Satuan produk tidak boleh kosong");
jComboBoxSatuan.requestFocus();
}else if (Harga.isEmpty()) {
JOptionPane.showMessageDialog(null,"Harga produk tidak boleh kosong");
jTextHarga.requestFocus();
}else if (Stok.isEmpty()){
JOptionPane.showMessageDialog(null,"Stok produk tidak boleh kosong");
jTextStok.requestFocus();
}else if (!(new Scanner(Harga).hasNextInt())){
JOptionPane.showMessageDialog(null,"Harga produk harus angka");
jTextHarga.requestFocus();
}else if (!(new Scanner(Stok).hasNextInt())){
JOptionPane.showMessageDialog(null,"Stok produk harus angka");
jTextStok.requestFocus();
}else{
try{
Connection conn=(Connection)koneksi.koneksiDB();
Statement stt=conn.createStatement();
stt.executeUpdate("UPDATE produk SET NamaProduk='"+NamaProduk+"',
Satuan='"+Satuan+"', Harga='"+Harga+"',"
+"Stok='"+Stok+"' WHERE KodeProduk='"+KodeProduk+"'");
BersihData();
tampilData();
SetEditOff();
JOptionPane.showMessageDialog(this,"Data berhasil diubah",
"Success",JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException e){
JOptionPane.showMessageDialog(this,"Ubah data gagal\n"+e.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE);
}
}

private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String KodeProduk=jTextKodeProduk.getText();
if (KodeProduk.isEmpty() ) {
JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");
jTextKodeProduk.requestFocus();
}else if(JOptionPane.showConfirmDialog(null,"Apakah anda yakin akan menghapus data ini?",
"Informasi",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==JOptionPane.OK_OPTION){
try{
Connection conn=(Connection)koneksi.koneksiDB();
Statement stt=conn.createStatement();
stt.executeUpdate("DELETE FROM produk WHERE KodeProduk='"+KodeProduk+"'");
BersihData();
tampilData();
SetEditOff();
JOptionPane.showMessageDialog(this,"Data berhasil di hapus","Success",
JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException e){
JOptionPane.showMessageDialog(this,"Delete data gagal\n"+e.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
//Fungsi Cancel
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:ersihData();
jButtonSave.setEnabled(false);
jButtonUpdate.setEnabled(false);
jButtonDelete.setEnabled(false);
SetEditOff();
}               
/*  * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates  
* and open the template in the editor.  
*/ package tokoku;  
/**  *  * @author RISTANTO  */
public class RistantoToko extends javax.swing.JFrame {
jMenuItem1 Penjualan;    
jMenuItem2 InputBarang;      
/**     
* Creates new form RistantoToko     
*/    

public RistantoToko() {
initComponents();    
}      
/**     
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.     
*/     @SuppressWarnings("unchecked")    
// <editor-fold defaultstate="collapsed" desc="Generated Code">        

private void initComponents() {       
   jDesktopPane1 = new javax.swing.JDesktopPane();    
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();     
   jMenu2 = new javax.swing.JMenu();      
jMenuItem1 = new javax.swing.JMenuItem();
   jMenuItem2 = new javax.swing.JMenuItem();  
  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
  setTitle("TOKO RISTANTO 171011400916");
  setBackground(new java.awt.Color(0, 102, 102));         
jDesktopPane1.setBackground(new java.awt.Color(0, 102, 102));     
   jDesktopPane1.setForeground(new java.awt.Color(0, 102, 102));      
  javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
  jDesktopPane1.setLayout(jDesktopPane1Layout);   
jDesktopPane1Layout.setHorizontalGroup(    
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 615, Short.MAX_VALUE) );  
  jDesktopPane1Layout.setVerticalGroup(       
  jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  .addGap(0, 429, Short.MAX_VALUE));
jMenu1.setText("File");    
  jMenuBar1.add(jMenu1);          
jMenu2.setText("Menu Toko");      
jMenu2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu2ActionPerformed(evt);
}
});  
  jMenuItem1.setText("Penjualan");        
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {                
jMenuItem1ActionPerformed(evt);       
  }});        
jMenu2.add(jMenuItem1);     
  jMenuItem2.setText("Input Barang");   
  jMenuItem2.addActionListener(new java.awt.event.ActionListener() {            
public void actionPerformed(java.awt.event.ActionEvent evt) {
  jMenuItem2ActionPerformed(evt); } });        
jMenu2.add(jMenuItem2);  
   jMenuBar1.add(jMenu2);       
setJMenuBar(jMenuBar1);       
  javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());   
  getContentPane().setLayout(layout);      
   layout.setHorizontalGroup(           
  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  .addGroup(layout.createSequentialGroup()                
.addComponent(jDesktopPane1)               
.addContainerGap())         );  
   layout.setVerticalGroup(            
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)        
  .addComponent(jDesktopPane1, javax.swing.GroupLayout.Alignment.TRAILING) );          
pack();      
setLocationRelativeTo(null);    
}// </editor-fold>                            

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) { 
  // TODO add your handling code here:  
     InputBarang ipb=new InputBarang();        
jDesktopPane1.add(ipb);      
  ipb.setVisible(true); //     
  dispose();     }                                               
private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) { 
// TODO add your handling code here:
}                                       
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
  // TODO add your handling code here: //        
Karyawan ky =new Karyawan(); //
  jDesktopPane1.add(pj); //
ky.setVisible(true);     }                                       
/**     
* @param args the command line arguments     
*/
public static void main(String args[]) {   
 /* Set the Nimbus look and feel */        
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">  
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/    
 try {            
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {       
        if ("Nimbus".equals(info.getName())) {                    
javax.swing.UIManager.setLookAndFeel(info.getClassName());        
         break;
}           
}      
  } catch (ClassNotFoundException ex) {      
     java.util.logging.Logger.getLogger(RistantoToko.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
   } catch (InstantiationException ex) {            
java.util.logging.Logger.getLogger(RistantoToko.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
 } catch (IllegalAccessException ex) {            
java.util.logging.Logger.getLogger(RistantoToko.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
 } catch (javax.swing.UnsupportedLookAndFeelException ex) {            
java.util.logging.Logger.getLogger(RistantoToko.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);  
      }         //</editor-fold>          
/* Create and display the form */        
java.awt.EventQueue.invokeLater(new Runnable() {            
public void run() {                
new RistantoToko().setVisible(true);
  }
});    

}      

// Variables declaration - do not modify                    
   private javax.swing.JDesktopPane jDesktopPane1;    
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;  
private javax.swing.JMenuBar jMenuBar1;    
private javax.swing.JMenuItem jMenuItem1;    
private javax.swing.JMenuItem jMenuItem2;   
// End of variables declaration                  

}

Hapus data

Fungsi bersihkan Form

private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {    
// TODO add your handling code here:        
BersihData();        
jButtonSave.setEnabled(false);        
jButtonUpdate.setEnabled(false);        
jButtonDelete.setEnabled(false);        
SetEditOff();    
}            

Funsi Hapus Data

private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {  
// TODO add your handling code here:
String KodeProduk=jTextKodeProduk.getText();
if (KodeProduk.isEmpty() ) {
JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");
jTextKodeProduk.requestFocus();
}else if(JOptionPane.showConfirmDialog(null,"Apakah anda yakin akan menghapus data ini?",
"Informasi",JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE)==JOptionPane.OK_OPTION){
try{
Connection conn=(Connection)koneksi.koneksiDB();
Statement stt=conn.createStatement();
stt.executeUpdate("DELETE FROM produk WHERE KodeProduk='"+KodeProduk+"'");
BersihData();
tampilData();
SetEditOff();
JOptionPane.showMessageDialog(this,"Data berhasil di hapus",
"Success",JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException e){
JOptionPane.showMessageDialog(this,"Delete data gagal\n"+e.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE);
}
}
}                                           

Berikut Source code lengkapnya:

JInternal Frame

InputBarang.java

/*  * To change this license header,
choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.  
*/ package tokoku; import java.sql.*;
import javax.swing.table.DefaultTableModel;
import java.util.Scanner; import java.sql.Connection;
import javax.swing.JOptionPane;  
/**  *  * @author RISTANTO  */
public class InputBarang extends javax.swing.JInternalFrame {
DefaultTableModel tabModel;
ResultSet RsProduk=null;
/**      * Creates new form InputBarang
*/    
public InputBarang() {        
initComponents();
  tampilData();    
  SetEditOff();    
}        
//fungsi untuk menampilkan data produk ke dalam tabel    
private void tampilData(){       
  try{        
    Object[] judul_kolom = {"Kode Barang", "Nama Barang",
"Satuan", "Harga", "Stok", "Create Date"};
    tabModel=new DefaultTableModel(null,judul_kolom);           
TabelProduk.setModel(tabModel);                     
  Connection conn=(Connection)koneksi.koneksiDB();       
     Statement stt=conn.createStatement();           
tabModel.getDataVector().removeAllElements();         
    RsProduk=stt.executeQuery("SELECT * from produk ");   
   while(RsProduk.next()){              
Object[] data={
RsProduk.getString("KodeProduk"),   
RsProduk.getString("NamaProduk"),        
    RsProduk.getString("Satuan"),       
    RsProduk.getString("Harga"),            
    RsProduk.getString("Stok"),                
   RsProduk.getString("CreateDate")           
    };           
tabModel.addRow(data);         
  }                       
} catch (Exception ex) {   
     System.err.println(ex.getMessage());     
}        
// disable button        
jButtonSave.setEnabled(false);    
  jButtonUpdate.setEnabled(false);  
  jButtonDelete.setEnabled(false);    
   jButtonCancel.setEnabled(false);    
}    
//menampilkan data ke form saat data pada tabel di klik  
void tblKeForm(){  
jTextKodeProduk.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),0)+"");
jTextNama.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),1)+"");
jComboBoxSatuan.setSelectedItem(tabModel.getValueAt(TabelProduk.getSelectedRow(),2)+"");  
jTextHarga.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),3)+"");
jTextStok.setText(tabModel.getValueAt(TabelProduk.getSelectedRow(),4)+"");
jButtonUpdate.setEnabled(true);
jButtonDelete.setEnabled(true);
jButtonCancel.setEnabled(true);
jButtonSave.setEnabled(false);
}

//membersihkan form   
private void BersihData(){
jTextKodeProduk.setText("");
jTextNama.setText("");      
  jComboBoxSatuan.setSelectedIndex(0);
  jTextHarga.setText("");
jTextStok.setText("");
}

//disable form   
private void SetEditOff(){
  jTextKodeProduk.setEnabled(false);      
jTextNama.setEnabled(false);       
  jComboBoxSatuan.setEnabled(false);    
 jTextHarga.setEnabled(false);     
  jTextStok.setEnabled(false);
}

private void seteditOn(){
jTextKodeProduk.setEnabled(true);
 jTextNama.setEnabled(true);
jComboBoxSatuan.setEnabled(true);
 jTextHarga.setEnabled(true);
jTextStok.setEnabled(true);   
}
/**
* This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always     
* regenerated by the Form Editor.     
*/     @SuppressWarnings("unchecked")    
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();   
jTable1 = new javax.swing.JTable();      
jTextHarga = new javax.swing.JTextField();    
jLabelStok = new javax.swing.JLabel();    
jTextStok = new javax.swing.JTextField();  
jButtonAdd = new javax.swing.JButton();        
jLabelKodeProduk = new javax.swing.JLabel();        
jButtonSave = new javax.swing.JButton();        
jTextKodeProduk = new javax.swing.JTextField();        
jButtonUpdate = new javax.swing.JButton();        
jLabelNama = new javax.swing.JLabel();        
jButtonDelete = new javax.swing.JButton();       
jTextNama = new javax.swing.JTextField();        
jButtonCancel = new javax.swing.JButton();        
jLabelSatuan = new javax.swing.JLabel();        
jScrollPane3 = new javax.swing.JScrollPane();       
TabelProduk = new javax.swing.JTable();        
jComboBoxSatuan = new javax.swing.JComboBox();       
jLabelHarga = new javax.swing.JLabel();          
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] { {null, null, null, null},
{null, null, null, null},            
    {null, null, null, null},          
    {null, null, null, null} },
new String [] {"Title 1", "Title 2", "Title 3", "Title 4"}));
jScrollPane1.setViewportView(jTable1);
setClosable(true);
setIconifiable(true);  
setMaximizable(true);
  setResizable(true);        
setTitle("INPUT BARANG");          
jLabelStok.setText("Stok");          
jButtonAdd.setBackground(new java.awt.Color(255, 153, 102));        
jButtonAdd.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N        
jButtonAdd.setText("AddNew");        
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {     
   jButtonAddActionPerformed(evt);
}
});
jLabelKodeProduk.setText("Kode Produk");          
jButtonSave.setBackground(new java.awt.Color(102, 102, 255));       
jButtonSave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N        
jButtonSave.setForeground(new java.awt.Color(255, 255, 255));        
jButtonSave.setText("Save");        
jButtonSave.addActionListener(new java.awt.event.ActionListener(){           
public void actionPerformed(java.awt.event.ActionEvent evt) {                
jButtonSaveActionPerformed(evt);
}
});          
jButtonUpdate.setBackground(new java.awt.Color(255, 204, 102));
jButtonUpdate.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
ButtonUpdate.setText("Update");       
jButtonUpdate.addActionListener(new java.awt.event.ActionListener() {  
public void actionPerformed(java.awt.event.ActionEvent evt) {           
   jButtonUpdateActionPerformed(evt);}});
 jLabelNama.setText("Nama");         
  jButtonDelete.setBackground(new java.awt.Color(255, 51, 51));
  jButtonDelete.setFont(new java.awt.Font("Tahoma", 0, 12)); //
    jButtonDelete.setText("Delete");      
   jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {     
   jButtonDeleteActionPerformed(evt); }});         
  jButtonCancel.setBackground(new java.awt.Color(0, 204, 204));    
   jButtonCancel.setFont(new java.awt.Font("Tahoma", 1, 12)); //
  jButtonCancel.setText("Cancel");
   jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {      
   jButtonCancelActionPerformed(evt); }});
jLabelSatuan.setText("Satuan");         
  TabelProduk.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {{null, null, null, null},
                {null, null, null, null},     
            {null, null, null, null},        
         {null, null, null, null}         
},    
new String [] {"Title 1", "Title 2", "Title 3", "Title 4"}));        
TabelProduk.addMouseListener(new java.awt.event.MouseAdapter() {            
public void mouseClicked(java.awt.event.MouseEvent evt) {               
TabelProdukMouseClicked(evt);
}
});
  jScrollPane3.setViewportView(TabelProduk);        
  jComboBoxSatuan.setModel(new javax.swing.DefaultComboBoxModel(new String[]
{ "Pcs", "Dus", "Kg" }));      
jComboBoxSatuan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {          
   jComboBoxSatuanActionPerformed(evt);}});        
  jLabelHarga.setText("Harga");       
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
     getContentPane().setLayout(layout);        
layout.setHorizontalGroup(           
  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
       .addGroup(layout.createSequentialGroup()         
     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
       .addGroup(layout.createSequentialGroup()
       .addGap(84, 84, 84)                        
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
       .addComponent(jLabelNama)
       .addComponent(jLabelSatuan)
      .addComponent(jLabelHarga)                   
       .addComponent(jLabelStok)                     
       .addComponent(jLabelKodeProduk))              
       .addGap(19, 19, 19)        
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
       .addComponent(jTextHarga)     
.addComponent(
jTextNama,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.PREFERRED_SIZE, 257,
javax.swing.GroupLayout.PREFERRED_SIZE)          
      .addComponent(jComboBoxSatuan, 0, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jTextKodeProduk,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.PREFERRED_SIZE, 258,
javax.swing.GroupLayout.PREFERRED_SIZE)    
       .addComponent(jTextStok, javax.swing.GroupLayout.PREFERRED_SIZE, 259,
javax.swing.GroupLayout.PREFERRED_SIZE))        
      .addGap(49, 49, 49)                 
     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
      .addComponent(jButtonDelete, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
   .addComponent(jButtonUpdate,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)                      
       .addComponent(jButtonSave, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)                            
.addComponent(jButtonAdd, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)         
        .addComponent(jButtonCancel,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
          .addGroup(layout.createSequentialGroup()             
          .addGap(62, 62, 62)            
          .addComponent(jScrollPane3,
javax.swing.GroupLayout.PREFERRED_SIZE, 505,
javax.swing.GroupLayout.PREFERRED_SIZE)))         
        .addContainerGap(189, Short.MAX_VALUE)) );   
    layout.setVerticalGroup(      
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()         
      .addGap(33, 33, 33)     
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
     .addComponent(jTextKodeProduk, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
     .addComponent(jLabelKodeProduk)
      .addComponent(jButtonAdd))         
      .addGap(18, 18, 18)           
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(jTextNama, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
     .addComponent(jLabelNama)     
    .addComponent(jButtonSave))   
     .addGap(18, 18, 18)              
   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    addComponent(jComboBoxSatuan,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabelSatuan)      
    .addComponent(jButtonUpdate))             
   .addGap(18, 18, 18)            
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
     .addComponent(jTextHarga, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)    
   .addComponent(jLabelHarga)        
    .addComponent(jButtonDelete))            
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)   
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jTextStok,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)  
     .addComponent(jLabelStok))        
    .addComponent(jButtonCancel))     
     .addGap(100, 100, 100)           
    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 153,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(39, Short.MAX_VALUE))       
  );          
pack();    
}// </editor-fold>                       
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) { 
/ TODO add your handling code here:     
BersihData();  
  jTextKodeProduk.requestFocus();     
  jButtonSave.setEnabled(true);      
jButtonUpdate.setEnabled(false);     
 jButtonDelete.setEnabled(false);  
  seteditOn();     }                            
private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {  
// TODO add your handling code here:        
String KodeProduk=jTextKodeProduk.getText();       
String NamaProduk=jTextNama.getText();     
  String Satuan=jComboBoxSatuan.getSelectedItem().toString();
  String Harga=jTextHarga.getText();     
String Stok=jTextStok.getText();       
java.util.Date tanggal = new java.util.Date();     
java.text.SimpleDateFormat TanggalFormat= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
String CreateDate=TanggalFormat.format(tanggal);    
if (KodeProduk.isEmpty() ) {          
  JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");           
 jTextKodeProduk.requestFocus();    
   }else if (NamaProduk.isEmpty()) {      
       JOptionPane.showMessageDialog(null,"Nama produk tidak boleh kosong");      
      jTextNama.requestFocus();
}else if (Satuan.isEmpty()) {         
   JOptionPane.showMessageDialog(null,"Satuan produk tidak boleh kosong");     
        jComboBoxSatuan.requestFocus();     
    }else if (Harga.isEmpty()) {   
        JOptionPane.showMessageDialog(null,"Harga produk tidak boleh kosong");   
         jTextHarga.requestFocus();
}else if (Stok.isEmpty()) {         
   JOptionPane.showMessageDialog(null,"Stok produk tidak boleh kosong");         
   jTextStok.requestFocus();
}else if (!(new Scanner(Harga).hasNextInt())) {  
          JOptionPane.showMessageDialog(null,"Harga produk harus angka");      
       jTextHarga.requestFocus();        
}else if (!(new Scanner(Stok).hasNextInt())) {    
        JOptionPane.showMessageDialog(null,"Stok produk harus angka");        
     jTextStok.requestFocus();       
  }else{           
  try{           
     Connection conn=(Connection)koneksi.koneksiDB();               
Statement stt=conn.createStatement();
stt.executeUpdate("insert into produk(KodeProduk,NamaProduk,Satuan,Harga,Stok,CreateDate)"+
               "VALUES('"+KodeProduk+"','"
+NamaProduk+"','"
+Satuan+"','"
+Harga+"','"
+Stok+"','"
+CreateDate+"')");         
BersihData();               
tampilData();               
SetEditOff();         
  JOptionPane.showMessageDialog(this,"Data berhasil disimpan",
"Success",JOptionPane.INFORMATION_MESSAGE);  
    } catch(SQLException e){
   JOptionPane.showMessageDialog(this,
"Simpan data gagal\n"+e.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE); 
}        
}
}
private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) {  
// TODO add your handling code here:     
String KodeProduk=jTextKodeProduk.getText();        
String NamaProduk=jTextNama.getText();        
String Satuan=jComboBoxSatuan.getSelectedItem().toString();       
String Harga=jTextHarga.getText();        
String Stok=jTextStok.getText();         
  java.util.Date tanggal = new java.util.Date();       
  java.text.SimpleDateFormat TanggalFormat= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
 String CreateDate=TanggalFormat.format(tanggal);
if (KodeProduk.isEmpty() ) {      
   JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");
jTextKodeProduk.requestFocus();        
}else if (NamaProduk.isEmpty()) {
OptionPane.showMessageDialog(null,"Nama produk tidak boleh kosong");
jTextNama.requestFocus();       
}else if (Satuan.isEmpty()) {     
  JOptionPane.showMessageDialog(null,"Satuan produk tidak boleh kosong");    
  jComboBoxSatuan.requestFocus();
}else if (Harga.isEmpty()) {
JOptionPane.showMessageDialog(null,"Harga produk tidak boleh kosong");         
   jTextHarga.requestFocus();      
}else if (Stok.isEmpty()) {
JOptionPane.showMessageDialog(null,"
Stok produk tidak boleh kosong");            
jTextStok.requestFocus();
}else if (!(new Scanner(Harga).hasNextInt()))
{ JOptionPane.showMessageDialog(null,"Harga produk harus angka");            
jTextHarga.requestFocus();        
}else if (!(new Scanner(Stok).hasNextInt())) {         
    JOptionPane.showMessageDialog(null,"Stok produk harus angka");      
   jTextStok.requestFocus();
}else{       
     try{     
       Connection conn=(Connection)koneksi.koneksiDB();  
       Statement stt=conn.createStatement();       
     stt.executeUpdate("UPDATE produk SET
NamaProduk='"+NamaProduk+"',
Satuan='"+Satuan+"', Harga='"+Harga+"',"+
                    "Stok='"+Stok+"' WHERE KodeProduk='"+KodeProduk+"'");
BersihData();   
       tampilData();          
       SetEditOff();          
    JOptionPane.showMessageDialog(this,"Data berhasil diubah",
"Success",JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException e){      
       JOptionPane.showMessageDialog(this,"Ubah data gagal\n"+e.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE);
}        
}    
}
private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                                     
// TODO add your handling code here:        
String KodeProduk=jTextKodeProduk.getText();     
  if (KodeProduk.isEmpty() ) {         
   JOptionPane.showMessageDialog(null,"Kode produk tidak boleh kosong");     
     jTextKodeProduk.requestFocus();        
}else if(JOptionPane.showConfirmDialog(null,
"Apakah anda yakin akan menghapus data ini?","Informasi",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE)==JOptionPane.OK_OPTION)
try{   
    Connection conn=(Connection)koneksi.koneksiDB();
Statement stt=conn.createStatement();            
stt.executeUpdate("DELETE FROM produk WHERE KodeProduk='"+KodeProduk+"'");     
       BersihData();
       tampilData();      
       SetEditOff();       
JOptionPane.showMessageDialog(this,"Data berhasil di hapus","Success",
JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException e){
JOptionPane.showMessageDialog(this,"Delete data gagal\n"+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
  }      
}  
}
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:        
BersihData();        
jButtonSave.setEnabled(false);        
jButtonUpdate.setEnabled(false);        
jButtonDelete.setEnabled(false);        
SetEditOff();}                                                  

private void TabelProdukMouseClicked(java.awt.event.MouseEvent evt) {   
// TODO add your handling code here:        
seteditOn();     
   jTextKodeProduk.setEnabled(false);
  tblKeForm();
}                                              
private void jComboBoxSatuanActionPerformed(java.awt.event.ActionEvent evt) { 
// TODO add your handling code here:

// Variables declaration - do not modify                        
private javax.swing.JTable TabelProduk;    
private javax.swing.JButton jButtonAdd;    
private javax.swing.JButton jButtonCancel;    
private javax.swing.JButton jButtonDelete;    
private javax.swing.JButton jButtonSave;    
private javax.swing.JButton jButtonUpdate;    
private javax.swing.JComboBox jComboBoxSatuan;    
private javax.swing.JLabel jLabelHarga;    
private javax.swing.JLabel jLabelKodeProduk;    
private javax.swing.JLabel jLabelNama;    
private javax.swing.JLabel jLabelSatuan;    
private javax.swing.JLabel jLabelStok;    
private javax.swing.JScrollPane jScrollPane1;    
private javax.swing.JScrollPane jScrollPane3;    
private javax.swing.JTable jTable1;    
private javax.swing.JTextField jTextHarga;    
private javax.swing.JTextField jTextKodeProduk;    
private javax.swing.JTextField jTextNama;    
private javax.swing.JTextField jTextStok;    
// End of variables declaration
}

Koneksi Database

/*  * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.  
*/ package tokoku;  
import java.sql.Connection; import java.sql.DriverManager;
import java.sql.SQLException; import javax.swing.JOptionPane;
/**  *  * @author RISTANTO  */
public class koneksi {
private static Connection KoneksiDatabse;
public static Connection koneksiDB() throws SQLException {
try {
String DB ="jdbc:mysql://localhost/penjualan";
String user="root";
String pass="";
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
KoneksiDatabse = (Connection) DriverManager.getConnection(DB,user,pass);
} catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Tidak ada koneksi","Error",
   JOptionPane.INFORMATION_MESSAGE);
System.err.println(e.getMessage());

System.exit(0);
} return KoneksiDatabse;
}
}

Dokumen PDF :

Download (PDF, 1.1MB)