I am using JTable in swing to display a MySQL table, although the table values are present in the row object (as in the output in screenshot) but jtable in the application is empty.
The output in the screenshot shoes the Object[] array but when I pass this in the addRow method, it doesn't show anything on the JTable GUI.
private void tableSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {
//fetch the name of the database to be created
String dbName = tableDBName.getText();
//fetch the root password
String password = new String(tableDBPass.getPassword());
// fetch table name
String tableName = tableTableName.getText();
DefaultTableModel tableModel = (DefaultTableModel)tableViewTable.getModel();
int rowCount = tableModel.getRowCount();
for(int i = 0; i<rowCount; i++){
tableModel.removeRow(0);
}
try{
// create connection
CreateConnection newCon = new CreateConnection();
Statement newStat = newCon.initiate(dbName, password);
// result set contains the data fetched from the MySQL table
ResultSet rs = newStat.executeQuery("select * from "+tableName);
// get column names and column count
ResultSetMetaData metaData = rs.getMetaData();
int n_columns = metaData.getColumnCount();
ArrayList<String> columnNames = new ArrayList<>();
for(int i = 1; i<=n_columns; i++){
columnNames.add(metaData.getColumnName(i));
}
while(rs.next()){
ArrayList row = new ArrayList(n_columns);
for(int i = 1; i<=n_columns; i++){
row.add(rs.getObject(i));
}
Object[] obj = row.toArray();
tableModel.addRow(obj);
System.out.println("table updated..: "+Arrays.toString(obj));
}
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
Besides this I deleted all the rows that are initially present when you insert the JTable in the form.
DefaultTableModel tableModel = (DefaultTableModel)tableViewTable.getModel();
So you start with an empty TableModel, which means the model has no columns or rows.
So even though you invoke the addRow() method, your model has no columns so there is nothing to display in the JTable
ArrayList<String> columnNames = new ArrayList<>();
for(int i = 1; i<=n_columns; i++){
columnNames.add(metaData.getColumnName(i));
}
The above code does nothing. All it does is add some data to an ArrayList, but that ArrayList is never used.
What you want to do is:
Use a Vector, not an ArrayList
Then you need to create an empty DefaultTableModel with just the columns names. Read the API for the appropriate constructor.
Then in your logic that iterates through the ResultSet you want to:
Again use a Vector for each row of data
add the data to the Vector
invoke the addRow(...) method of the model. The model will also accept a Vector so there is no need to convert it to an array
After all the data is added to the model you then need to:
Use tableModelView.setModel(...) to replace the model in your table.
Now your table model will have both columns and rows of data.
Related
I want to display column name row while accessing table. Here I tried this code... but only table displayed without column name.
using java eclipse and sqlite database
try
{
String query="Select * from client";
PreparedStatement pst=conn.prepareStatement(query);
ResultSet rs=pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
DefaultTableModel tm = (DefaultTableModel) table.getModel();
for(int i=1;i<=columnCount;i++)
{
tm.addColumn(rsmd.getColumnName(i));
}
while (rs.next())
{
String[] a = new String[columnCount];
for(int i = 0; i < columnCount; i++)
{
a[i] = rs.getString(i+1);
}
tm.addRow(a);
// tm.fireTableDataChanged();
rs.close();
pst.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
You can use following code to get column names:
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount(); // get column count
for (int i = 1; i <= count; i++){
System.out.println(metaData.getColumnLabel(i));
}
ResultSet always contains the returned rows but not the column names.
To get the column names you can use below code.
ResultSetMetaData metadata = rs.getMetaData();
int columnCount = metadata.getColumnCount();
String column_names[] = new String[ columnCount ]; // define a array to store the column names
for (int i=0; i<=columnCount; i++) {
column_names[ i ] = metadata.getColumnLabel(i); // push column names into array
}
DefaultTableModel table_model = new DefaultTableModel( column_names, columnCount ); // create a table model based of the columns and column count
table=new JTable( table_model ); // create a new table with that model
String column_i = table.getModel().getColumnName(i);
Iterate through 'i'; as it represents the index of the column.
Cheers!
JScrollPane pane = new JScrollPane(table);
contentPane.add(table);
JscrollPane.add(table);
The above code is all confused:
First you create a scrollpane using the table (which is correct), but then you add the table to the content pane (which is incorrect). A table can only have a single parent so it gets removed from the scrollpane.
Then you try to add the table back to the scrollpane which won't work because you need to add the table to the viewport of the scrollpane, not the scrollpane directly.
So bottom line all you need is:
JScrollPane pane = new JScrollPane(table);
//contentPane.add(table);
//JscrollPane.add(table);
Edit:
First get the code working without the SQL. Use the above suggestion and then change your current code:
//table.setModel(DbUtils.resultSetToTableModel(rs));
table.setModel( new DefaultTableModel(5,5) );
This should display an empty table with 5 rows and 5 columns.
If you see the table then the problem is with your SQL, you are returning an empty ResultSet.
If you don't see the table then you have a problems somewhere else in your code.
I am selecting records from the database and its showing some empty records in the JTable Along with the records I am not been able to filter records with table .
Here are some empty records which is in the image
public ArrayList<User> getUsers(){
ArrayList<User> usersList=new ArrayList<User>();
Connection connection=getConnection();
String query="SELECT * FROM info";
Statement myState;
ResultSet rs;
try{
myState=connection.createStatement();
rs=myState.executeQuery(query);
User user;
while(rs.next()){
user=new User(rs.getInt("id"),rs.getString("fname"),rs.getString("lname"),rs.getInt("age"));
usersList.add(user);
}
}
catch(Exception ep){
ep.printStackTrace();
}
return usersList;
}
I am populating these records in JTable with this function which is given below.
public void ShowUsersinJTable(){
ArrayList<User> uList=getUsers();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
Object[] row=new Object[4];
for(int i=0;i<uList.size();i++){
row[0]=uList.get(i).getId();
row[1]=uList.get(i).getFname();
row[2]=uList.get(i).getLname();
row[3]=uList.get(i).Age();
model.addRow(row);
}
}
as the code seems about right try changing your code to this:
ArrayList<User> uList=getUsers();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
for(int i=0;i<uList.size();i++){
Object[] row=new Object[4];
row[0]=uList.get(i).getId();
row[1]=uList.get(i).getFname();
row[2]=uList.get(i).getLname();
row[3]=uList.get(i).Age();
model.addRow(row);
}
also you can delete all rows before filling the table (only needed if table was filled with data)
for (int i = table.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}
please tell me if it has worked, so i can help you further if needed
The default number of rows of the jTable in netbeans is four. So you can remove this by going to jTable properties -> model -> Rows.
Or, you can set rowCount to be zero before adding rows in the table like this:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
I have developed below code,
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/online_store","username","password");
if(con != null){
String query = "SELECT * FROM expense";
rs = stmt.executeQuery(query);
ResultSetMetaData rsmt = rs.getMetaData();
int c = rsmt.getColumnCount();
Vector column = new Vector(c);
for(int i = 1; i <= c; i++) { column.add(rsmt.getColumnName(i)); }
Vector data = new Vector(); Vector row = new Vector();
while(rs.next())
{
row = new Vector(c);
for(int i = 1; i <= c; i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
expense_table.add(data);
// expense_table.getColumnName(null);
JOptionPane.showMessageDialog(null, "get details from database");
}
}catch(SQLException ex){
System.out.println(ex);
}
My existing table's name is expense_table. I need to display all the records from database in this table without change its structure/without creating new table.Everything is ok except showing data(rows) vector in table which is " expense_table.add(data);" line. Please tell me is there any method to to this.
I need to display all the records from database in this table without change its structure/without creating new table.
So then you don't need to access the column names from the ResultSet. You just need to add new rows of data to the JTable. So get rid of the logic that creates the "column" Vector.
//expense_table.add(data);
You can't add a Vector to a JTable. There is no method that allows you to do this so get rid of that statement.
Instead you need to add the data to the DefaultTableModel one row at a time:
//data.add(row);
DefaultTableModel model = (DefaultTableModel)expense_table.getModel();
model.addRow( row );
I have the following code for a jtable. it gets data from a database and populates the table.
Code to get info from db:
Vector<Vector<String>> InvoiceDetails = new Vector<Vector<String>>();
Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from CustomerDetails");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> InvoiceDetail = new Vector<String>();
InvoiceDetail.add(rs.getString(1)); //Empid
InvoiceDetail.add(rs.getString(2)); //name
InvoiceDetail.add(rs.getString(3)); //position
InvoiceDetail.add(rs.getString(4));
//need to add code for button here
InvoiceDetails.add(InvoiceDetail);
}
jtable code:
public TableExample() throws Exception {
GetEmployeeDetails dbengine = new GetEmployeeDetails();
data = dbengine.getEmployee();
header = new Vector<String>();
header.add("invoicedata1");
header.add("invoicedata2");
header.add("invoicedata3");
header.add("invoicedata4");
//need to add button here
initComponents();
}
this is working fine as per now. Now I need to add another column which has buttons which I can click to view some specific data of that column. How can I do this?
Mind that I am new to java. Thanks in advance.
First of all variable names should NOT start with an upper case character. "InvoiceDetail" should be "invoiceDetail". Most of your names are correct. Be consistent!!!
You can use the Table Button Column.
You simply add a String to your "header" to represent the column name and then add a String to the "invoiceDetails" to represent the text of the button in the column.
The TableButtonColumn will provide the renderer and editor for you.
I have to make a 'query' method for my class which accesses MySQL thru' JDBC.
The input parameter to the method is a full SQL command (with values included), so I don't know the names of columns to fetch out.
Some of the columns are strings, some others are integers, etc.
The method needs to return the value of type ArrayList<HashMap<String,Object>>
where each HashMap is 1 row, and the ArrayList contains all rows of result.
I'm thinking of using ResultSet.getMetaData().getColumnCount() to get the number of columns then fetch cell by cell out of the current row, but is this the only solution? any better ones?
I have the example code here, just in case anybody need it. ('Con' in the code is the standard JDBC connection).
//query a full sql command
public static ArrayList<HashMap<String,Object>>
rawQuery(String fullCommand) {
try {
//create statement
Statement stm = null;
stm = con.createStatement();
//query
ResultSet result = null;
boolean returningRows = stm.execute(fullCommand);
if (returningRows)
result = stm.getResultSet();
else
return new ArrayList<HashMap<String,Object>>();
//get metadata
ResultSetMetaData meta = null;
meta = result.getMetaData();
//get column names
int colCount = meta.getColumnCount();
ArrayList<String> cols = new ArrayList<String>();
for (int index=1; index<=Col_Count; index++)
cols.add(meta.getColumnName(index));
//fetch out rows
ArrayList<HashMap<String,Object>> rows =
new ArrayList<HashMap<String,Object>>();
while (result.next()) {
HashMap<String,Object> row = new HashMap<String,Object>();
for (String colName:cols) {
Object val = Result.getObject(colName);
row.put(colName,val);
}
rows.add(row);
}
//close statement
stm.close();
//pass back rows
return tows;
}
catch (Exception ex) {
System.out.print(ex.getMessage());
return new ArrayList<HashMap<String,Object>>();
}
}//raw_query