When using Java development database application systems, you often need to display query results on the user interface. Since Sun's JDK1.x Development Kit is not a visualized integrated development environment (IDE), it is not easy to easily display the query results in a table in DBGRID. Therefore, you can only rely on your own code.
In practical applications, we can use three classes such as Vector, JTable, AbstractTableModel to better solve this problem. Here, in detail, implement the method.
I. Class Vector, class JTABLE and class AbstractTableModel profile:
1, class vector:
Class Vector is a historical set class of Java, belonging to a java.util package. It has been packaged with heterogeneous layers and array hybrids, with the following two features:
* Vector is heterogeneous, not required to have the same type of each element, and a variety of object types can be mixed in the vector;
* The vector is an array of hybrids because they can increase during increasing elements.
Its isomer is in line with the characteristics of different types of properties in database records, and its dynamics also matches database queries, and the result set records a number of species.
The class vector is defined as follows:
Public Class Vector Extends AbstractList
Implements List, Cloneable, Serializable {...}
Realize the search, new, deletion, etc. of the vector member. Such as: add (object obj) can easily add an object; Get (int index) can easily get an object in the vector; Remove (Object Obj) can easily delete an object in the vector.
2, class jtable:
The JTable component is a complicated small piece in the Swing component, which is part of the javax.swing package, which can display data in the form of a two-dimensional table. Class JTABLE is defined as follows:
Public Class JTable Extends JComponent
Implements Tablemodellistener, Scrollable, TableColumnModelliStener,
ListSelectionListener, CelleditorListener, Accessible {...}
Class JTABLE has the following features when displaying data:
* Contribute: You can customize the display mode and editing status of data;
* Isomeric: Different types of data objects can be displayed, even complex objects such as color, icons;
* Simple: You can easily establish a two-dimensional table with a default.
Its customizable can meet the requirements of different users and occasions, and isomerism is also characterized by the characteristics of the attribute types of database access results. Class JTABLE provides an extremely rich two-dimensional table operation method, such as setting an editing state, display mode, selecting row column, etc., will not be described here.
Before using class JTable display data, custom models, unit drawers, or unit editing must be generated depending on the situation. Class ABSTRACTLISTMODEL is used to customize user's own data model, which is later described later. The TableCellRenderer interface is used to customize the unit drawer, the TableCelleditor interface is used to customize the unit editor, which is mainly used for the processing of color objects, and is not used in the example, not excessive description.
3, class AbstractTableModel:
Class AbstractTableModel is an abstract class, not fully implemented, can not be instantiated, and must be implemented in the program during use. It is part of javax.swing.table. The class is defined as follows:
Public Abstract Class AbstractTableModel Extends Objectimplements Tablemodel, Serializable {...}
Class ABSTRACTTABLEMODEL provides the default implementation of most methods in the TableModel interface. The TableModel interface defines the basic data structure of the JTABLE. Users must generate their own data models, which can be met by implementing all the methods in the TableModel interface, but the function of the management listener is common for all data models, so the class AbstractTableModel is defined in javax.swing.table. This work. It manages the audience table and provides a convenience of generating TableModeEvents incidents and entrusting the audience.
To generate a specific TableModel as a subclass of AbstractTableMode, at least three methods must be implemented:
Public int getRowcount ();
Public int getColumncount ();
Public Object GetValueat (int Row, int column);
At this point, we can establish a simple two-dimensional table (5 × 5), the implementation method is as follows:
TableModel Datamodel = new AbstractTableModel () {
Public int getColumncount () {Return 5;}
Public int getRowcount () {return 5;
Public Object getValueat (int Row, int co) {return new integer (row * col);}
}
JTable Table = New JTABLE (DATAMODEL);
JscrollPane scrollpane = new jscrollpane (table);
Second, the database and its connection method introduction:
The example uses the Sybase database system, and the data inventory is placed in the database server. The path is: d: / worker, the database name is: worker.dbf. Has the following fields:
Field name
Types of
WNO (employee)
VARCHAR
WNAME (employee name)
VARCHAR
SEX (gender)
VARCHAR
BIRTHDAY (date of birth)
Date
Wage
Float
To connect this database, you need to use the class DriverManager in the java.sql package. This class is a utility class for managing JDBC drivers. It provides methods such as connecting, registration, undo driver, setting registration, and database access login email. The specific connection method is as follows:
Step 1: Position, load, and link Sybdriver class;
Driver = "com.sybase.jdbc.sybdriver";
Sybdriver sybdriver = (sybdriver) Class.Forname (driver) .newinstance ();
Step 2: Register the SybDriver class;
Drivermanager.RegisterDriver (Sybdriver);
Step 3: A SybConnection object is obtained.
User = "sa";
PASSWORD = ""
URL = "JDBC: Sybase: TDS: 202.117.203.114: 5000 / Worker"; SybConnection Connection = (SybConnection) DriverManager.getConnection
(URL, User, Password);
After establishing the connection, you can perform the database query and change via the Statement interface.
Third, implementation method:
Limited to the space, only the core code, the introduction, interface processing, and variable definitions, etc. are given here.
Step 1: Object declaration.
AbstractTableModelTm; // Declare a class AbstractTableModel object
JTable jg_table; // Declare a class JTable object
Vector vect; // Declare a vector object
JScrollPane JSP; // Declare a rolling bar object
String title [] = {"Workers", "employee name", "gender", "date of birth", "salary"}
// Two-dimensional table name
Step 2: Custom form.
1. Implement the method in the abstract class AbstractTableModel object TM:
Vect = new vector (); // instantiate vector
TM = New AbstractTableModel () {
Public int getColumncount () {
Return Title.Length;} // Number of tables
Public int getRowcount () {
Return vect.size ();} // Number of lines
Public Object GetValueat (int Row, int column) {
IF (! vect.isempty ())
Return
(Vector) Vect.Elementat (ROW). Elementat (Column);
Else
Return NULL;} // Get attribute values in the cell
Public String getColumnName (int column) {
Return Title [Column];} // Set the table name
Public void setValueat (Object Value, Int Column) {}
// Data model is not editable, this method is set to empty
Public Class getColumnClass (int C) {
Return getValueat (0, c) .getClass ();
} // Get column belongings
Public Boolean IscelleDitable (int Row, Int Column) {
Return False;} // Setting the cell is not editable, for the default implementation
}
2, custom form:
JG_TABLE = New JTABLE (TM); // Generate your own data model
JG_Table.SetTooltiptext ("Show All Query Results"); // Setting Help Tips
JG_Table.SetAutoSizeMode (jtable.auto_resize_off);
/ / Set the table to adjust the size mode
Jg_table.setcellselectionenableNabled (false); // Set cell selection mode
JG_Table.SetShowVerticalLines (TRUE); // Set whether to display the divided line between cells
JG_Table.SetShowhorizontallines (TRUE);
JSP = new jscrollpane (jg_table); // Plus a rolling strobe for the table
Step 3: Show the results of the query.
1. Connect the database: The second part has been given.
2, database query:
St.createStatement (); ResultSet RS = Stmt.executeQuery ("SELECT * from worker");
3, display the query results:
Vect.removeAllelements (); // Initialization vector object
TM.FireTablestructureChanged (); // Update Table Content
While (rs.next ()) {
Vector rec_vector = new vector ();
/ / From the result set of data placed in vector REC_Vector
REC_VECTOR.Addelement (rs.getstring (1));
REC_VECTOR.Addelement (rs.getstring (2));
REC_VECTOR.Addelement (Rs.getstring (3));
REC_VECTOR.Addelement (Rs.Getdate (4));
Rec_vector.addelement (new float (rs.getfloat (5));
Vect.addelement (REC_VECTOR); // Vector REC_Vector Add to Vector Vect
}
TM.FireTablestructureChanged (); // Update the table, display vector vect
The example is as follows:
To implement the effect of the preceding, the following effect is recorded, there are two ways:
First, if the software environment supports JDBC 2.0, you can use rsprevoius () and rs.next () to get records, and then display individual field values via the setText Field in class JTextField.
Second, if JDBC2.0 is not supported, you can use the vector vector to remove the data in JTABLE. Customize a pointer to record the location. When the pointer is added 1, take out the previous row data into the vector display; the pointer is reduced by 1, remove the next row data display. The display method is the same.
It should be noted that the code is not given in the code, such as SQLException, must be given in the actual application. In addition, in some systems, the Chinese characters in the text domain do not necessarily display properly and need to be implemented with other methods.