Java JTable
March 12, 2007
been a long time not updating my blog.. tsk tsk tsk.. heheeh but anyway.. after reading books, making some experiments, googling, i finally learn how to use Java JTable. here’s how i did it.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import oracle.jdbc.pool.OracleDataSource;
public class myTable {
/** Creates a new instance of myTable */
public myTable() {
}
public void createTable() throws SQLException {
OracleDataSource ods = new OracleDataSource(); // create a new database connection instance
ods.setURL(url);
ods.setUser(user);
ods.setPassword(pass);
System.out.println(“Connected”); //print if the connection is susccessful
Connection conn = ods.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT PRODUCTCODE, GENERIC, BRAND, DESCRIPTION from PRODUCT ORDER by GENERIC”);
Vector rowData = new Vector(); // this will be used as a parameter of your table
while (rs.next()) {
Vector row = new Vector();
row.addElement(rs.getString(“GENERIC”));
row.addElement(rs.getString(“BRAND”));
row.addElement(rs.getString(“DESCRIPTION”));
row.addElement(rs.getString(“PRODUCTCODE”));
rowData.addElement(row);
}
Vector columnName = new Vector();
columnName.addElement(“GENERIC”); //this is the header of the table
columnName.addElement(“BRAND”);
columnName.addElement(“DESCRIPTION”);
columnName.addElement(“PRODUCTCODE”);
JTable table = new JTable(rowData, columnName); // create the table
JScrollPane jsp = new JScrollPane(table); //create a scrollpane and add the table inside the scrollpane
JFrame myFrame = new JFrame(); //create a Frame
myFrame.add(jsp); // add the scrollpane to the frame
myFrame.setSize(800,600); //set the size of the frame
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true); //display the table
}
public static void main(String args[]) throws SQLException {
myTable m = new myTable(); //create an instance of our myTable class
m.createTable();
}
private String url = “jdbc:oracle:thin:@//localhost:1521/database”;
private String user = “user”;
private String pass = “password”;
}
Entry Filed under: Java. .
Trackback this post | Subscribe to the comments via RSS Feed