一种方法是存储模型中每一行的当前颜色。这是一个固定在3列3行的简单模型:
static class MyTableModel extends DefaultTableModel { List<Color> rowColours = Arrays.asList( Color.RED, Color.GREEN, Color.CYAN ); public void setRowColour(int row, Color c) { rowColours.set(row, c); fireTableRowsUpdated(row, row); } public Color getRowColour(int row) { return rowColours.get(row); } @Override public int getRowCount() { return 3; } @Override public int getColumnCount() { return 3; } @Override public Object getValueAt(int row, int column) { return String.format("%d %d", row, column); }}
注意
setRowColour通话
fireTableRowsUpdated; 这将导致仅更新表的该行。
渲染器可以从表中获取模型:
static class MyTableCellRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { MyTableModel model = (MyTableModel) table.getModel(); Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); c.setBackground(model.getRowColour(row)); return c; }}
更改行的颜色很简单:
model.setRowColour(1, Color.YELLOW);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)