JTable的基本使用
1.JTable的使用DefaultTableModel
/*将表格头转换过向量类型,以备表格模型使用*/
String[] tableHeads = {"ID", "姓名", "年龄", "城市"};
Vector tableHeadName = new Vector();
for (int i = 0; i < tableHeads.length; i++) {
tableHeadName.add(tableHeads[i]);
}
/*初始化表格数据,这些数据实例运行来源于数据库中*/
Vector cell;
Vector row = new Vector();
for (int i = 1; i <= 100; i++) {
cell = new Vector();
cell.add("" + i);
cell.add(" 水如清" + i);
cell.add(" 22");
cell.add(" 深圳");
row.add(cell);
}
/*设置表格模型*/
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.setDataVector(row, tableHeadName);
this.jTable1.setModel(tableModel);
2.表格间隔色显示方法
public static void makeFace(JTable table) {
try {
DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
public @Override Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (row % 2 == 0) {
setBackground(Color.white); /*设置奇数行底色*/
} else if (row % 2 == 1) {
setBackground(new Color(206, 231, 255)); /*设置偶数行底色*/
}
return super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
}
};
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
3.继承一个AbstractTableModel
class DataModel extends AbstractTableModel {
/* 抽象AbstractTableModel类为 TableModel 接口中的大多数方法提供默认实现。
* 它负责管理侦听器,并为生成 TableModelEvents 以及将其调度到侦听器提供方便
* 要创建一个具体的 TableModel 作为 AbstractTableModel 的子类,只需提供对以下三个方法的实现:
* public int getRowCount(); /* 返回此数据表中的行数
* public int getColumnCount(); /* 返回此数据表中的列数
* public Object getValueAt(int row, int column); /* 返回 row 和 column 处单元格的属性值
*/
class TML implements TableModelListener {
/* TableModelListener定义侦听 TableModel 中更改的对象的接口. */
public void tableChanged(TableModelEvent e) {
/* void tableChanged(TableModelEvent e)
此细粒度通知告知侦听器单元格、行或列的哪些具体范围发生了更改。 */
//将数据保存至指定的文件中
// try {
// OutputStream fos = new FileOutputStream("list.dat");
// //创建字节文件输出流
// BufferedOutputStream bos = new BufferedOutputStream(fos);
// /* 创建一个文件缓冲输出流 */
// dos = new DataOutputStream(bos);
// for (int r = 0; r < RowCount; r++) {
// for (int c = 0; c < ColumnCount; c++) {
// dos.writeUTF((data[r][c]).toString());
// }
// }
// dos.close();
// } catch (Exception b) {
// }
}
}
DataModel() { //构造方法
addTableModelListener(new TML());
/* void addTableModelListener(TableModelListener l)
每次数据模型发生更改时,就向被通知的列表添加一个侦听器。*/
}
public int getColumnCount() { /* 返回此数据表中的列数 */
return data[0].length;
}
public int getRowCount() { /* 返回此数据表中的行数 */
return data.length;
}
public Object getValueAt(int row, int col) { /* 返回 row 和 column 处单元格的属性值 */
return data[row][col];
}
@Override
public String getColumnName(int col) {
/* String getColumnName(int column)
返回列默认名称,其中列使用以下工作表约定:A、B、C Z、AA、AB 等等。
*/
return columnName[col];
}
@Override
public void setValueAt(Object val, int row, int col) {
/* void setValueAt(Object aValue, int rowIndex, int columnIndex)
由于提供了此空实现,因此,如果用户的数据模型是不可编辑的,则他们不必实现此方法。
*/
data[row][col] = val;
fireTableDataChanged();
/* void fireTableDataChanged()
通知所有侦听器,表的所有行单元格值可能已更改。
*/
}
@Override
public boolean isCellEditable(int row, int col) {
/* boolean isCellEditable(int row, int column)
无论参数值是多少都返回 true,用于设置用户选中的单元格为可编辑状态。
*/
return true;
}
}
4.在JTable中按回车键水平移动
/**
* 设置在JTable中按回车键水平移动
* @param table JTable对象
* */
public static void setFocusMoveHorizontal(JTable table) {
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextColumnCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextColumnCell");
}
5.单元格获得焦点立即进入编辑状态
private void jTable1FocusGained(java.awt.event.FocusEvent evt) {
int row, col;
row = jTable1.getSelectedRow();
col = jTable1.getSelectedColumn();
//下面程序触发开始编辑,然后全选编辑器的文本
jTable1.editCellAt(row, col);
// DefaultCellEditor cell = (DefaultCellEditor) jTable1.getCellEditor(row, col);
// cell.getComponent().requestFocus();
JTextField editor = ((JTextField)jTable1.getCellEditor().getTableCellEditorComponent(jTable1,jTable1.getValueAt(row,col),true,row,col));
editor.requestFocus();
editor.selectAll();
}
6.自定义CellEditor,CellRender。
public class DefineEditor extends javax.swing.JInternalFrame {
private JTable table;
String[] states = new String[]{"stop", "stop", "stop"};
/** Creates new form DefineEditor */
public DefineEditor() {
//initComponents();
table = new JTable(new TableModel());
TableColumn tableColumn = table.getColumnModel().getColumn(1);
tableColumn.setCellRenderer(new Renderer());
tableColumn.setCellEditor(new Editor());
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
this.setSize(500, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//table model
class TableModel extends AbstractTableModel {
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return states.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return states[rowIndex];
}
return null;
}
@Override
public String getColumnName(int columnIndex) {
if (columnIndex == 0) {
return "state";
} else {
return "operate";
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return false;
} else {
return true;
}
}
}
// cell editor
class Editor extends AbstractCellEditor implements TableCellEditor, ActionListener {
int row;
JTable table;
JPanel panel;
JButton start;
JButton stop;
Editor() {
panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
start = new JButton("start");
stop = new JButton("stop");
start.addActionListener(this);
stop.addActionListener(this);
panel.add(start);
panel.add(stop);
}
public Object getCellEditorValue() {
return null;
}
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
this.table = table;
this.row = row;
return panel;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
states[row] = "start";
} else {
states[row] = "stop";
}
((AbstractTableModel) table.getModel()).fireTableCellUpdated(row, 0);
}
}
// cell render
class Renderer extends JComponent implements TableCellRenderer {
JPanel panel;
JButton start;
JButton stop;
Renderer() {
panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
start = new JButton("start");
stop = new JButton("stop");
panel.add(start);
panel.add(stop);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return panel;
}
}
}