我正在创建我的第一个 JTable,它需要我创建一个自定义AbstractTableModel
、TableCellEditor
和DefaultTableCellRenderer
. 鉴于我以前不需要创建这些,我在让我的表按预期运行方面取得了一些重大进展。
但是,我对我要覆盖的所有不同方法感到不知所措,并且正在转动我的轮子试图弄清楚如何修改特定单元格的 ImageIcon。 该单元格必须包含一个 JLabel,因为它既需要一个文本字符串,也需要 ImageIcon
一个文本字符串。我已经可以设置初始值ImageIcon
(尽管我可能做错了),但我无法设置更新的ImageIcon
. 没有失败,但没有改变。
一般来说,假设所有这些模型、编辑器和渲染器都已实例化,那么获取图标并将其设置为 a 的JLabel
单元格的最佳方法是什么?JTable
我的模型已经定义为返回JLabel.class
这些单元格,如果您想知道的话,我也会在fireTableCellUpdated(row, col)
应该进行更改后执行此操作。如果我System.out.println(getIcon())
在更新之前和之后做一个,我什至可以看到源已经改变了。
下面是一些代码(更新了 URL/ImageIcon 修复):
class MonitorTable extends JTable {
MonitorTableModel model = new MonitorTableModel(rows, columnNames);
setModel(model);
...
public void setIconAt(ImageIcon icon, int row, int col) {
model.setIconAt(icon, row, col);
} // End setIconAt(ImageIcon, int, int)
...
class MonitorTableModel extends AbstractTableModel {
...
public void setIconAt(ImageIcon icon, int row, int col) {
StatusTableCellRenderer cell =
(StatusTableCellRenderer)getColumnModel().getColumn(col).getCellRenderer().
getTableCellRendererComponent(myTableObject, null, false, false, row, col);
System.out.println(cell.getIcon()); // Shows initial icon source
cell.setIcon(icon);
fireTableCellUpdated(row, col); // Should update the table
System.out.println(cell.getIcon()); // Shows new icon source
System.out.println("Cell updated");
} // End setIconAt(ImageIcon, int, int)
} // End class MonitorTableModel
public class StatusTableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
setIcon(imgGray);
setText((String)value);
return this;
} // End getTableCellRendererComponent(JTable, Object, boolean, boolean, int, int)
} // End class StatusTableCellRenderer
} // End class MonitorTable