Here is my first table I ever created, it works by connecting to a MS Access database, which connects using ODBC connection.
Note; This code was only done to verify I could make it work, thus it should be commented and organized a little better.
The retrieveData routine section is the database call.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.sql.*;
import logfile.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
public class TableTest extends JFrame {
/**
* Description of the Field
*/
protected JTable m_table;
/**
* Description of the Field
*/
protected StorageTableData m_data;
/**
* Description of the Field
*/
protected JLabel m_title;
private JPanel panel12;
private JTextField txtName;
private JButton cmdQuery;
private logfile logName;
/**
* Constructor for the TableTest object
*/
public TableTest() {
// Frame Caption
super("Table Test");
setSize(600, 300);
m_data = new StorageTableData();
// Create ErrorLog
logName = new logfile();
// TestField and JButton
panel12 = new JPanel();
panel12.setLayout(new BoxLayout(panel12, BoxLayout.X_AXIS));
panel12.add(Box.createRigidArea(new Dimension(25, 0)));
txtName = new JTextField(10);
panel12.add(txtName);
panel12.add(Box.createRigidArea(new Dimension(34, 0)));
cmdQuery = new JButton("Query");
cmdQuery.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Dean2;
Dean2 = txtName.getText();
m_data.retrieveData(Dean2);
System.out.println("Error");
logName.write_to_log("Searching for " + Dean2);
//m_table.repaint();
}
});
panel12.add(cmdQuery);
getContentPane().add(panel12, BorderLayout.NORTH);
m_table = new JTable();
m_table.setAutoCreateColumnsFromModel(false);
m_table.setModel(m_data);
for (int k = 0; k < StorageTableData.m_columns.length; k++) {
DefaultTableCellRenderer renderer = new
ColoredTableCellRenderer();
renderer.setHorizontalAlignment(
StorageTableData.m_columns[k].m_alignment);
TableColumn column = new TableColumn(k,
StorageTableData.m_columns[k].m_width, renderer, null);
m_table.addColumn(column);
}
JTableHeader header = m_table.getTableHeader();
header.setUpdateTableInRealTime(true);
header.addMouseListener(m_data.new ColumnListener(m_table));
header.setReorderingAllowed(true);
m_table.getColumnModel().addColumnModelListener(
m_data.new ColumnMovementListener());
JScrollPane ps = new JScrollPane();
ps.getViewport().add(m_table);
getContentPane().add(ps, BorderLayout.CENTER);
WindowListener wndCloser =
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
/**
* Description of the Method
*
*@param argv Description of Parameter
*/
public static void main(String argv[]) {
new TableTest();
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColoredTableCellRenderer extends DefaultTableCellRenderer {
/**
* Sets the value attribute of the ColoredTableCellRenderer object
*
*@param value The new value value
*/
public void setValue(Object value) {
super.setValue(value);
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class StorageData {
/**
* Description of the Field
*/
public String m_symbol;
/**
* Description of the Field
*/
public String m_name;
/**
* Description of the Field
*/
public String m_date;
/**
* Description of the Field
*/
public String m_type;
/**
* Description of the Field
*/
public String m_description;
/**
* Constructor for the StorageData object
*
*@param symbol Description of Parameter
*@param name Description of Parameter
*@param date Description of Parameter
*@param type Description of Parameter
*@param description Description of Parameter
*/
public StorageData(String symbol, String name, String date,
String type, String description) {
m_symbol = symbol;
m_name = name;
m_date = date;
m_type = type;
m_description = description;
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColumnData {
/**
* Description of the Field
*/
public String m_title;
/**
* Description of the Field
*/
public int m_width;
/**
* Description of the Field
*/
public int m_alignment;
/**
* Constructor for the ColumnData object
*
*@param title Description of Parameter
*@param width Description of Parameter
*@param alignment Description of Parameter
*/
public ColumnData(String title, int width, int alignment) {
m_title = title;
m_width = width;
m_alignment = alignment;
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class StorageTableData extends AbstractTableModel {
/**
* Description of the Field
*/
public final static ColumnData m_columns[] = {
new ColumnData("Code ID", 100, JLabel.LEFT),
new ColumnData("Name", 160, JLabel.LEFT),
new ColumnData("Date", 100, JLabel.RIGHT),
new ColumnData("Type", 100, JLabel.RIGHT),
new ColumnData("Description", 100, JLabel.RIGHT),
};
/**
* Description of the Field
*/
protected SimpleDateFormat m_frm;
/**
* Description of the Field
*/
protected Vector m_vector;
/**
* Description of the Field
*/
protected java.util.Date m_date;
/**
* Description of the Field
*/
protected int m_columnsCount = m_columns.length;
/**
* Description of the Field
*/
protected int m_sortCol = 0;
/**
* Description of the Field
*/
protected boolean m_sortAsc = true;
/**
* Description of the Field
*/
protected int m_result = 0;
/**
* Constructor for the StorageTableData object
*/
public StorageTableData() {
m_frm = new SimpleDateFormat("MM/dd/yyyy");
m_vector = new Vector();
setDefaultData();
}
/**
* Sets the defaultData attribute of the StorageTableData object
*/
public void setDefaultData() {
try {
m_date = m_frm.parse("4/6/1999");
}
catch (java.text.ParseException ex) {
m_date = null;
}
m_vector.removeAllElements();
//m_vector.addElement(new StorageData("ORCL", "Oracle Corp.",
// 23.6875, 25.375, -1.6875));
Collections.sort(m_vector, new
StockComparator(m_sortCol, m_sortAsc));
}
/**
* Sets the valueAt attribute of the StorageTableData object
*
*@param value The new valueAt value
*@param row The new valueAt value
*@param col The new valueAt value
*/
public void setValueAt(Object value, int row, int col) {
fireTableCellUpdated(row, col);
}
/**
* Gets the rowCount attribute of the StorageTableData object
*
*@return The rowCount value
*/
public int getRowCount() {
return m_vector == null ? 0 : m_vector.size();
}
/**
* Gets the columnCount attribute of the StorageTableData object
*
*@return The columnCount value
*/
public int getColumnCount() {
return m_columnsCount;
}
/**
* Gets the columnName attribute of the StorageTableData object
*
*@param column Description of Parameter
*@return The columnName value
*/
public String getColumnName(int column) {
String str = m_columns[column].m_title;
if (column == m_sortCol) {
str += m_sortAsc ? " �" : " �";
}
return str;
}
/**
* Gets the cellEditable attribute of the StorageTableData object
*
*@param nRow Description of Parameter
*@param nCol Description of Parameter
*@return The cellEditable value
*/
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
/**
* Gets the valueAt attribute of the StorageTableData object
*
*@param nRow Description of Parameter
*@param nCol Description of Parameter
*@return The valueAt value
*/
public Object getValueAt(int nRow, int nCol) {
if (nRow < 0 | | nRow >= getRowCount()) {
return "";
}
StorageData row = (StorageData) m_vector.elementAt(nRow);
switch (nCol) {
case 0:
return row.m_symbol;
case 1:
return row.m_name;
case 2:
return row.m_date;
case 3:
return row.m_type;
case 4:
return row.m_description;
}
return "";
}
/**
* Gets the title attribute of the StorageTableData object
*
*@return The title value
*/
public String getTitle() {
if (m_date == null) {
return "Dean's Tester";
}
return "No date " + m_frm.format(m_date);
}
/**
* Description of the Method
*
*@param Dean Description of Parameter
*@return Description of the Returned Value
*/
public int retrieveData(String Dean) {
final String query = "select Code_ID, Code_Name, Code_Date, Type_Name, Code_Description from Code,Type WHERE (Code_Name like '%" + Dean + "%' or Code_Description like '%" + Dean + "%' or Code like '%" + Dean + "%') and Code_Type_Seq_id=Type_Seq_id;";
System.out.println(query);
Thread runner =
new Thread() {
public void run() {
Connection conn;
Statement stmt;
ResultSet results;
try {
// Load the JDBC-ODBC bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(
"jdbc

dbc:Test", "admin", "");
System.out.println("Error2");
stmt = conn.createStatement();
System.out.println("Error2.1");
results = stmt.executeQuery(query);
System.out.println("Error3");
boolean hasData = false;
m_vector.removeAllElements();
while (results.next()) {
if (!hasData) {
hasData = true;
}
System.out.println("Error4");
String symbol = results.getString(1);
String name = results.getString(2);
DateFormat dateFormatter;
Locale currentLocale = new Locale("en", "US");
dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, currentLocale);
String date = dateFormatter.format(results.getDate(3));
String type = results.getString(4);
String change = results.getString(5);
m_vector.addElement(new StorageData(symbol, name, date, type, change));
System.out.println("Error11");
}
System.out.println("Close Files");
results.close();
stmt.close();
conn.close();
fireTableStructureChanged();
if (!hasData) {
// We've got nothing
m_result = 1;
}
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Load data error: " + e.toString());
m_result = -1;
}
finally {
Collections.sort(m_vector,
new StockComparator(m_sortCol, m_sortAsc));
m_result = 0;
}
}
};
runner.start();
return m_result;
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColumnListener extends MouseAdapter {
/**
* Description of the Field
*/
protected JTable m_table;
/**
* Constructor for the ColumnListener object
*
*@param table Description of Parameter
*/
public ColumnListener(JTable table) {
m_table = table;
}
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void mouseClicked(MouseEvent e) {
TableColumnModel colModel = m_table.getColumnModel();
int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();
if (modelIndex < 0) {
return;
}
if (m_sortCol == modelIndex) {
m_sortAsc = !m_sortAsc;
}
else {
m_sortCol = modelIndex;
}
for (int i = 0; i < m_columnsCount; i++) {
//NEW
TableColumn column = colModel.getColumn(i);
column.setHeaderValue(getColumnName(column.getModelIndex()));
}
m_table.getTableHeader().repaint();
Collections.sort(m_vector, new
StockComparator(modelIndex, m_sortAsc));
m_table.tableChanged(
new TableModelEvent(StorageTableData.this));
m_table.repaint();
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColumnMovementListener implements TableColumnModelListener {
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnAdded(TableColumnModelEvent e) {
m_columnsCount++;
}
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnRemoved(TableColumnModelEvent e) {
m_columnsCount--;
if (m_sortCol >= e.getFromIndex()) {
m_sortCol = 0;
}
}
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnMarginChanged(ChangeEvent e) { }
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnMoved(TableColumnModelEvent e) { }
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnSelectionChanged(ListSelectionEvent e) { }
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class StockComparator implements Comparator {
/**
* Description of the Field
*/
protected int m_sortCol;
/**
* Description of the Field
*/
protected boolean m_sortAsc;
/**
* Constructor for the StockComparator object
*
*@param sortCol Description of Parameter
*@param sortAsc Description of Parameter
*/
public StockComparator(int sortCol, boolean sortAsc) {
m_sortCol = sortCol;
m_sortAsc = sortAsc;
}
/**
* Description of the Method
*
*@param o1 Description of Parameter
*@param o2 Description of Parameter
*@return Description of the Returned Value
*/
public int compare(Object o1, Object o2) {
if (!(o1 instanceof StorageData) | | !(o2 instanceof StorageData)) {
return 0;
}
StorageData s1 = (StorageData) o1;
StorageData s2 = (StorageData) o2;
int result = 0;
result = s1.m_symbol.compareTo(s2.m_symbol);
if (!m_sortAsc) {
result = -result;
}
return result;
}
/**
* Description of the Method
*
*@param obj Description of Parameter
*@return Description of the Returned Value
*/
public boolean equals(Object obj) {
if (obj instanceof StockComparator) {
StockComparator compObj = (StockComparator) obj;
return (compObj.m_sortCol == m_sortCol) &&
(compObj.m_sortAsc == m_sortAsc);
}
return false;
}
}
Let me know, if you need anything else.
Dean