Pages

JTable'da Database'den Veri Listeleme (How to JTable list)


Merhaba arkadaşlar ben Emrah DEDEOĞLU bugün ki dersimizde JTable’da  database’den çekilen verileri listelemeyi anlatacağım
Projemizin Adı: EclipseJTable
Databaseimizin adı:  ders1
Tablomuzun adı: personel
Sutunları: id, adi, soyadi


TestWorking.java;



package tr.org.eclipseturkiye.emrah.test;

import javax.swing.SwingUtilities;

import tr.org.eclipseturkiye.emrah.db.RecordDao;
import tr.org.eclipseturkiye.emrah.ui.MainFrame;

public class TestWorking {
     
      public static void main(String[] args) {
           
            SwingUtilities.invokeLater(new Runnable() {
                 
                 
                  public void run() {
                       
                        new MainFrame();
                        RecordDao.initTable();
                  }
            });
      }

}
MainFrameGui.java Arayüz Kısmı
package tr.org.eclipseturkiye.emrah.ui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import tr.org.eclipseturkiye.emrah.db.RecordDao;
import tr.org.eclipseturkiye.emrah.domain.PersonelDomain;

public class MainFrame extends JFrame {

      public MainFrame() {

            initFrame();
      }

      public void initFrame() {
            JPanel panel = initPanel();

            add(panel);

            setTitle("eclipseturkiye.blogspot.com");
            pack();
            setVisible(true);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      }

      public JPanel initPanel() {
            JPanel panel = new JPanel(new BorderLayout());
            JPanel kayitPanel = new JPanel(new GridLayout(3, 2, 2, 2));

            JLabel adiJLabel = new JLabel("Adı:", JLabel.RIGHT);
            kayitPanel.add(adiJLabel);
            final JTextField adiField = new JTextField(10);
            kayitPanel.add(adiField);
            JLabel soyadiJLabel = new JLabel("Soyadı:", JLabel.RIGHT);
            kayitPanel.add(soyadiJLabel);
            final JTextField soyadiField = new JTextField(10);
            kayitPanel.add(soyadiField);
            JButton kaydetButton = new JButton("Kaydet");
            kayitPanel.add(kaydetButton);
            kaydetButton.addActionListener(new ActionListener() {
                 
                 
                  public void actionPerformed(ActionEvent arg0) {
                       
                        PersonelDomain kisiDomain = new PersonelDomain();
                       
                        kisiDomain.setAdi(adiField.getText());
                        kisiDomain.setSoyadi(soyadiField.getText());
                       
                        RecordDao.insertUser(kisiDomain);
                        System.out.println("Kayıt Başarılı");
                  }
            });
           

            String dizi[] = { "id", "adi", "soyadi" };
            DefaultTableModel model = new DefaultTableModel(dizi, 0);
            JTable table = new JTable(model);
            JScrollPane pane = new JScrollPane(table);
           
           
            /**LİSTELEME ALGORİTMASI**/
           
            for(PersonelDomain list : RecordDao.listele()){
                 
                  model.addRow(list.getObjects());
                 
            }
           
           
            panel.add(kayitPanel, BorderLayout.CENTER);
            panel.add(pane, BorderLayout.SOUTH);

            return panel;

      }

}

PersonelDomain.java
package tr.org.eclipseturkiye.emrah.domain;

public class PersonelDomain {
     
      private int id;
      private String adi;
      private String soyadi;
      public int getId() {
            return id;
      }
      public void setId(int id) {
            this.id = id;
      }
      public String getAdi() {
            return adi;
      }
      public void setAdi(String adi) {
            this.adi = adi;
      }
      public String getSoyadi() {
            return soyadi;
      }
      public void setSoyadi(String soyadi) {
            this.soyadi = soyadi;
      }
     
     
      /**Listelemeyi Sağlamak object dizi döndüren method belirledik**/
      public Object [] getObjects(){
           
            Object [] listveriler = {id,adi,soyadi};
           
            return listveriler;
      }

}

RecordDao.java
package tr.org.eclipseturkiye.emrah.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import tr.org.eclipseturkiye.emrah.domain.PersonelDomain;

public class RecordDao {

