Two methods of jtable control binding SQL data source in visual swing deep parsing

Source: Internet
Author: User
Tags bind tostring
The following is a detailed analysis of the two methods for binding SQL data sources for JTable controls in visual swing, and the need for a friend to come over and refer to

In MyEclipse's visual Swing, there are JTable controls.
JTable is used to display and edit regular two-dimensional cell tables.
So how do you bind data in database SQL to jtable?
Here, two ways are available.
the construction method of JTable
by looking at the Java API, you can get two important constructs for JTable:
JTable (object[][] rowdata, object[] columnnames)
constructs a JTable to display the values in the two-dimensional array rowdata, whose column names are called ColumnNames.
JTable (TableModel DM)
constructs a JTable that initializes it using the data model DM, the default column model, and the default selection model.

Below, we will bind the jtable to the SQL database through these two constructs.

The necessary preparatory work
One, there is a database to bind to.
Second, drag a JTable control into the visual swing.

Method One: binding by two dimensional arrays
This method uses the following construction method:
JTable (object[][] rowdata, object[] columnnames)
constructs a JTable to display the values in the two-dimensional array rowdata, whose column names are called ColumnNames.
Constructing two-dimensional array RowData
We have been able to read the SQL database to resultset through the pre-compiling study of the previous blog post.
Comprehensive application analysis of pre-compiling in the PreparedStatement class of JDBC
reviewed as follows:

Copy Code code as follows:


/** Query and returns the Recordset/


public ResultSet getresultset (String sql, object[] objarr) {


getconnection ();


try {


pstatement = connection.preparestatement (sql, resultset.type_scroll_insensitive, resultset.concur_read_only);


if (objarr!=null && objarr.length>0) {


for (int i = 0; i < objarr.length; i++) {


Pstatement.setobject (i+1, objarr[i]);


    }


   }


RSet = Pstatement.executequery ();


//list = resultsettolist (RS);


} catch (SQLException e) {


E.printstacktrace ();


} finally {


//close ();


  }


return rSet;


 }


"Note" is only different from the previous blog's method name.
Now, to convert resultset into a two-dimensional array, write the following methods:

Copy Code code as follows:


/** Turn the result set into object[][] * * * *


public object[][] Resultsettoobjectarray (ResultSet rs) {


object[][] data = null;


try {


Rs.last ();


int rows = Rs.getrow ();


data = new object[rows][];


ResultSetMetaData MD = Rs.getmetadata ();//Get the metadata for the recordset


int columnCount = Md.getcolumncount ();//Number of columns


Rs.first ();


int k = 0;


while (Rs.next ()) {


System.out.println ("I" +k);


object[] row = new Object[columncount];


for (int i=0; i<columncount; i++) {


Row[i] = Rs.getobject (i+1). toString ();


    }


Data[k] = row;


k++;


   }


} catch (Exception e) {


  }


return data;


 } 


The two methods are saved to the file Userdao.java.
Instantiate Userdao first in the Java file where swing resides:

Copy Code code as follows:


Userdao Userdao = new Userdao ();


You can convert SQL data to a two-dimensional array:

Copy Code code as follows:


object[][] dataobjects = Userdao.resultsettoobjectarray (Userdao.getresultset (


"Select Id,username,password from T_userr", null));


Build Column Name ColumnNames
This is simple, just write the column name to a string array.

Copy Code code as follows:


string[] Tablestrings = {"id", "username", "password"};


Build the JTable Model:

Copy Code code as follows:


Jtable1.setmodel (New DefaultTableModel (DataObjects, tablestrings));


Overall Code view:
Overall Code view:
Final JTable effect chart:



Method Two: the construction method used by the model binding method is:

JTable (TableModel DM)
constructs a JTable that initializes it using the data model DM, the default column model, and the default selection model.

Set the model path

Enter the control panel of the JTable control and click Model.

Select model from code.

Fill in Model Method path: package name. Java filename. method name.

It is recommended that the method be set to a static method for easy invocation.

Write Model method

Writes the model method under the path just set, noting that its return type is TableModel.

The method of writing is similar to the above, no longer repeat.

Copy Code code as follows:


public static TableModel member () {


string[][] Playerinfo = new String[80][8];


Basedao Bdao = new Basedao ();


String sql = "Select id,realname,username,sex,phone,email,vocation,city from Jdbctest";


string[] ss = {};


arraylist<hashmap<object, object>> list = bdao.query (SQL, SS);


//Bdao.allarray (list);


int i = 0, j = 0;


for (Hashmap<object, object> maps:list) {


set<object> keysobjects = Maps.keyset ();


for (Object kobject:keysobjects) {


Playerinfo[i][j] = Maps.get (kobject). toString ();


J + +;


   }


i++;


j = 0;


  }


string[] Names = {"id", "username", "sex", "phone", "vocation", "email", "realname", "City"};


DefaultTableModel Dmodel = new DefaultTableModel (Playerinfo, Names);


Return (TableModel) Dmodel;


 }


JTable Effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.