How to get a DefaultTableModel object's data into a subclass of DefaultTableModel
Here is an example that shows how to read the data from the ResultSet and implement the getColumnClass(...)
method in your own custom DefaultTableModel:
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromDatabase extends JFrame
{
public TableFromDatabase()
{
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
try
{
// Connect to an Access Database
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
// String url = "jdbc:odbc:???"; // if using ODBC Data Source name
String url =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/directory/???.mdb";
String userid = "";
String password = "";
Class.forName( driver );
Connection connection = DriverManager.getConnection( url, userid, password );
// Read data from a table
String sql = "Select * from ???";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnLabel(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
connection.close();
}
catch(Exception e)
{
System.out.println( e );
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
@Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JTable table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
JPanel buttonPanel = new JPanel();
add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
TableFromDatabase frame = new TableFromDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
By overriding the getColumnClass(...)
method you will now see number formatted right aligned and if you ever need to sort the data it will work properly since the column will be sorted based on a numeric value not a String value.
I want to add a CheckBox to each row.
So now you have two options:
Modify the above code so that the "columnNames" Vector contains another header name for the check box column and add
Boolean.FALSE
to each "row" Vector as you iterate through the ResultSet.Use the above TableModel as is (or use the DbUtils TableModel) and then create a wrapper TableModel that will add a check box column to any existing TableModel. Check out: How to add checkbox in Jtable populated using rs2xml for an example of this approach.
How to subclass DefaultTableModel and change its dataVector
You have to override the getValueAt(...)
method:
@Override
public Object getValueAt(int row, int column) {
DataHolder data = dataVector_.get(row);
switch(column) {
case 0: return data.month;
case 1: return data.day;
case 2: return data.year;
default: return null;
}
How to Retrieve JTable Data as an Array
I take that back, on 2nd thoughts, you dont need any typecasting - TableModel is an interface that has all the 3 method calls you need. :)
Summary: Get the model for the table, check its class and typecast it to appropriate class (Abstract or Default TableModel), and use its methods to load a newly created array. Some psuedoCode:
public Object[][] getTableData (JTable table) {
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0 ; i < nRow ; i++)
for (int j = 0 ; j < nCol ; j++)
tableData[i][j] = dtm.getValueAt(i,j);
return tableData;
}
Your headers should not have changed by user-edits. Hope that helps. Regards, - M.S.
Related Topics
Java Error - Actual and Formal Argument Lists Differ in Length
How to Perform a Java Callback Between Classes
How to Make a Java Class That Implements One Interface with Two Generic Types
How to Change the Shape of a Jtabbedpane Tab
Can You Explain the Httpurlconnection Connection Process
Differencebetween A.Getclass() and A.Class in Java
Java Regex to Extract Text Between Tags
Is a Volatile Int in Java Thread-Safe
What Does the "Assert" Keyword Do
Java Linkedhashmap Get First or Last Entry
Why Does Eclipse Complain About @Override on Interface Methods
Springboot 2.6.0/Spring Fox 3 - Failed to Start Bean 'Documentationpluginsbootstrapper'
Manipulating and Comparing Floating Points in Java
Spring Resttemplate Get with Parameters
How to Put All Required Jar Files in a Library Folder Inside the Final Jar File with Maven