      private static String url = "jdbc:mysql://localhost/ders1?useUnicode=true&characterEncoding=UTF-8";
      private static String user = "root";
      private static String pass = "";

      static {

            try {
                  Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }


      public static Connection getConnection() {

            Connection conn = null;

            try {
                  conn = DriverManager.getConnection(url, user, pass);
            } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }

            return conn;

      }

      public static void initTable() {
            try {
                  Connection conn = getConnection();
                  Statement sorgu = conn.createStatement();

                  sorgu.executeUpdate("CREATE TABLE personel(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, adi VARCHAR (50) NOT NULL, soyadi VARCHAR(50) NOT NULL) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_turkish_ci");

                  sorgu.close();
                  conn.close();

            } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  // e.printStackTrace();
            }
      }

      public static void insertUser(PersonelDomain kayit) {
            try {
                  Connection conn = getConnection();
                  Statement stmt = conn.createStatement();

                  stmt.executeUpdate("INSERT INTO personel (adi, soyadi) VALUES ('"
                             + kayit.getAdi() + "','" + kayit.getSoyadi() + "')");

                  stmt.close();
                  conn.close();

            } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  // e.printStackTrace();
            }
      }

      public static List<PersonelDomain> listele() {

            List<PersonelDomain> liste = new ArrayList<PersonelDomain>();

            try {
                  Connection conn = getConnection();
                  Statement stmt = conn.createStatement();

                  ResultSet rs = stmt.executeQuery("SELECT * FROM personel");

                  while (rs.next()) {

                        PersonelDomain siradakiKisiDomain = new PersonelDomain();
                        siradakiKisiDomain.setId(rs.getInt("id"));
                        siradakiKisiDomain.setAdi(rs.getString("adi"));
                        siradakiKisiDomain.setSoyadi(rs.getString("soyadi"));

                        liste.add(siradakiKisiDomain);
                  }

                  stmt.close();
                  conn.close();

            } catch (SQLException e) {
                 
                  System.out.println(e);
            }
            return liste;

      }

}

Arkadaşlar kısaca projenin tüm kaynak kodları bu şekilde… bizim için önemli olan Üç kısım var.
Biri arayüz de listelemeyi sağlayan döngü, 2 Domainde object olarak verileri çekmeyi sağlayan Object dizi diğeri ise RecordDao da listeleme yapan kod;
Şimdi bu önemli yerleri sizinle paylaşıyorum;
Database Kısmı
public static List<PersonelDomain> listele() {

            List<PersonelDomain> liste = new ArrayList<PersonelDomain>();

            try {
                  Connection conn = getConnection();
                  Statement stmt = conn.createStatement();

                  ResultSet rs = stmt.executeQuery("SELECT * FROM personel");

                  while (rs.next()) {

                        PersonelDomain siradakiKisiDomain = new PersonelDomain();
                        siradakiKisiDomain.setId(rs.getInt("id"));
                        siradakiKisiDomain.setAdi(rs.getString("adi"));
                        siradakiKisiDomain.setSoyadi(rs.getString("soyadi"));

                        liste.add(siradakiKisiDomain);
                  }

                  stmt.close();
                  conn.close();

            } catch (SQLException e) {
                 
                  System.out.println(e);
            }
            return liste;

      }

}

Domain Kısmı;
/**Listelemeyi Sağlamak için object dizi döndüren method belirledik**/
      public Object [] getObjects(){
           
            Object [] listveriler = {id,adi,soyadi};
           
            return listveriler;
      }

}

Arayüz Kısmı;



/**LİSTELEME ALGORİTMASI
*for ile RecordDao class’ın da bulunan  listele methodunda ki veriler DefaultTable model içerisine atılıyor.
**/
           
            for(PersonelDomain list : RecordDao.listele()){
                 
                  model.addRow(list.getObjects());
                 
            }

Bu üç durumu gerçekleştirdikten sonra JTable da veriler listelenecektir.
Kısaca JTable’da listeleme bu şekilde gerçekleşmektedir.

Not: Bu Ders Emrah DEDEOĞLU tarafından yazılmıştır içerisinde kullanılan örnekler denenmiş ve olumlu sonuç alınmıştır.


Share on Google Plus

About eclipseturkiye

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

4 yorum: