Sie sind auf Seite 1von 5

/*

* 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 Jtable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.sql.*;
/**
*
* @author zaini
*/
public class DemoJtable extends javax.swing.JFrame {
// Tabel model dari jtable
DefaultTableModel dtmData = new DefaultTableModel(
// Isian datanya
new Object[][] {
},
// Judul Kolomnya
new String[] {"No", "Nama", "Alamat"}
);
/**
* Creates new form contoh
*/
public DemoJtable(){
initComponents();
init_table();
// init_table_fromdb();
}
/**
* 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">//GEN-BEGIN:i
nitComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jtfMemberId = new javax.swing.JTextField();
jtfNama = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Kode", "Nama", "Jenis Kelamin"

}
));
jScrollPane1.setViewportView(jTable1);
jButton1.setText("Simpan");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Tambah Baris");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentP
ane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING
)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Ali
gnment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout
.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREF
ERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addComponent(jtfMemberId, javax.swing.GroupLayout.P
REFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPl
acement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jtfNama, javax.swing.GroupLayout.PREFE
RRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_
SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SI
ZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX
_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING
)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createS
equentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Ali
gnment.BASELINE)
.addComponent(jtfMemberId, javax.swing.GroupLayout.PREFERRED
_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_S
IZE)
.addComponent(jtfNama, javax.swing.GroupLayout.PREFERRED_SIZ
E, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SI
ZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX
_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
int jmlBaris = dtmData.getRowCount() + 1;
String nama = jtfMemberId.getText();
String alamat = jtfNama.getText();
dtmData.addRow(new String[]{String.valueOf(jmlBaris) , nama, alamat});
jtfMemberId.setText("");
jtfNama.setText("");
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
simpanData();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @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 cod
e (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the d
efault look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lo
okandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIMana
ger.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DemoJtable.class.getName()).log(j
ava.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DemoJtable.class.getName()).log(j

ava.util.logging.Level.SEVERE, null, ex);


} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DemoJtable.class.getName()).log(j
ava.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DemoJtable.class.getName()).log(j
ava.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run(){
new DemoJtable().setVisible(true);
}
});
}
/**
* Inisialisasi Table model sebagai isian data dari jtable
*/
private void init_table(){
jTable1.setModel(dtmData);
dtmData.addRow(new String[]{"1", "Ali", "Malang"});
}
private void init_table_fromdb() {
try{
int jmlData;
String kode, nama;
DefaultTableModel isi = new DefaultTableModel(
new Object[][]{},
new String[]{"No", "Member ID", "Nama"}
);
jTable1.setModel(isi);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhos
t/fahruddin",
"root", "fahruddin");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT kode, nama FROM info");
while(rs.next()){
jmlData = isi.getRowCount() + 1;
kode = rs.getString("kode");
nama = rs.getString("nama");
isi.addRow(
new String[]{String.valueOf(jmlData), kode, nama}
);
}
rs.close();
st.close();
conn.close();
}
catch(ClassNotFoundException e){
}
catch(SQLException e){
}

}
/**
* Method Untuk Menyimpan Data
*/
private void simpanData(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhos
t/fahruddin",
"root", "fahruddin");
Statement st = conn.createStatement();
String kode = jtfMemberId.getText();
String nama = jtfNama.getText();
String query;
query = "SELECT kode FROM info "
+ "WHERE kode = \'" + kode + "\'";
ResultSet rs = st.executeQuery(query);
Boolean ada = rs.first();
if(ada){
// update (jika member_id ditemukan)
System.out.println("update data ...");
query = "UPDATE info SET "
+ "nama = \'"+ nama +"\' "
+ "WHERE kode=\'" + kode + "\'";
}else{
// insert (jika member_id tidak ditemukan )
System.out.println("tambah data ...");
query = "INSERT INTO info (kode, nama) VALUES "
+ "(\'"+ kode +"\', \'"+ nama +"\')";
}
System.out.println(st.execute(query));
rs.close();
st.close();
conn.close();
init_table_fromdb(); // Merefresh tabel
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}
catch(SQLException se){
System.out.println(se.getMessage());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jtfMemberId;
private javax.swing.JTextField jtfNama;
// End of variables declaration//GEN-END:variables
}

Das könnte Ihnen auch gefallen