我想防止列被调整为大于 10px。我希望它很小,因为它只包含复选框。
我在这里实例化 JTable:
private void initDataSearchResultTable()
{
dataSearchResultTable = new JTable();
dataSearchResultTable.setSelectionBackground(new Color(0xaaaaff));
dataSearchResultTable.setFillsViewportHeight(true);
dataSearchResultTable.setRowSelectionAllowed(true);
dataSearchResultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
dataSearchResultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
我在这里为表格设置表格模型(当用户单击按钮时):
void updateDataSearchTableModel(CachedRowSet cachedRowSet)
{
TableModel tableModel = dataSearchResultTable.getModel();
if (tableModel instanceof DataSearchTableModel) {
((DataSearchTableModel) tableModel).updateModel(cachedRowSet);
} else {
tableModel = new DataSearchTableModel(cachedRowSet);
dataSearchResultTable.setModel(tableModel);
this.setCellRendererForDataSearchTable();
((DataSearchTableModel) tableModel).structureChanged();
}
}
在方法 structureChanged() 中,我调用方法 fireTableStructureChanged()。这可确保布尔列呈现为复选框。
接下来,我尝试设置 0 和 1 列的宽度并使其可调整大小。它不起作用:
private void setCellRendererForDataSearchTable()
{
DataSearchResultTableCellRenderer cellRenderer = new DataSearchResultTableCellRenderer();
TableColumnModel columnModel = dataSearchResultTable.getColumnModel();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
TableColumn column = columnModel.getColumn(i);
if (i == 0) {
column.setMaxWidth(15);
column.setResizable(false);
} else if (i == 1) {
column.setMaxWidth(30);
column.setResizable(false);
}
column.setCellRenderer(cellRenderer);
}
}
我的渲染器只为选定的单元格设置边框。我的表格模型更有趣:
public DataSearchTableModel(CachedRowSet cachedRowSet)
{
this.cachedRowSet = cachedRowSet;
updateModel(this.cachedRowSet);
}
public void updateModel(CachedRowSet cachedRowSet)
{
try {
metaData = this.cachedRowSet.getMetaData();
this.numOfCols = metaData.getColumnCount();
// Retrieve the number of rows.
this.cachedRowSet.beforeFirst();
this.numOfRows = 0;
while (this.cachedRowSet.next()) {
this.numOfRows++;
}
this.cachedRowSet.beforeFirst();
} catch (SQLException e) {
e.printStackTrace();
}
}
但这不起作用,那些列仍然调整大小并且宽度错误?
谢谢!