A detailed introduction to JTable

Source: Internet
Author: User
Tags pack

Turn from: http://www.cnblogs.com/mailingfeng/archive/2011/12/28/2304289.html


8-1: Using the JTable Component: Class hierarchy diagram:
Java.lang.Object
--java.awt.component
--java.awt.container
--javax.swing.jcomponent
--javax.swing.jtabel
Before using JTable, let's take a look at what its constructors are and how it should be used:
Jtabel constructor:
JTable (): Create a new jtables and use the system default model.
JTable (int numrows,int numcolumns): Creates an empty table with numrows rows, numcolumns columns, and uses DefaultTableModel.
JTable (object[][] rowdata,object[][] columnnames): Creates a table that displays two-dimensional array data, and can display the name of the column.
JTable (TableModel DM): Create a JTable, with default field mode and selection mode, and set data mode.
JTable (TableModel Dm,tablecolumnmodel cm): Establishes a JTable, sets the data mode and field mode, and has the default selection mode.
JTable (TableModel dm,tablecolumnmodel cm,listselectionmodel SM): Establish a JTable, set data mode, field mode, and selection mode.
JTable (Vector rowdata,vector columnnames): Create a data table with vector as the input source to display the name of the row.
Let's start with array construction to show you how to use JTable to build a simple table:
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;

public class simpletable{
Public simpletable () {
JFrame f= new JFrame ();
Object[][] playerinfo={
{"Ah-hang", new Integer (), new Integer (), new Integer (), new Boolean (FALSE)},
{"Ah,", new Integer (), new Integer (), new Integer (128), new Boolean (True)},
};
String[] names={"name", "Chinese", "mathematics", "Total score", "Pass"};
JTable table= New JTable (playerinfo,names);
Table.setpreferredscrollableviewportsize (New Dimension (550,30));
JScrollPane scrollpane= new JScrollPane (table);
F.getcontentpane (). Add (Scrollpane,borderlayout.center);
F.settitle ("Simple Table");
F.pack ();
F.show ();

F.addwindowlistener (New Windowadapter () {
public void windowclosing (WindowEvent e) {
System.exit (0);
}
});
}
public static void Main (string[] args) {
Simpletable b= new simpletable ();
}
}

The table consists of two parts: row headings (column headers) and Row objects (Column object). Use the Gettableheader () method provided by JTable to get the row headers. In this example, we put the jtable in the JScrollPane, which shows the column header and Colmn object in full, because JScrollPane automatically gets the column Header. But if the reader of the literary world removes and modifies line 16th on line 15th above:
F.getcontentpane (). Add (Table,borderlayout.center); Then you will find that the column header is missing.
If you do not want to use JScrollPane, to solve this problem, you must modify the program as follows:
JTable table=new JTable (p,n);
Table.setpreferredscrollableviewportsize (New Dimension (550,30));
F.getcontentpane (). Add (Table.gettableheader (), Borderlayout.north);
F.getcontentpane (). Add (Table,borderlayout.center);
The result will be the same as the previous row header. The results of the operation will follow that the width of each field is the same unless you drag a column wide. If we want to set the value of the column width in the first place, you can set it by using the Setpreferredwidth () method provided by the TableColumn class, and you can use the Setautoresizemode () provided by the JTable class. method to set the change in the width of other columns while resizing a column, let's look at the following example:
Import javax.swing.*;
Import javax.swing.table.*;
Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;
public class simpletable2{
Public SimpleTable2 () {
JFrame f= new JFrame ();
Object[][] p={
{"Ah-hang", new Integer (), new Integer, new integer (=), new Boolean (False), new Boolean (FALSE)},
{"Ah-hang", new Integer (), new Integer (128), new Boolean (True), new Boolean (FALSE)},
};
String[] n={"name", "Chinese", "mathematics", "Total score", "Pass", "cheat"};
TableColumn column= null;
JTable table= New JTable (p,n);
Table.setpreferredscrollableviewportsize (New Dimension (550,30));
Table.setautoresizemode (Jtable.auto_resize_subsequent_columns);
Using the Getcolumnmodel () method in JTable to obtain the Tablecolumnmodel object, and then using the GetColumn () method defined by the Tablecolumnmodel interface to fetch the TableColumn object, You can control the width of a field by using the Setpreferredwidth () method of this object.
for (int i=0;i<6;i++) {
Column=table.getcolumnmodel (). GetColumn (i);
if ((i%2) ==0) column.setpreferredwidth (150);
else Column.setpreferredwidth (50);
}
JScrollPane scrollpane= new JScrollPane (table);
F.getcontentpane (). Add (Scrollpane,borderlayout.center);
F.settitle ("Simple Table");
F.pack ();
F.show ();
F.setvisible (TRUE);
F.addwindowlistener (New Windowadapter () {
public void windowclosing (WindowEvent e) {
System.exit (0);
}
});
}
public static void Main (string[] args) {
New SimpleTable2 ();
}
}

The


