Java中Table的应用

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



效果图如下:

Java中Table的应用_第1张图片


如需要对表格的更多操作可参考以下两个例子:

http://download.csdn.net/detail/baalhuo/9076895

http://download.csdn.net/detail/baalhuo/9076905

你可能感兴趣的:(Java)