代码如下
package com.nfs;
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TestSimpleJTable {
private static DefaultTableModel tableModel1 = new DefaultTableModel() {
public boolean isCellEditable(int row, int col) {
if (col == 1) {
return true;
}
else {
return false;
}
}//使得第二列的单元格子可编辑,其他列的单元格子不可编辑
// public Class getColumnClass(int col) {
// Vector v=(Vector)dataVector.elementAt(0);
// return v.element(col).getClass();
// }
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}//可以使单元格子实现Image,CheckBox等
};
private JTable jTable1 = new JTable(tableModel1);
public static void main(String[] args) {
String[][] data = {{"A", "B"}, {"C", "D"}};
String[] colName = {"First", "Last"};
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
JTable table = new JTable(data,colName){//(tableModel1){
/**
* long
*/
private static final long serialVersionUID = 1L;
// JTable的RowSelectionChanged事件在这里。
public void valueChanged(ListSelectionEvent e) {
super.valueChanged(e);
if (!this.isVisible()) {
return;
}
ListSelectionModel sm =
(ListSelectionModel)e.getSource();
int row = sm.getLeadSelectionIndex();
int colCount = this.getColumnCount();
String[] sa = new String[colCount];
for (int col=0; col<colCount; col++) {
sa[col] = (String)this.getValueAt(row, col);
}
String s = "";
for (int i=0; i<sa.length; i++) {
s += sa[i] + "\t";
}
System.out.println("--->>>"+s);
field.setText(s);
}
};
JTable table1 = new JTable(tableModel1);
tableModel1.addRow(new Object[] {new ImageIcon( "C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\1.gif "), new Boolean(false), "John ", "male ", "23 "});
tableModel1.addRow(new Object[]{"111","222","233","444","555"});
Vector<String> columnNames = new Vector();
// String[] m_colNames = { "子服务ID", "主服务ID",
// "子服务名称","开始路径","日志路径","备注","是否启用","是否可视","创建时间"};