[英]JTable with different row types
我想在我的程序中實現一個具有多種類型的不同行的JTable
。
這是一個例子:
因此,基本上costs
是這樣計算的:
Sale * Production * Production % = Costs
我完全不確定的是:如何為JTable模型中的每一行賦予新的列“類型”。 目前,我正在像這樣使用JTable模型:
public Object getValueAt(int row, int col) {
Customer cd = customerList.get(row);
switch (col) {
case 0:
return cd.getName();
case 1:
return cd.getAge();
case 2:
return cd.getPhone();
default:
break;
}
return null;
}
關於如何實現此用例的任何建議?
感謝您的回答!
如果您希望行中的單元格具有特殊的格式或數據類型,則只需執行您為Customer
所做的操作,然后切換列和行即可,即,假設您表中的一個條目由單列表示。
因此,只需執行以下操作:
Report report = reports.get(col - 1); //made those names up but you should get the idea
switch (row) {
...
case 5:
double p = report.getPercentage(); //assuming 10% is stored as 0.1
return String.format("%.0f%%", p * 100); //%.0f means a floating point number with 0 fraction digits
...
}
或者(例如,如果您的模型需要更靈活或者您只有一堆值,例如作為2D數組)將類型(即,如何顯示值)存儲在具有行,列或單元格(行)的地圖中和列)索引作為鍵。
更新:
正如mKorbel在評論中所說,最好讓渲染器進行格式化。 但是,問題在於您不能只為每行注冊一個渲染器,因此您必須提出另一種解決方案。
現在有兩個突然出現在我的腦海:
子類JTable
是為了重寫getCellRenderer(row, col)
,以便為需要它的行提供PercentageCellRenderer
。 您必須配置例如表模型中的哪一行。
提供一個標准的單元格渲染器,該渲染器檢查getTableCellRendererComponent()
的行和列,並相應地應用格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.