我有一个带有两个选项卡的 tappedpane 的 jframe。每个选项卡包含一个jtable,每个jtable都连接到一个单独的tablemodel jframe类有一个渲染器方法,可以将列的宽度调整为列中最长文本的长度renderer方法被硬编码到一个表模型中. 但是希望将 tablemodel 类作为变量传递给渲染器方法。
这是模型数据的代码
public class MyTableModel extends AbstractTableModel {
private List<List<Object>> dataList = new ArrayList<>();
private String[] header = { "ID","SUBJECT","LETTTER FROM","LETTER DATE","DATE RECEIED",
"REMARKS","DATE DISPATCHED","DESTINATION OFFICE"};
private int minRowCount = 5;
public MyTableModel()
{ }
public List<List<Object>> getDataList() {
return dataList;
}
public void setDataList(List<List<Object>> dataList) {
this.dataList = dataList;
fireTableDataChanged();
fireTableStructureChanged();
}
public void setHeader(String[] header) {
this.header = header;
}
public String[] getHeader() {
return header;
}
@Override
public int getRowCount() {
return Math.max(minRowCount, dataList.size());
}
@Override
public int getColumnCount() {
return header.length;
}
@Override
public String getColumnName(int col) {
return header[col];
}
@Override
public Object getValueAt(int row, int col) {
Object value = null;
if(row < dataList.size())
{value = dataList.get(row).get(col);}
return value;
}
@Override
public Class<?> getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
}
这是在 jframe 类中初始化 tabemdel 对象的代码
MyTableModel myModel = new MytableModel();
下面是渲染器方法的代码
public final void setColumnWidth( )
{ int width = 0; //width of column
int headerWidth = 0; //width of header
//create header renderrer
final TableCellRenderer headerRenderer = resultTable.getTableHeader().getDefaultRenderer();
for(int myColumn = 0 ;myColumn < resultTable.getColumnCount(); myColumn++)
{ width = 0;
headerWidth = 0;
width = 0;
Component hcomp = headerRenderer.getTableCellRendererComponent(
resultTable, resultTable.getModel().getColumnName(myColumn), false, false, 0, myColumn);
headerWidth = Math.max(hcomp.getPreferredSize().width , headerWidth);
resultTable.getColumnModel().getColumn(myColumn).setPreferredWidth(headerWidth);
//iterate through the rows to find the widest cell
for (int row = 0; row < resultTable.getRowCount(); row++) {
TableCellRenderer renderer = resultTable.getCellRenderer(row, myColumn);
Component comp = resultTable.prepareRenderer(renderer, row, myColumn);
width = Math.max (comp.getPreferredSize().width, width);
width = Math.max(width, headerWidth);
//set the columnwith to the widest cell
resultTable.getColumnModel().getColumn(myColumn).setPreferredWidth(width);
}
} }
问题是每个表模型类都扩展了 AbstractModelTable
关于如何实现这一目标的任何建议