JTable、JList 等中的单元格渲染器使用就像一个邮票(有关详细信息,请参阅Editors and Renderers)。
这意味着通常,相同(相同)JComponent 用于绘制所有单元格。该组件仅在用于绘制单元格之前填充适当的内容。而当背景设置为RED时,它会一直保持红色,直到设置为不同的颜色。
我不确定你想通过使用这个DEFAULT_RENDERER 实例来实现什么。您可以简单地从DefaultTableCellRenderer 继承并直接返回组件(实际上是渲染器本身)。但是,无论如何,您都必须包含一些代码,以确保为每次调用设置适当的颜色,大致类似于
....
if (shouldBeRed(row, column)) {
c.setBackground(Color.RED);
} else {
c.setBackground(notRed);
}
return c;
(请注意,如果您扩展DefaultTableCellRenderer,这实际上可以隐藏在对super 方法的调用中,但此处的详细信息取决于您是否会保留此DEFAULT_RENDERER 实例...)
您可能还对this example of blinking table cells 感兴趣,它展示了如何根据特定标准为多个表格单元格分配不同的颜色。
编辑:一个例子。虽然我通常会尽量避免用这样的例子来回答这样的问题,因为即使是最轻微的修改,你也会问另一个问题,在这种情况下可能会在
行
- 如何取消突出显示该行
- 如何突出显示多行
- 如何用不同的颜色突出显示多行
- ...
您可以在 https://stackoverflow.com/a/24556135/3182664 中找到所有这些问题的答案 - 同时,我会将这个问题标记为重复。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
public class TableRowColor
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("TableRowColor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
final JTable table = createTable();
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JButton changeColorButton = new JButton("Change color");
changeColorButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
changeColor(table, 1);
}
});
frame.getContentPane().add(changeColorButton, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JTable createTable()
{
String[] columnNames = { "First Name", "Last Name", "Sport", };
Object[][] data = { { "Kathy", "Smith", "Snowboarding" },
{ "John", "Doe", "Rowing" }, { "Sue", "Black", "Knitting" },
{ "Jane", "White", "Speed reading" }, { "Joe", "Brown", "Pool" } };
return new JTable(data, columnNames);
}
public static void changeColor(JTable table, final int coloredRow)
{
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column)
{
super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
if (row == coloredRow)
{
setBackground(Color.RED);
}
else
{
setBackground(null);
}
return this;
}
});
table.repaint();
}
}