在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