Pages

Saturday, 5 April 2014

JAVA create JTable using Vector() and one class

Note: This example assumes that a connection class already exists. 

/**
 * Fields
 **/
     // Connection variables.
     Connection conn = null;
     PreparedStatement pst = null;
     static ResultSet rst = null;

     private Vector columnNames = new Vector();
     private Vector data = new Vector();
     private JTable tblData = new JTable();
     private DefaultTableModel model;
    
     private JPanel pnl_Data = new JPanel();
     …
     …                              

     …

/**
 *Constructor
 **/
public Class(){
     Connect_to_database ctb = new Connect_to_database();
     conn = ctb.ConnectDb();
    
     createTable();
     …
     …   
     …
    
     pnl_Data.setBorder(new TitledBorder(null, "Data", TitledBorder.CENTER, TitledBorder.TOP, null, Color.BLUE));
     pnl_Data.setBackground(Color.WHITE);
     pnl_Data.setBounds(570, 11, 636, 850);
     contentPane.add(pnl_Data);
}

/**
 * Load table Data Method
 **/
public void reloadData(){
     columnNames.clear();
     data.clear();
          
     try {
           String sql = "SELECT * FROM User_tb“;
          
           pst = conn.prepareStatement(sql);
           rst = pst.executeQuery();

           ResultSetMetaData md = rst.getMetaData();
           int columns = md.getColumnCount();
               
           for (int i = 1; i <= columns; i++) {
                columnNames.addElement( md.getColumnName(i) );
           } while (rst.next()) {
                Vector row = new Vector(columns);
                for (int i = 1; i <= columns; i++){
                     row.addElement( rst.getObject(i) );
                }
                data.addElement( row );
           }

           rst.close();
           pst.close();
     } catch (Exception e) {
           System.out.println("Error at reloadData()" + e);
     }
}

/**
 * Create table method
 **/
public void createTable() {
     reloadData();
               
     try {
           model = new DefaultTableModel(data, columnNames);
           tblData = new JTable(model);
                    
           tblData.setBounds(10, 829, 616, -802);
           JScrollPane scroll = new JScrollPane(tblData, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
           tblData.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
           scroll.setBorder(null);
           tblData.setBorder(null);
           scroll.setPreferredSize(new Dimension(610, 809));
           pnl_Data.add(scrollCPL);
     } catch (Exception e) {
           System.out.println("Error at createTable()" + e);
     }
}

by: Michael Lashley