Swing's popular jtable class provides a simple mechanism for displaying large data blocks. Jtable has many features for data generation and editing, many of which can be customized to further enhance its functions. This article will guide you step by step into the jtable world.
ListingContains a simple sample code, which describes common jtable behaviors. You can change the layout of a jtable, drag and drop its columns, or drag the separator of the title to change its size.
These columns are saved in a string array:
String [] columnnames = {"product", "number of boxes", "price "};
The data is initialized and saved in a two-dimensional array of objects:
Object [] [] DATA =
{
{"Apples", new INTEGER (5), "5.00 "},
{"Oranges", new INTEGER (3), "6.00 "},
{& Quot; pears & quot;, new INTEGER (2), & quot; 4.00 & quot "},
{& Quot; grapes & quot;, new INTEGER (3), & quot; 2.00 & quot "},
};
Jtable is usedDataAndColumnnamesComposed:
Jtable table = new jtable (data, columnnames );
View jtable
The jtable height and width are set as follows:
Table. setpreferredscrollableviewportsize (new dimension (300, 80 ));
If the size of a column or jtable window in jtable is re-determined, other columns are scaled down or enlarged to adapt to the new window. You can use setautoresizemode () to control this behavior:
Table. setautoresizemode (INT mode );
ModePossible values of integer fields include:
Auto_resize_off
Auto_resize_next_column
Auto_resize_subsequent_columns
Auto_resize_last_column
Auto_resize_all_columns
Table Default Value
The default color of the square coordinate line in a cell isColor. Gray. To change the color of these square coordinate lines, you need to use:
Table. setgridcolor (color. Black );
You can use the following method to change the Row Height:
Table. setrowheight (intpixelheight );
The height of each cell is equal to the Row Height minus the distance between rows.
By default, the foreground color and background color of the content are determined by swing's WYSIWYG implementation. You can use the following method to change the selected color:
Table. setselectionbackground (color. Black); table. setselectionforeground (color. White );
You can also hide the cell's square coordinate line, as shown below:
Table. setshowhorizontallines (false );
Table. setshowverticallines (false );
FigureAA jtable with its horizontal coordinate line hidden is displayed.
Figure
Column width
The jtable component has several classes and interfaces that control table features. Tablecolumn keeps track of the column width and adjusts the column size, including the maximum and minimum widths.
Tablecolumnmodel manages the tablecolumns set and column selection. To set the width of a column, you must set a reference for the table column model. Then, get the expected tablecolumn and call its setpreferredwidth () method:
Tablecolumncolumn = table. getcolumnmodel (). getcolumn (0 );
Column. setpreferredwidth (100 );
When you drag and drop a column, the column index does not change. The getcolumn (0) method always returns the correct column, no matter where it appears on the screen.
Title
Jtableheader displays the jtable title. You can subdivide jtableheader to get a custom layout. For example, if your application requires a title that spans multiple columns, simply segment the jtableheader and integrate it into your jtable.
You can set a reference for the jtableheader of the current jtable or call its setreorderingallowed () method to specify whether re-sorting of titles is allowed:
Table. gettableheader (). setreorderingallowed (false );
Similarly, you can make sure that the column size does not change as it is dragged between the column headers. To achieve this, you need to use the setresizingallowed () method:
Table. gettableheader (). setresizingallowed (false );
Select Mode
By default, When you select a cell in the jtable, the entire row is selected. There are multiple ways to allow users to customize their selection methods. Using the listselectionmodel interface, you can select one or more rows:
Table. setselectionmode (listselectionmodel. single_selection );
Listselectionmodel has the following fields:
- Single_selection allows you to select a row at a time.
- Single_interval_selection allows you to select a series of adjacent rows.
- Multiple_interval_selection also allows you to select adjacent columns, but with the extension function. It allows you to use the [CTRL] key to select multiple adjacent rows ).
The setcellselectionenabled () method allows you to select a single cell or the entire row simultaneously:
Table. setcellselectionenabled (true );
If it is set to yes, the setcellselectionenabled () method also allows you to select columns while selecting rows and individual cells. IfFigureB.
Figure B
Edit Cells
This simple table allows users to edit any cells in the table.Listing BLists a table that allows programmers to determine which cells can be edited. The first step is to create a custom tablemodel:
Class simpletablemodel extends acttablemodel {}
Data is encapsulated in tablemodel. When jtable is initialized, the custom tablemodel is passed as a parameter to the jtable constructor instead of the two-dimensional object array:
Simpletablemodelmymodel = new simpletablemodel ();
Jtable table = new jtable (mymodel );
If you want to edit the second and third columns and change the first column to a constant value, you must forcibly replace the iscelleditable () method of tablemodel:
Public booleaniscelleditable (INT row, intcol ){
If (COL = 0) {return false ;}
Else {return true ;}
}
Simple Table Verification
Make sure that you only enter an integer. If you enter a value in the second column ("number of boxes"), the setvalueat () method is mandatory, the verification logic is included in this new method. First, check whether the column is an integer and whether the column should only contain an integer:
If (data [0] [col] instanceof integer &&! (Value instanceof integer ))
{... } Else {data [row] [col] = value ;}
Then, check whether the inserted value is an integer. If it is not, this field should not be updated and an error message should be displayed:
Try {
Data [row] [col] = new INTEGER (value. tostring ());
} Catch (numberformatexception e ){
Joptionpane. showmessagedialog (simpletable. This,
"Please enter only integer values .");
}
Background Color
Listing cContains the code for colortable. Java, which explains how to add colors to jtable. You can add the background color to the jtable by forcibly replacing its preparerenderer () method:
Jtable table = new jtable (data, columnnames ){
Public component preparerenderer (tablecellrenderer R, int row, intcol ){}
};
Then, insert the logic that determines which columns should have colors and what colors should be:
If (COL = 2 &&! Iscellselected (row, col )){
Color BG = new color (200,100, 30 );
C. setbackground (BG );
C. setforeground (color. White );
}
Note that when you change the background color of a cell, you should also change the color of the text displayed in the cell to make it easier to read.FigureCDisplays a jtable with the color added to the first and second columns.
Figure C
Everything is under control
Our example is just the basis of other parts of jtable. By using these tools, you can quickly and easily control the formatting of tables generated by Java applications, so that your users will not encounter any obstacles during normal use.
Certificate ----------------------------------------------------------------------------------------------------------------------------------
Import java. AWT. dimension;
Import javax. Swing. jframe;
Import javax. Swing. jscrollpane;
Import javax. Swing. jpanel;
Import javax. Swing. jtable;
Import java. AWT. color;
Import java. AWT. gridlayout;
Import javax. Swing. Table. tablecolumn;
Public class jtabledemo
{
Public static void main (string [] ARGs)
{
/*
There are many constructor types described below:
Jtable ()
Jtable (INT numrows, int numcolumns)
Jtable (object [] [] rowdata, object [] columnnames)
*/
Jtable example1 = new jtable (); // not visible but exists
Jtable example2 = new jtable (8, 6 );
Final object [] columnnames = {"name", "gender", "Home Address", // it is best to use final for column name Modification
"Phone Number", "Birthday", "work", "income", "Marital status", "Love status "};
Object [] [] rowdata = {
{"DDD", "male", "Nanjing, Jiangsu", "1378313210", "03/24/1985", "student", "Parasitic", "Unmarried", "no "},
{"Eee", "female", "Nanjing, Jiangsu Province", "13645181705", "XX/1985", "tutor", "unknown", "Unmarried ", "It seems no "},
{"Fff", "male", "Nanjing, Jiangsu", "13585331486", "12/08/1985", "Car Salesman", "uncertain", "Unmarried", "yes "},
{"Ggg", "female", "Nanjing, Jiangsu Province", "81513779", "XX/1986", "Hotel attendant", "OK but unknown ", "Unmarried", "yes "},
{"Hhh", "male", "Nanjing, Jiangsu", "13651545936", "XX/1985", "student", "Exile", "Unmarried ", "Not after numerous breaking up "}
};
Jtable friends = new jtable (rowdata, columnnames );
Friends. setpreferredscrollableviewportsize (new dimension (600,100); // you can specify the table size.
Friends. setrowheight (30); // set the height of each row to 20
Friends. setrowheight (0, 20); // set the height of 1st rows to 15
Friends. setrowmargin (5); // you can specify the distance between two adjacent rows of cells.
Friends. setrowselectionallowed (true); // sets whether to be selected. The default value is false.
Friends. setselectionbackground (color. White); // you can specify the background color of the selected row.
Friends. setselectionforeground (color. Red); // you can specify the foreground color of the selected row.
Friends. setgridcolor (color. Black); // you can specify the gridline color.
Friends. selectall (); // select all rows
Friends. setrowselectioninterval (); // you can specify the initial row to be selected. All rows 1 to 3 are in the selected status.
Friends. clearselection (); // cancel the selection
Friends. setdragenabled (false); // do not understand this
Friends. setshowgrid (false); // whether to display grid lines
Friends. setshowhorizontallines (false); // whether to display horizontal gridlines
Friends. setshowverticallines (true); // whether to display vertical gridlines
Friends. setvalueat ("TT", 0, 0); // sets the value of a cell. This value is an object.
Friends. dolayout ();
Friends. setbackground (color. lightgray );
Jscrollpane pane1 = new jscrollpane (example1); // it is best to add jtable to jscrollpane.
Jscrollpane pane2 = new jscrollpane (example2 );
Jscrollpane pane3 = new jscrollpane (Friends );
Jpanel Panel = new jpanel (New gridlayout (0, 1 ));
Panel. setpreferredsize (new dimension (600,400 ));
Panel. setbackground (color. Black );
Panel. Add (pane1 );
Panel. Add (pane2 );
Panel. Add (pane3 );
Jframe frame = new jframe ("jtabledemo ");
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. setcontentpane (panel );
Frame. Pack ();
Frame. Show ();
}
}