954,170 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

JTable + MySQL

If in big problem, I want a to add the ResultSet of MySQL in JTable.Table should in Panel. and There should be autosizing of the result.

Ashwin Vasnai
Newbie Poster
16 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

So in which section of your code you are having problem?

peter_budo
Code tags enforcer
Moderator
15,433 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 901
 

This is a very common thing to want to do. You will have no problem finding example solutions on the web (if you look).

JamesCherrill
Posting Genius
Moderator
6,337 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,070
 

And where are you having problem? Don't expect to do this for you and if reply by saying that you want some guidelines then I will ask guidelines at which part of your problem:

1) Creating the database
2) Open Database Connection (JDBC Connectivity)
3) Write the query (SQL query Knoledge)
4) Get the data from the database by running the query through java (package java.sql.*)
5) Create the JForm, JPanel, JTable (package jacax.swing.*)
6) Putting the data into the JTable (package jacax.swing.*)

I suggest to put the above steps in different classes

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

well I want to have auto-resize the column according to largest string in the cell.
every time I have adjust the size manually.
How it is possible in Java.

Ashwin Vasnai
Newbie Poster
16 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

AFIK there's no automatic way. It's a very common requirement, and there are a number of good sample solutions on the web (basically you have to loop down the whole column to find the widest entry, then use that size to set the column width).
You may find this useful:

public void packColumns(JTable table) {
	DefaultTableColumnModel colModel = (DefaultTableColumnModel) table
			.getColumnModel();
	for (int cNumber = 0; cNumber < table.getColumnCount(); cNumber++) {
		TableColumn col = colModel.getColumn(cNumber);
		int width = 0;
		// Get width of column header
		TableCellRenderer renderer = col.getHeaderRenderer();
		if (renderer == null) {
			renderer = table.getTableHeader().getDefaultRenderer();
		}
		Component comp = renderer.getTableCellRendererComponent(table, col
				.getHeaderValue(), false, false, 0, 0);
		width = comp.getPreferredSize().width;
		// Get maximum width of column data
		for (int r = 0; r < table.getRowCount(); r++) {
			renderer = table.getCellRenderer(r, cNumber);
			comp = renderer.getTableCellRendererComponent(table, table
					.getValueAt(r, cNumber), false, false, r, cNumber);
			width = Math.max(width, comp.getPreferredSize().width);
		}
		col.setPreferredWidth(width + 2);  // Add margin
	}
}
JamesCherrill
Posting Genius
Moderator
6,337 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,070
 

@James
You would saved hell of typing if you just pointed to Swing Hacks - Size Your Columns to Suit Your JTable's Contents ;)

peter_budo
Code tags enforcer
Moderator
15,433 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 901
 

thanks it works.

Ashwin Vasnai
Newbie Poster
16 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 
@James You would saved hell of typing if you just pointed to Swing Hacks - Size Your Columns to Suit Your JTable's Contents ;)

Hi Peter. This is something I already had in my "useful fragments" collection - no typing needed! (Whenever I stumble across some interesting code I snag a copy and build it into my library of "useful" stuff. It's amazing how often I already have an answer there when a problem comes up.)

JamesCherrill
Posting Genius
Moderator
6,337 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,070
 

Interesting idea and maybe handy if you work in specific area. However it wouldn't be useful in my case as in the company we do everything from GUI, web, mobile with various frameworks or technologies. You can say everyday something new and also we may "never again enter the same river".

peter_budo
Code tags enforcer
Moderator
15,433 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 901
 
If in big problem, I want a to add the ResultSet of MySQL in JTable.Table should in Panel. and There should be autosizing of the result.
import java.sql.*;
import javax.swing.table.*;

/**
 * @author lanhlung696
 * Get data for table 
 */
class TableDataModel extends DefaultTableModel {
    public void setResultSet(ResultSet results) {
        try {
            ResultSetMetaData metadata = results.getMetaData();
            int columns =  metadata.getColumnCount();
            
            // Get the column names and set header names
            for(int i = 0; i < columns; i++) {
                addColumn(metadata.getColumnLabel(i+1));
            }
            
            // Get all rows
            while(results.next()) {
                String[] rowData = new String[columns];    // Create array to hold the data
                for(int i = 0; i < columns; i++) {         // For each column
                    rowData[ i ] = results.getString(i+1);   // retrieve the data item
                }
                addRow(rowData);    // Add a row
            }
            fireTableChanged(null);           // Signal the table there is new model data
        } catch (SQLException sqle) {
            System.err.println(sqle.getMessage());
        }
    }
}

This is code you want.

lanhlung696
Newbie Poster
3 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You