<span style="font-size:14px;">import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TableTest extends JFrame{
private JTable table;
private DefaultTableModel defaultTableModel = null;
private JScrollPane scrollPane;
String Names[] = {"姓名", "性别","年龄","电话","特长","所属"};
Object[][] playerInfo = {
{"唐僧","男","28","100","念经","取经团队"},
{"孙悟空","男","600","101","打妖怪","取经团队"},
{"猪八戒","男","37","102","散伙","取经团队"},
{"沙和尚","男","56","103","挑担子","取经团队"},
{"白龙马","男","123","104","驼唐僧","取经团队"}
};
private String ss[][];
public TableTest() {
setTitle("表格测试");
setSize(500, 300);
setLocation(500, 200);
scrollPane = new JScrollPane();
scrollPane.setSize(300, 200);
//创建一个只有表头的表格模型
defaultTableModel = new DefaultTableModel( null,Names);
//将playerInfo中非空元素插入表中
for(Object[] x:playerInfo){
if(x[0]!=null){
defaultTableModel.addRow(x);
}
}
table = new JTable(defaultTableModel);
//设置单元格中的文字居中 非表头单元格
DefaultTableCellRenderer r = new DefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(Object.class, r);
scrollPane.setViewportView(table);
add(scrollPane);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
/* //获取表格中的信息
*
* Vector data = defaultTableModel.getDataVector();
* VectorToString(data);
*
*/
}
//将二维矢量数组转化成二维字符串数组 存储在数组ss中
public void VectorToString(Vector data){
Vector rowData;
ss = new String[10][3];
String field="";
for(int i = 0; i<data.size();i++){
rowData =(Vector) data.get(i);
for(int j=0;j<rowData.size();j++){
field = (String) rowData.get(j);
ss[i][j] = field;
}
}
}
public static void main(String[] args) {
new TableTest();
}
}</span>
效果图如下:
如需要对表格的更多操作可参考以下两个例子: