Micro-level of JTable usage (specific operations)

Source: Internet
Author: User

JTable is composed of data and columnNames:
JTable table = new JTable (data, columnNames );

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 "},
};

The JTable height and width are set as follows:
Table. setPreferredScrollableViewportSize (new Dimension (300, 80 ));

If the size of one column in The JTable or the size of the JTable window is re-determined

To adapt to the new window. Use setAutoResizeMode ()

This behavior can be controlled:
Table. setAutoResizeMode (int mode );

The possible values of the mode integer field are:
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 is Color. gray. To change the appearance of these square coordinate lines

Color, 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 all seen by Swing.

To determine. 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 );

Column width

The JTable component has several classes and interfaces that control table features. TableColumn will keep track of the column's

Width, and adjust the column size, including the maximum and minimum width.

TableColumnModel manages the TableColumns set and column selection. To set a column

To set a reference for the model of the table column. Then, obtain the desired

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 will always

Returns the correct column, no matter where it appears on the screen.

Title

JtableHeader displays the JTable title. You can segment the JtableHeader to obtain

Defined layout. For example, if your application requires a title that spans multiple columns

Just 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 reach this

Purpose: 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. Use ListSelectionModel to connect

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 adjacent rows.
* MULTIPLE_INTERVAL_SELECTION can also select adjacent columns, but with extensions

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:
Table. setCellSelectionEnabled (true );

If it is set to yes, the setCellSelectionEnabled () method also allows

Cells and columns

Edit Cells

This simple table allows users to edit any cells in the table. Listing B lists

A table that allows programmers to determine which cells can be edited. Step 1: Create 1

Custom TableModel:
Class SimpleTableModel extends acttablemodel {}

Data is encapsulated in TableModel. When JTable is initialized, the custom TableModel

It is passed to the JTable constructor as a parameter 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

The isCellEditable () method of TableModel must be forcibly replaced:
Public booleanisCellEditable (int row, intcol ){
If (col = 0) {return false ;}
Else {return true ;}
}

Simple Table Verification

Make sure that the user only enters the integer value. For example, to the second column ("number of boxes ")

) Enter a value to forcibly replace the setValueAt () method, and include the verification logic 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

This is 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 code for ColorTable. java, which explains how to add

Color. You can add a background to the JTable by forcibly replacing its prepareRenderer () method.

Color:
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

Text color to make it easier to read. Figure C shows a combination of the first and second columns

Color JTable.

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.