Data
Swing's popular JTable class provides a simple mechanism for displaying large chunks of data. JTable has many things that are used for data generation and editing, many of which can be customized to further enhance its functionality. This article will guide you step-by-Step into the JTable world.
Listing A contains a simple example of code that illustrates the behavior of commonly used jtable. The user can change the layout of the JTable, drag and drop its columns, or change its size by dragging the caption's divider line.
These columns are saved in a String array: string[] ColumnNames = {"Product", "Number of Boxes", "Price"}; Data is initialized and stored in a two-dimensional object array: 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
The height and width of the jtable are set according to the following method: Table.setpreferredscrollableviewportsize (New Dimension (300, 80)); If the size of a jtable column or JTable window is redefined, the other columns will be scaled down or enlarged to fit the new window. You can control this behavior using the Setautoresizemode () method: Table.setautoresizemode (int mode), and the possible values for the mode integer field are: Auto_resize_offauto_resize_ Next_columnauto_resize_subsequent_columnsauto_resize_last_columnauto_resize_all_columns
Default values for tables
The default color for a grid coordinate line in a cell is Color.gray. To change the color of these grid coordinate lines, use the following: Table.setgridcolor (color.black); You can change the height of the line by: Table.setrowheight (intpixelheight); The height of each cell equals the height of the row minus the distance between the rows. By default, the foreground color of the content and the selection of the background color are determined by what swing sees as the resulting 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 grid coordinate line of a cell, as follows: Table.setshowhorizontallines (false); Table.setshowverticallines (false); Figure A shows a jtable that hides its horizontal coordinate line.
Figure A
Width of column
The JTable component has several classes and interfaces that control the table's attributes. TableColumn keeps track of the width of the columns and is responsible for resizing the columns, including the maximum and minimum widths. Tablecolumnmodel manages the collection of Tablecolumns and the selection of columns. To set the width of a column, you set a reference for the table column's model. Then, get the desired tablecolumn and call its Setpreferredwidth () method: Tablecolumncolumn = Table.getcolumnmodel (). GetColumn (0); Column.setpreferredwidth (100); The index of the column does not change when the user drags the column. The GetColumn (0) method always returns the correct column, regardless of where it appears on the screen.
Title
Jtableheader will handle the display of jtable headers. You can subdivide the Jtableheader to get a custom layout. For example, if your application needs a header that spans multiple columns, simply subdivide the jtableheader and integrate it into your jtable. You can specify whether the title reordering is allowed by setting a reference for the current jtable Jtableheader or by calling its setreorderingallowed () method: Table.gettableheader (). Setreorderingallowed (false); Similarly, you can be sure that the column is not resized by dragging between column headings. To achieve this, you will use the Setresizingallowed () method: Table.gettableheader (). setresizingallowed (false);
Selection mode
By default, when a user selects a cell in the jtable, the entire row is selected. There are several ways to allow users to customize the way they choose. With the ListSelectionModel interface, you can allow users to select single or multiple rows: Table.setselectionmode (listselectionmodel.single_selection); ListSelectionModel have the following fields:
Single_selection allows you to select one row at a time. Single_interval_selection allows you to select adjacent series of rows. Multiple_interval_selection also allows you to select adjacent columns, but with extended functionality. It allows the user to use the [Ctrl] key to select multiple nonadjacent selections (that is, nonadjacent rows are selected).
The Setcellselectionenabled () method allows the user to select either a single cell or an entire row at the same time: table.setcellselectionenabled (TRUE); The Setcellselectionenabled () method also allows you to select a column while selecting a row and a single cell, if shown in Figure B.
Figure B
Edit Cells
Our simple table allows the user to edit any cell in the table. Listing b lists a table that allows programmers to decide which cells can be edited. The first step is to create a custom Tablemodel:class Simpletablemodel extends Abstracttablemodel {} data is encapsulated in TableModel, when JTable initializes 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 the second and third columns to be editable and the first column to be constant, then you have to force an alternative to the TableModel isCellEditable () method: Public booleaniscelleditable (int row, intcol) {if (col = 0) {return false;} else {return true;}}
Simple table Validation
You need to make sure that the user only enters an integer value, and if so, enter a value into the second column ("Number of boxes") to force an alternative to the setValueAt () method and include the validation logic in the new method. First, you want to check whether the column is an integer, and whether the column should contain only an integer value: if (Data[0][col] instanceof integer &&! ( Value instanceof Integer)} {...} else {Data[row][col] = value;} Then, check to see if the value being inserted is an integer. If it is not, then the field should not be updated, and an error message should be displayed: try {data[row][col] = new Integer (value.tostring ()); NumberFormatException e) {joptionpane.showmessagedialog (simpletable.this, "Please enter only integer values.");}
Background color
Listing c contains code for Colortable.java, which shows how to add color to jtable. You can add a background color to JTable by forcing an override of 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 color and what color 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 color the text displayed in the cell so that it becomes more readable. Figure C shows a jtable with a first column and a second column plus a color.
Figure C
Everything is under control.
Our example is just the basis of jtable other parts. By using these tools, you can quickly and easily control the formatting of the tables generated by your Java application so that your users do not encounter obstacles while they are in normal use.
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.