Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.02 KB | None | 0 0
  1. /**
  2.  * This model work with any database table. You should only set an object of java.sql.ResultSet into it.
  3.  * This table cannot insert data into database.
  4.  */
  5.  
  6. import java.util.*;
  7. import java.sql.*;
  8. import java.awt.*;
  9. import java.awt.event.ActionEvent;
  10. import java.awt.event.ActionListener;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13. import javax.swing.table.*;
  14. import javax.swing.*;
  15.  
  16. public class DatabaseTableModel extends AbstractTableModel {
  17.     private static final long serialVersionUID = 1L;
  18.     private ArrayList<String> columnNames = new ArrayList<String>();
  19.     private ArrayList<Class> columnTypes = new ArrayList<Class>();
  20.     private ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
  21.  
  22.     public int getRowCount() {
  23.         synchronized (data) {
  24.             return data.size();
  25.         }
  26.     }
  27.  
  28.     public int getColumnCount() {
  29.         return columnNames.size();
  30.     }
  31.  
  32.     public Object getValueAt(int row, int col) {
  33.         synchronized (data) {
  34.             return data.get(row).get(col);
  35.         }
  36.     }
  37.  
  38.     public String getColumnName(int col) {
  39.         return columnNames.get(col);
  40.     }
  41.  
  42.     public Class getColumnClass(int col) {
  43.         return columnTypes.get(col);
  44.     }
  45.  
  46.     public boolean isCellEditable(int row, int col) {
  47.         return true;
  48.     }
  49.  
  50.     public void setValueAt(Object obj, int row, int col) {
  51.         synchronized (data) {
  52.             data.get(row).set(col, obj);
  53.         }
  54.     }
  55.  
  56.     /**
  57.      * Core of the model. Initializes column names, types, data from ResultSet.
  58.      *
  59.      * @param rs ResultSet from which all information for model is token.
  60.      * @throws SQLException
  61.      * @throws ClassNotFoundException
  62.      */
  63.     public void setDataSource(ResultSet rs) throws SQLException, ClassNotFoundException {
  64.         ResultSetMetaData rsmd = rs.getMetaData();
  65.         columnNames.clear();
  66.         columnTypes.clear();
  67.         data.clear();
  68.  
  69.         int columnCount = rsmd.getColumnCount();
  70.         for (int i = 0; i < columnCount; i++) {
  71.             columnNames.add(rsmd.getColumnName(i + 1));
  72.             Class type = Class.forName(rsmd.getColumnClassName(i + 1));
  73.             columnTypes.add(type);
  74.         }
  75.         fireTableStructureChanged();
  76.         while (rs.next()) {
  77.             ArrayList rowData = new ArrayList();
  78.             for (int i = 0; i < columnCount; i++) {
  79.                 if (columnTypes.get(i) == String.class)
  80.                     rowData.add(rs.getString(i + 1));
  81.                 else
  82.                     rowData.add(rs.getObject(i + 1));
  83.             }
  84.             synchronized (data) {
  85.                 data.add(rowData);
  86.                 this.fireTableRowsInserted(data.size() - 1, data.size() - 1);
  87.             }
  88.         }
  89.     }
  90.  
  91.     //***TEST***
  92.     public static void main(String[] args) {
  93.        
  94.         try {
  95.             Class.forName("com.mysql.jdbc.Driver");
  96.             String url = "localhost:3306/base";                //your data
  97.             String user = "root";                  //your data
  98.             String password = "root";               //your data
  99.             String query = "select * from people";  //your data
  100.             Connection con = DriverManager.getConnection("jdbc:mysql://" + url, user, password);
  101.             Statement st = con.createStatement();
  102.             ResultSet rs = st.executeQuery(query);
  103.             DatabaseTableModel model = new DatabaseTableModel();
  104.             model.setDataSource(rs);
  105.             JTable table = new JTable(model);
  106.             JScrollPane panelScroll = new JScrollPane(table);
  107.            
  108.             JPanel panelButt = new JPanel();
  109.             panelButt.setPreferredSize(new Dimension(150, 100));
  110.            
  111.             JButton buttonAdd = new JButton("Add");
  112.             buttonAdd.addActionListener(new ActionListener() {
  113.                 @Override
  114.                 public void actionPerformed(ActionEvent e) {
  115.                     try {
  116.                         Statement stmt = con.createStatement();
  117.                         String sql = "INSERT INTO Registration " +
  118.                                 "VALUES (100, 'Zara', 'Ali', 18)";
  119.                         stmt.executeUpdate(sql);
  120.                     } catch (SQLException ex) {
  121.                         Logger.getLogger(DatabaseTableModel.class.getName()).log(Level.SEVERE, null, ex);
  122.                     }
  123.                 }
  124.             });
  125.             panelButt.add(buttonAdd);
  126.            
  127.            
  128.             JFrame frame = new JFrame("Database Table Model");
  129.            
  130.             //frame.add(panelScroll);
  131.             frame.add(panelButt,BorderLayout.WEST);
  132.             frame.setLocationRelativeTo(null);
  133.             frame.setSize(500, 400);
  134.             frame.pack();
  135.             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  136.             frame.setVisible(true);
  137.  
  138.         } catch (SQLException e) {
  139.             e.printStackTrace();
  140.         } catch (ClassNotFoundException e) {
  141.             e.printStackTrace();
  142.         }
  143.     }
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement