25 Agustus 2012


Selanjutnya, mencoba membuat tutorial Java, berhubung masih tahap belajar jadi penjelasan dan tutorial yang dibuat juga mungkin masih kurang bagus :) . Disini saya menggunakan Netbeans, biar gampang membuat tampilannya tinggal drag and drop. Di java, ada kelas Properties (java.util.Properties) yang dapat digunakan untuk menyimpan konfigurasi untuk aplikasi. Properties adalah kelas yang memilki key dan value, dibantu oleh kelas FileInputStream dan FileOutputStream dalam menulis dan membaca konfigurasi pada berkas. Berikut contoh kode program konfigurasi database yang saya buat menggunakan Properties.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.swing.JOptionPane;

public class KonfigurasiGUI extends javax.swing.JFrame {

    /** Creates new form KonfigurasiGUI */
    public KonfigurasiGUI() {
        initComponents();
        /* set aplikasi agar tampil di tengah layar*/
        setLocationRelativeTo(null);
        /* baca berkas konfigurasi database */
        Properties p = this.bacaBerkasKonfigurasi("konfigurasi database");
        /* tes koneksi berdasarkan konfigurasi pada berkas properties */
        this.cekKoneksi(p.getProperty("host"), p.getProperty("db_name"), p.getProperty("port"),
                p.getProperty("user"), p.getProperty("password"));
    }

    public void simpanBerkasKonfigurasi(Properties p, String fileName){
        /* FileOuputStream, berfungsi untuk menulis data pada berkas */
    FileOutputStream out = null;
    try{
     out = new FileOutputStream(fileName);
     /* Simpan konfigurasi pada properties */
     p.store(out,"Berkas konfigurasi database");
     JOptionPane.showMessageDialog(null,"Konfigurasi Database Telah Disimpan");
    }
    catch(Exception e){
    JOptionPane.showMessageDialog(null,"Konfigurasi Database Gagal Disimpan");
    }
        finally{
            try {
                out.close();
            } catch (IOException ex) {
            }
        }
    }

    public boolean cekKoneksi(String host, String dbName, String port, String user, String password){
        Connection con;
        try{
     /* Tes koneksi */
     con = DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+
                  dbName+"?user="+user+"&password="+password+"");
     /* Set status jika tersambung ke database */
     this.jlStatus.setText("Tersambung ke Database");
     return true;
     }catch(Exception e){
     /* print error */
     e.printStackTrace();
     /* Set status jika tidak tersambung ke database */
     this.jlStatus.setText("Koneksi ke Database Gagal");
     return false;
     }
    }

    public Properties bacaBerkasKonfigurasi(String fileName){
    Properties p = new Properties();
    try{
    FileInputStream in =  new FileInputStream(fileName);
    /* baca konfigurasi pada berkas konfigurasi database */
    p.load(in);
    /* tutup FileInputStream */
    in.close();
    }
    catch(Exception e){
    JOptionPane.showMessageDialog(null,"Gagal Baca Berkas",
            "Konfigurasi Database MySQL : Info Baca Berkas", JOptionPane.INFORMATION_MESSAGE);
    }
    return p;
    }

Berikut bagian inisialisai komponennya, dibuat otomatis oleh Netbeans ketika mengatur komponen pada Layout.

/** 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() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        tfHost = new javax.swing.JTextField();
        tfPort = new javax.swing.JTextField();
        tfDatabase = new javax.swing.JTextField();
        tfUser = new javax.swing.JTextField();
        tfPassword = new javax.swing.JTextField();
        bSimpan = new javax.swing.JButton();
        jlStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Host");

        jLabel2.setText("Password");

        jLabel3.setText("User");

        jLabel4.setText("Port");

        jLabel5.setText("Database");

        jLabel6.setText("Konfigurasi Database MySQL ");

        tfHost.setText("localhost");

        tfPort.setText("3306");

        tfDatabase.setText("test");

        tfUser.setText("root");

        bSimpan.setText("Simpan");
        bSimpan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSimpanActionPerformed(evt);
            }
        });

        jlStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jlStatus.setText("status");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(bSimpan))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 83, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tfHost)
                            .addComponent(tfPort, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(tfDatabase, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
                            .addComponent(tfUser)
                            .addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(20, 20, 20))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(80, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jlStatus, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(73, 73, 73))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlStatus)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(bSimpan)
                .addContainerGap(65, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void bSimpanActionPerformed(java.awt.event.ActionEvent evt) {                                        

        if(cekKoneksi(this.tfHost.getText(), this.tfDatabase.getText(), this.tfPort.getText(),
                      this.tfUser.getText(), this.tfPassword.getText())){
        Properties p = new Properties();
        /* set Properties dengan nilai dari JTextField */
        p.setProperty("host", this.tfHost.getText());
        p.setProperty("db_name", this.tfDatabase.getText());
        p.setProperty("port", this.tfPort.getText());
        p.setProperty("user", this.tfUser.getText());
        p.setProperty("password", this.tfPassword.getText());
        this.simpanBerkasKonfigurasi(p, "konfigurasi database");
        }
        else{
            JOptionPane.showMessageDialog(null,"Cek Kembali parameter koneksi", "Info : Konfigurasi Koneksi Database MySQL", JOptionPane.INFORMATION_MESSAGE);
        }
    }                                       

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new KonfigurasiGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton bSimpan;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jlStatus;
    private javax.swing.JTextField tfDatabase;
    private javax.swing.JTextField tfHost;
    private javax.swing.JTextField tfPassword;
    private javax.swing.JTextField tfPort;
    private javax.swing.JTextField tfUser;
    // End of variables declaration                   

}

Berikut source codenya, belum termasuk library untuk koneksi ke MySQL. Mungkin bisa digoogling 




0 komentar:

Posting Komentar