JavaDoc對JTable的解釋是用來顯示和編輯常規(guī)二維單元表,JTable是Swing中最復雜的組件,它是一個規(guī)則的二維表,但是又因為它有很多Renderer和Editer使得它可以實現(xiàn)很多復雜的效果.
JTable也是遵循MVC模式設計和實現(xiàn)的,Model使用的是實現(xiàn)TableModel接口的類,Java提供了AbstractTableModel和DefaultTableModel供我們使用,我們也可以通過實現(xiàn)TableModel接口或者繼承AbstractTableModel使用我們自己的Model.
JTable的View內(nèi)的方法都是通過修改TableModel的數(shù)據(jù)然后再通過fireTableStructureChanged反映到畫面的.
JTable的UI都是通過TbaleUI和TableHeaderUI控制的,JTable再通過CellRenderer,CellEditor,HeaderRenderer和HeaderEditor等渲染它的外觀.
當然對于JTable的操作就不會這么簡單了,它實現(xiàn)了ColumnModel,RowModel,SelectedModel,DropModel等處理各種事件,對應也有各種Renderer,這些我們一般都不會太關(guān)心.因為我們實際運用JTable時遇到的主要問題不在這些方面.
我們一般關(guān)心的是外觀,那樣的話主要關(guān)注的是UI;關(guān)注數(shù)據(jù)存儲性能,需要修改的是Model;關(guān)注外觀渲染形式,則需要修改的是各種Renderer和Editor,除非真的需要關(guān)注復雜事件,否則一般我們不會重寫后面的那些Model.
首先還是從最基礎(chǔ)的應用開始說起:
先看Sun官方的例子:

這個例子是最最簡單的JTable的應用,沒有修改JTable的任何樣式,只是單純的賦予數(shù)據(jù).
先定義JTable的表頭:
// table
column
String[] columnNames = { "First Name", "Last
Name", "Sport", "# of
Years", "Vegetarian" };
然后是JTable內(nèi)的數(shù)據(jù):
// table
data
Object[][] data = {
{ "Mary", "Campione", "Snowboarding", new Integer(5),
new Boolean(false) },
它的列數(shù)是和表頭對應的,當然也可以用Vector定義.
然后把JTable創(chuàng)建出來:
final JTable table = new
JTable(data, columnNames);
然后設置一個首先大小:
table.setPreferredScrollableViewportSize(new Dimension(500, 120));
table.setFillsViewportHeight(true);
最后顯示到畫面:
// Create
the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
然后開始改變它,首先是外觀顯示:
改變線的顏色:
//Sets the color used to draw grid lines
table.setGridColor(Color.red);
改變行高:
//Sets the height, in pixels
table.setRowHeight(20);
改變前景色、背景色:
//Sets the background color of this component
table.setBackground(Color.cyan);
//Sets the foreground color of this component
table.setForeground(Color.black);
改變選擇模式:
//Sets the
table's selection mode to allow
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
改變某列的寬度:
//Sets this column's preferred width
table.getColumnModel().getColumn(2).setPreferredWidth(150);
使列不可大小變動:
//Sets
whether the user can resize columns
table.getTableHeader().setResizingAllowed(false);
JTable自動調(diào)整大小:
//Sets the table's auto resize
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
隱藏某一列:
//hide column
table.getColumnModel().getColumn(3).setMaxWidth(0);
table.getColumnModel().getColumn(3).setMinWidth(0);
最后效果如下圖:
當然JTable還有很多的屬性可以定制,直接參考API就可以了,可惜的是JTable的好多屬性定制都是大眾化的,比如我們只需要一條線是帶顏色的,只需要某一種類型的數(shù)據(jù)是變色的就需要自己實現(xiàn)Renderer來渲染了,這在以后會寫到.
然后是JTable的事件處理,JTable 繼承于JComponent,這樣它就有了JComponent的全部事件,但是對于容器變更addComponentListener,
屬性變更addPropertyChangeListener等事件我們一般都不會關(guān)心,我們關(guān)心的主要是鼠標事件addMouseListener和選擇事件addListSelectionListener,這兒演示下這兩種事件的處理:
首先是選擇事件:
行選擇事件:
ListSelectionModel
rowSM = table.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
publicvoid valueChanged(ListSelectionEvent e) {
列選擇事件:
ListSelectionModel
colSM = table.getColumnModel()
.getSelectionModel();
colSM.addListSelectionListener(new ListSelectionListener() {
publicvoid valueChanged(ListSelectionEvent e) {
然后根據(jù)lsm.getMinSelectionIndex();就可以取得現(xiàn)在選擇的行和列了.
② 然后是鼠標事件:
直接在JTable上加監(jiān)聽: table.addMouseListener(this);
然后處理就可以了.
@Override
publicvoid mouseClicked(MouseEvent e) {
if
(e.getSource() instanceof JTableHeader) {
if
(SwingUtilities.isRightMouseButton(e)) {
// right mouse button click in JTableHeader
}
} else {
if
(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2)
{
// double left mouse button click in JTable
//Returns the index of the row that point lies in
int row = table.rowAtPoint(e.getPoint());
//Returns the index of the column that point lies in
int column = table.columnAtPoint(e.getPoint());
//return cell value
System.out.println(table.getValueAt(row, column));
} elseif (SwingUtilities.isRightMouseButton(e)) {
// right mouse button click in JTable
}
}
}
最后再說下JTable的數(shù)據(jù)模型,JTable默認使用DefaultTableModel數(shù)據(jù)模型,所有的數(shù)據(jù)都是String的,所有的單元格都是可編輯的,這明顯不滿足我們的需求,所以我們大部分時候需要自己實現(xiàn)數(shù)據(jù)模型.
這里我們繼承AbstractTableModel類來實現(xiàn)自己的數(shù)據(jù)模型.
//own
table model.
class MyTableModel
extends AbstractTableModel {
復寫方法:
@Override
public Class<? extends Object>
getColumnClass(int c) {
return
getValueAt(0, c).getClass();
}
實現(xiàn)單元格是指定的數(shù)據(jù)類型
@Override
publicvoid setValueAt(Object value, int row, int col) {
data[row][col] =
value;
fireTableCellUpdated(row, col);
}
實現(xiàn)單元格值改變
@Override
publicboolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col <
2) {
returnfalse;
} else {
returntrue;
}
}
實現(xiàn)單元格編輯
最后使用它:
JTable table = new JTable(new MyTableModel());
效果圖:
到這里,簡單的JTable的使用就完成了,我們可以用數(shù)據(jù)填充一個JTable,可以改變編輯,可以設置前景色、背景色,可以設置列寬度,可以設置監(jiān)聽,至于復雜的比如合并單元格、排序、改變表頭、合并表頭、增加行號、增加懸浮提示、表頭隱藏、Table內(nèi)放置組件、特殊效果等會在以后介紹.