/**
*
*/
package de.tutorials;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
/**
* @author Tom
*
*/
public class DynamicJTableExample extends JFrame {
private JTextField txtSQLCommand;
private JButton btnExecuteSQL;
private JTable tblSQLData;
private MysqlDataSource mds;
public DynamicJTableExample() {
super("DynamicJTableExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
tblSQLData = new JTable();
JScrollPane scrollPane = new JScrollPane(tblSQLData);
scrollPane.setPreferredSize(new Dimension(400, 300));
btnExecuteSQL = new JButton("Execute");
btnExecuteSQL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
con = mds.getConnection();
String sqlStatement = txtSQLCommand.getText();
if (sqlStatement == null || "".equals(sqlStatement)) {
return;
}
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sqlStatement);
DefaultTableModel dtm = buildTableModelFrom(rs);
tblSQLData.setModel(dtm);
tblSQLData.updateUI();
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
throw new RuntimeException(e1);
}
}
}
}
});
txtSQLCommand = new JTextField(15);
add(scrollPane, BorderLayout.NORTH);
add(txtSQLCommand, BorderLayout.CENTER);
add(btnExecuteSQL, BorderLayout.EAST);
initDataSource();
pack();
setVisible(true);
}
private void initDataSource() {
mds = new MysqlDataSource();
mds.setUser("root");
mds.setPassword("");
mds.setServerName("localhost");
mds.setPort(3306);
mds.setDatabaseName("test");
}
private DefaultTableModel buildTableModelFrom(ResultSet rs)
throws Exception {
ResultSetMetaData rsmd = rs.getMetaData();
int clmCnt = rsmd.getColumnCount();
Object[] columnNames = new Object[clmCnt];
for (int i = 1; i <= columnNames.length; i++) {
columnNames[i - 1] = rsmd.getColumnName(i);
}
List rows = new ArrayList();
while (rs.next()) {
Object[] row = new Object[clmCnt];
for (int i = 1; i <= clmCnt; i++) {
row[i - 1] = rs.getString(i);
}
rows.add(row);
}
return new ListBasedTableModel(rows, columnNames);
}
/**
* @param args
*/
public static void main(String[] args) {
new DynamicJTableExample();
}
class ListBasedTableModel extends DefaultTableModel{
List data;
public ListBasedTableModel(List data, Object[] columnNames){
super(columnNames,data.size());
this.data = data;
}
public Object getValueAt(int row, int column) {
return ((Object[])data.get(row))[column];
}
}
}