我有一个 Jtable,其中包含一些值 [全部都是字符串]。有些值前面有“*”,我需要对其进行着色。我可以使用单元格渲染器为那些带有“*”的单元格着色。但是在给单元格着色后,我需要删除“*”而不改变单元格颜色。当我尝试编辑单元格值时,颜色变回白色。我在这里缺少什么。 这是代码
public SimpleTable()
{
JPanel panel = new JPanel();
setTitle("Colored JTable");
setBounds(400, 400, 400, 250);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
JTable table = new JTable(this.getRows(), this.getHeaders());
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setDefaultRenderer(Object.class, new MyTableRenderer());
this.scrollPane = new JScrollPane(table);
panel.add(scrollPane);
getContentPane().add(panel);
}
这是我的单元格渲染器
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(table.getValueAt(row, column).toString().contains("*"))
{
String v = table.getValueAt(row, column).toString().replace("*", "");
table.setValueAt(v, row, column);
cellComponent.setBackground(Color.YELLOW);
}
else
{
cellComponent.setBackground(Color.WHITE);
}
return cellComponent;
最佳答案
选项:
- 将 * 保留在单元格数据中,将其用作绘画标记,但不要在渲染器中渲染它。
- 使用行的单独非可视化字段(例如 boolean 值)来确定单元格是否应涂成红色。
我更喜欢后者,因为它是一种更干净、更面向对象的解决方案。请注意,您的单元格渲染器应该仅参与渲染。它永远不应该更改表所保存的数据。
第一个示例:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value != null && value.toString().contains("*")) {
value = value.toString().replace("*", "");
setBackground(Color.YELLOW);
} else {
setBackground(Color.WHITE);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
关于java - 如何在更改单元格值后渲染单元格颜色Jtable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259106/