Java中Table的应用

<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>



效果图如下:



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

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值