How to display column name and set scrollbar to jtable? - java

connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
table_1.setModel(buildTableModel(result));
method:
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
result:

You need to wrap your JTable inside a JScrollPane, and add the resulting JScrollPane to your layout.
The sample code you provided does not show how you're adding the JTable to the JPanel or JFrame of your application.

Found a solution:
I put a JScrollPane in jframe then use following code:
connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
JTable t=new JTable();
t.setModel(buildTableModel(result));
s1.setViewportView(t);
s1 is JScrollPane.
Output:

Related

jtable take time to display data from db

I am reading data from SQL database and displaying it in a Jtable; then I am adding other columns and doing some calculations... The display time of data in Jtable is long even if the number of rows is low. Any hint pleaaaase?
public JTable display () throws ClassNotFoundException, SQLException, ParseException{
java.sql.Connection sqlConnection = null;
sqlConnection = getSQLConnection();
Statement stmt = null;
stmt = sqlConnection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT OFINTERNE,CMDCLIENT,CHAINE,REF,QTE,QTEBAC,DELAI,EFFECTIF,RENDEMENT,TPSn,"
+ "dateCreation,QTEPROD,datedebutpce,datedebutbac,datefinpce,termine from TEST_LAMIAA where OFINTERNE<3000 "
+ "order by chaine");
ResultSetMetaData rsmetaData = rs.getMetaData();
//stores the number of columns
int colmns = rsmetaData.getColumnCount();
// the object that will pass data to the jTable
DefaultTableModel dtm = new DefaultTableModel();
Vector cl_names = new Vector();
Vector data_rows = new Vector();
for(int i = 1; i<(colmns+1); i++){
cl_names.addElement(rsmetaData.getColumnName(i));
}
dtm.setColumnIdentifiers(cl_names);
while(rs.next()){
data_rows = new Vector();
for(int j = 1; j <(colmns+1) ; j++){
data_rows.addElement(rs.getString(j));
// System.out.println(rs.getString(j));
}
dtm.addRow(data_rows);
}
//pass default model object into my table
jTable1.setModel(dtm);
//adding columns
TableColumn col = new TableColumn(dtm.getColumnCount() - 1);
col.setHeaderValue("Sequence");
jTable1.addColumn(col);
dtm.addColumn(col);
TableColumn date = new TableColumn(dtm.getColumnCount() - 1);
date.setHeaderValue("Date");
jTable1.addColumn(date);
dtm.addColumn(date);
TableColumn duree = new TableColumn(dtm.getColumnCount() - 1);
duree.setHeaderValue("Duree");
jTable1.addColumn(duree);
dtm.addColumn(duree);
TableColumn datFin = new TableColumn(dtm.getColumnCount() - 1);
datFin.setHeaderValue("Date Fin");
jTable1.addColumn(datFin);
dtm.addColumn(datFin);
jTable1.setModel(dtm);
return jTable1;
}

DefaultTableModel in a JFrame only creating on Row - JAVA

Im trying to get a number of rows from a database to populate a JTable in a JFrame but its only getting the first row/entry (row 1 always). Its a list of houses + details stored in a table
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = (ResultSetMetaData) rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount-1; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
How do I print out at all the rows in the table rather than just the first?
public void displaySaleProperties() throws SQLException{
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected to database.");
// The Connection is obtained
Statement Stmt = (Statement) conn.createStatement();
// Stmt.execute(createPropertyTable);
ResultSet rs = Stmt.executeQuery("select * from PropertySale");
// It creates and displays the table
JTable table = new JTable(buildTableModel(rs));
table.setPreferredSize(new Dimension(1150,17));
// JOptionPane.showMessageDialog(null, new JScrollPane(table));
final JPanel panelOne = new JPanel();
panelOne.setVisible(true);
panelOne.setBackground(Color.LIGHT_GRAY);
// JFRAME
final JFrame topFrame = new JFrame();
topFrame.setSize(1200, 300);
topFrame.setLocationRelativeTo ( null );
topFrame.setVisible(true);
topFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// PUT TOGETHER
topFrame.add(panelOne);
panelOne.add(table);
panelOne.revalidate();
panelOne.repaint();
// Closes the Connection
} catch (SQLException e) {
System.err.println("Cannot connect to database." + e);
} finally {
if(conn != null){
conn.close();
}
}
}
Remove the line with:
table.setPreferredSize(new Dimension(1150,17));
In another way, may you want to use a scroll pane:
JTable table = new JTable(buildTableModel(rs));
JScrollPane scrollPane = new JScrollPane(table);
topFrame.add(scrollPane);

Refresh JTable data after updating database

I have a JTable that I created with the Netbeans GUI creator and populated the table by using Vector objects. I want the table to be updated after a change is made to the database. I'm not sure how to do this. Could anyone please guide me through doing this?
Try to put this after your update code
rs=st.executeQuery("select * from Table order by columnName");
table.setModel(buildTableModel(rs));
//Create function
private TableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 0; column < columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}

Unable to display header for jTable

These are my codes for my jTable in java swing.
private JTable getJTable() {
if (jTable == null) {
Vector columnNames = new Vector(); //Vector class allows dynamic array of objects
Vector data = new Vector();
JPanel panel = new JPanel();
panel.setSize(new Dimension(198, 106));
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select * from forumTopics";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}
String header[] = {"description", "title", "category", "posted by"};
for(int i=0;i<jTable.getColumnCount();i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel().getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.setBounds(new Rectangle(82, 218, 736, 292));
jTable.setEnabled(false);
jTable.setRowHeight(50);
jTable.getRowHeight();
}
return jTable;
}
I set an array for the header of my table. However, the program only shows the data inside my database without any header. Can somebody please enlighten me? Thanks in advance.
Put your JTable in JScrollPane like
add(new JScrollPane( getJTable() ) );

JTable swing import database sql

Could someone provide me with an example or tutorial on how to import a data from a mysql database within a JTable within the use of a GUI. I tried looking for an example but have not found anything.
Hopefully we can put this question to rest
Connection db = DriverManager.getConnection( jdbc:mysql://192.168.0.3:3306,<user>,<password>);
Statement stmt = db.createStatement();
PreparedStatement psmt = con.prepareStatement("SELECT * FROM DB");
ResultSet rs = psmt.executeQuery();
// get column names
int len = rs.getMetaData().getColumnCount();
Vector cols= new Vector(len);
for(int i=1; i<=len; i++) // Note starting at 1
cols.add(rs.getMetaData().getColumnName(i));
// Add Data
Vector data = new Vector();
while(rs.next())
{
Vector row; = new Vector(len);
for(int i=1; i<=len; i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
// Now create the table
JTable table = new JTable(data, cols);

Categories

Resources