在Java程序設計中,會經常用到JTable組件,默認的JTable組件的列寬是等長的,
如此這般就限制了表格的美觀性。如果有一列是實現身份證號碼的,這一列寬度
就會明顯的不足,所以我們要解決這種情況,代碼如下所示:
public void TableTest() { String[] type = {"列1","列2","列3","列4","列5","列6","列7"}; Vector<String> Column = buildTableModel(type); Vector<Vector<String>> Values = new Vector<Vector<String>>(); DefaultTableModel Model = new DefaultTableModel(Values, Column); JTable tab = buildTable(Model); tab.setColumnModel(getColumn(table, width)); //設置不等列寬,width是int型一維數組 } /** * Autor: Kilper * Blog: http://blog.csdn.net/Kilper */ public Vector<String> buildTableModel(String[] type) { Vector<String> vector = new Vector<String>(); for (int i = 0; i < type.length; i++) vector.add(type[i]); return vector; } /** * Autor: Kilper * Blog: http://blog.csdn.net/Kilper */ public static JTable buildTable(DefaultTableModel model) { JTable table = new JTable(model); table.setShowGrid(true); table.setGridColor(Color.BLUE); table.setRowHeight(20); table.setFont(new Font("", Font.PLAIN, 12)); return table; } /** * Autor: Kilper * Blog: http://blog.csdn.net/Kilper */ public static TableColumnModel getColumn(JTable table, int[] width) { TableColumnModel columns = table.getColumnModel(); for (int i = 0; i < width.length; i++) { TableColumn column = columns.getColumn(i); column.setPreferredWidth(width[i]); } return columns; }
文章來源於:http://blog.csdn.net/kilper/article/details/5821430