1. 程式人生 > >JTable 如何設定表格的列寬

JTable 如何設定表格的列寬

import java.awt.BorderLayout;

import javax.swing.*;
import javax.swing.table.*;
/**
 * 教你如何設定表格的列寬
 * @author Administrator
 *
 */
public class Table_TableColumn extends JFrame {
	Object[][] data = {{"王鵬","001","69","87"},
			{"李斯","002","69","87"},
			{"全脂","003","69","87"},
			{"陸遠","004","69","87"}};
	Object[] head = {"姓名","學號","科目1","科目2"};
	JTable jt;
	JScrollPane jsp;
	TableColumn column;
	public Table_TableColumn() {
		jt = new JTable(data,head);
//		設定列表頭不可別使用者重新拖動排列
		jt.getTableHeader().setReorderingAllowed(false);
		jsp = new JScrollPane(jt);
//      JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS  此為系統的預設值   當調整某列寬時,此欄位後的所有列寬都會跟著一起變動
//		JTable.AUTO_RESIZE_ALL_COLUMNS   當調整某列寬時,所有的欄位的所有列寬都會跟著一起變動
//		JTable.AUTO_RESIZE_NEXT_COLUMN    當調整某列寬時,此欄位後的下一列列寬都會跟著一起變動,其他列不變
//		JTable.AUTO_RESIZE_LAST_COLUMN    當調整某列寬時,最後一個欄位列的列寬都會跟著一起變動,其他列不變
//		JTable.AUTO_RESIZE_OFF             當調整某列寬時,所有列列寬都不變
		jt.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
		this.add(jt.getTableHeader(),BorderLayout.NORTH);
		this.add(jsp,BorderLayout.CENTER);
		this.setBounds(10, 100, 400, 200);
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new Table_TableColumn();
	}

}