请问如何改变(设置)JTable对象的第i列列宽?

alphazhao 2002-05-24 05:59:58
我通过扩展AbstractTableModel,通过提供getRowCount,getColumnCount,getValueAt三个方法,利用数据库查询的结果集ResultSet,将查询数据库的结果用一个JTable显示出来。
现在问题来了,我想问一下JTable有没有方法可以设置第i列的列宽?
我找了找帮助,硬是没有找倒……

哪位兄台可以帮我啊?
...全文
187 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
alphazhao 2002-05-24
  • 打赏
  • 举报
回复
多谢各位了
呆会结贴
现在吃饭去也……
呵呵
soldier1002 2002-05-24
  • 打赏
  • 举报
回复
and use the following fuction to automatically adjust


private void initColumnSizes(JTable table, MyTableModel model, Object[][] tableData){
TableColumn column = null;
int headerWidth = 0;
int cellWidth = 0;

//resize the first columan size to feet
for(int i = 0; i<1; i++){
column = table.getColumnModel().getColumn(i);
String colName = tmodel.getColumnName(i);
JTextField t = new JTextField(colName);
headerWidth = new Double((t.getPreferredSize().getWidth())).intValue();
for(int j =0; j<tableData.length ; j++){
t = new JTextField(tableData[j][i].toString());
cellWidth = Math.max(cellWidth, t.getPreferredSize().width);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
Apocalypse 2002-05-24
  • 打赏
  • 举报
回复
table.getColumn("column name").setMinWidth(width);
table.getColumn("column name").setMaxWidth(width);
table.setColumnsToFit(0); //据说是JTable的bug,必须如此调用
soldier1002 2002-05-24
  • 打赏
  • 举报
回复

public class MyTableModel extends AbstractTableModel{
Object[][] data;
String[] columnNames;
public MyTableModel(Object[][] tableData, String[] inColumnNames){
data = tableData;
columnNames = inColumnNames;
}

public Object getValueAt(int row, int col){
return data[row][col];
}

public Class getColumnClass(int c){
return getValueAt(0, c).getClass();
}

public int getColumnCount(){
return data[0].length;
}
public int getRowCount(){
return data.length;
}
public String getColumnName(int col){
return columnNames[col];
}

public boolean isCellEditable(int row, int col){
if(col == 2){
return true;
}else{
return false;
}
}
public void setValueAt(Object value, int row, int col){
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
soldier1002 2002-05-24
  • 打赏
  • 举报
回复
or also can automatically adjust the columan size for differnt table header and content,
soldier1002 2002-05-24
  • 打赏
  • 举报
回复
javax.swing.table.TableColumnModel tcm = jTable1.getColumnModel();
javax.swing.table.TableColumn tc =tcm.getColumn(1);
tc.setPreferredWidth(130);

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