column can be adjusted with 5 parameters:
Auto_resize_subsequent_columens: When a column is resized, all characters Krekun after this field are changed along with each other. This is the system default value.
Auto_resize_all_columns: When a column is resized, the column widths of all the fields on this table are changed along with each other.
Auto_resize_off: When a column is resized, all characters on this table Krekun are not changed.
Auto_resize_next_column: When you resize a column, the column width of the next field in this field changes, and the rest does not change.
Auto_resize_last_column: When you resize a column, the width of the last field changes, and the rest does not change.
from the example above, using swing to construct a table is very simple, as long as you use a vector or array to form the data input of our table, the vector or array content into the JTable, a basic table is produced. However, while using JTable (object[][] rowdata,object[][] columnnames) and jtable (Vector rowdata,vector columnnames) It is convenient to construct jtable structure function, but it has some disadvantages. For example, in the example above, each field (cell) in our table is initially modifiable, the user may modify to our data, and secondly, the data type in each cell in the table will be considered the same. In our example, the data type is displayed as a string type, so data declared as Boolean by the original data type appears as a string instead of the check box. In addition, if we want to display the data is not fixed, or changes, such as a transcript, teachers and students see the table will not be the same, the display of the appearance or mode of operation may also be different. In order to deal with these complex situations, the above simple construction method is not suitable for use, Swing provides a variety of model (such as: TableModel, Tablecolumnmodel and ListSelectionModel) to solve the above inconvenience, To increase the flexibility of our design forms. Let's start with TableModel:
8-2:tablemodel

The

TableModel class itself is a interface, in which a number of methods are defined: Basic access that includes accessing the contents of the table field (cell), calculating the number of columns in the table, and so on. Let the designer simply use TableModel to implement the form he wants. The TableModel interface is in javax.swing.table package, which defines many of the model jtable will use, and the reader can find this package using Java API files, And this package to find the methods defined by various types or interfaces.
TableModel method:
void Addtablemodellistener (Tablemodellistener L): makes a table capable of handling tablemodelevent. When the table model changes, the TableModel event events information is emitted.
Class getColumnClass (int columnindex): Returns the class name of the field data type.
int getColumnCount (): Returns the number of fields (rows).
String getcolumnname (int columnindex): Returns the field name.
int GetRowCount (): Returns the number of data columns.
Object getvalueat (int rowindex,int columnindex): Returns the value in a cell of the data.
Boolean iscelleditable (int rowindex,int columnindex): Returns whether the cell is editable, or true, if it is editable.
void Removetablemodellistener (Tablemodellistener l): Removes a listener from the Tablemodellistener.
void setValueAt (Object avalue,int rowindex,int columnindex): Sets the value of a cell (rowindex,columnindex);

Since TableModel itself is a interface, it is not easy to implement this interface directly to create a table. Fortunately, Java provides two classes to implement this interface, one is the Abstracttablemodel abstract class, One is the DefaultTableModel entity class. The former implements most of the TableModel methods, allowing users to construct their own table patterns flexibly; the latter inherits the former class and is the Java default table pattern. The relationship between the three is as follows:
TableModel---Implements--->abstracttablemodel-----extends--->defaulttablemodel 8-3:abstracttablemodel:

The Java-provided Abstracttablemodel is an abstract class that helps us achieve most of the TableModel methods except GetRowCount (), getColumnCount (), getValueAt () These three methods. So our main task is to implement these three methods. Using this abstract class, you can design tables in different formats. Let's look at the methods it offers.
Abstracttablemodel Method:
void Addtablemodellistener (Tablemodellistener L): Enables a table to have the ability to handle tablemodelevent. When the table model changes, The TableModelEvent event information is emitted. int Findcolumn (String columnName): Look for the item in the row name that contains ColumnName. If so, return the position of the row it is in, or return-1 to indicate that it was not found.
void firetablecellupdated (int row, int column): Notifies all listener that the contents of the (Row,column) field in this table have changed.
void firetablechanged (TableModelEvent e): Sends the event notifications received to all the tablemodellisteners registered in this table model.
void Firetabledatachanged (): Notifies all listener that the contents of the column in this table have changed. The number of columns may have changed, so jtable may need to display the structure of the table again.
void firetablerowsdeleted (int firstrow, int lastrow): Notifies all listener in this table FirstRow row to lastrow column has been deleted.
void firetablerowsupdated (int firstrow, int lastrow): Notifies all listener in this table FirstRow row to lastrow column has been modified.
void firetablerowsinserted (int firstrow, int lastrow): Notifies all listener in this form firstrow row to lastrow column has been added.
void Firetablestructurechanged (): Notifies all listener that the structure of the table has changed. The number of rows, names, and data types may have changed.
Class getColumnClass (int columnindex): Returns the class name of the field data type.
String getcolumnname (int column): Returns the default value if no column headings are set, followed by A,b,c,... Z,aa,ab,..; If this column is not available, an empty string is returned.
Public eventlistener[] Getlisteners (Class listenertype): Returns all listenertype in accordance with listener in the listener created by this table model, and returns as an array.
Boolean iscelleditable (int rowIndex, int columnindex): Returns all Listenertype in accordance with the listener form of the listener established in this table model, and returns as an array.
void Removetablemodellistener (Tablemodellistener l): Removes a listener from the Tablemodellistener.
void setValueAt (Object avalue, int rowIndex, int columnindex): Sets the value of a cell (Rowindex,columnindex).
If you carefully compare the method defined by TableModel with the method provided above Abstracttablemodel, you can find that Abstracttablemodel abstract class does not implement GetRowCount (), getColumnCount (), getValueAt () These three methods, which is why we are going to implement these three methods. Let's look at how to use Abstracttablemodel to actually make the table pattern that you want.
Example: Tablemodel1.java
View Code


Cheating is displayed in check box, with the data type displayed to the right, and the string type to the left.
Tablemodel2.java import javax.swing.table.abstracttablemodel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public  class tablemodel2  implements actionlistener{
jtable t =  Null

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.