Use the swing jtable class to make the data look clean.

Source: Internet
Author: User

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.

Listing A contains 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.

This
Some columns are saved in a string array: String [] columnnames = {"product", "Number
Boxes "," price "}; 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 "},
{"Pears", new INTEGER (2), "4.00" },{ "Grapes", new
INTEGER (3), "2.00" },}; jtable is composed of data and columnnames: jtable table = new
Jtable (data, columnnames );
View jtable
Set the jtable height and width as follows:
Set: Table. setpreferredscrollableviewportsize (new dimension (300,
80); if the size of a column or jtable window is re-determined, other columns are scaled down or enlarged to adapt to the new window. Use
The setautoresizemode () method can control this behavior: Table. setautoresizemode (int
Mode); possible value of the mode integer field
Available: bytes

Table Default Value

Single
The default color of the square coordinate line in the grid is color. Gray. To change the color of these square coordinate lines, use
To: Table. setgridcolor (color. Black); you can use the following method to change the Row Height.
Degree: Table. setrowheight (intpixelheight); the height of each cell is equal to the height of the row minus the distance between rows. By default, the foreground of the content
The choice of color and background color is determined by swing's WYSIWYG implementation. You can use the following method to change the selected face
Color: Table. setselectionbackground (color. Black );
Table. setselectionforeground (color. White); you can also hide the cell's square coordinate line, as shown below:
Example: Table. setshowhorizontallines (false); table. setshowverticallines (false );
Figure A shows a jtable that hides its horizontal coordinate line.

Figure

Column width
The jtable component has several table-controlled features.
Class and interface. Tablecolumn keeps track of the column width and adjusts the column size, including the maximum and minimum widths. Tablecolumnmodel manages
Tablecolumns set and column selection. To set the width of a column, you must set a reference for the table column model. Then, obtain 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
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 the title is reordered
Xu: Table. gettableheader (). setreorderingallowed (false); similarly, you can be sure that the column is not in the column title
Drag between them to change the size. To achieve this, you need to use 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
You can select one or more
Row: Table. setselectionmode (listselectionmodel. single_selection); listselectionmodel
The following fields are available:
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 users to use the [CTRL] key to select multiple adjacent
(That is, select non-adjacent rows ).
The setcellselectionenabled () method allows you to select a single cell or the entire
Row: Table. setcellselectionenabled (true); if it is set to yes, setcellselectionenabled ()
You can also select columns when selecting rows and individual cells, as shown in Figure B.

Figure B

Edit Cells

Here we are
A simple table allows you to edit any cells in the table. Listing
B lists 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
Is 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 tablemodel
Iscelleditable () method: Public booleaniscelleditable (INT row, intcol) {if
(COL = 0) {return false;} else {return true ;}}
Simple Table Verification
You
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
C contains the code for colortable. Java, which explains how to add colors to jtable. You can forcibly replace its preparerenderer () method
To add the background color to jtable: 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
The color of the text displayed in the cell makes it easier to read. Figure C shows a jtable with colors 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.

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.