我创建了以下TableCellRenderer
来设置JTable
中特定单元格的颜色。问题是它设置了整个列的颜色。如何定义行?
package run;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class test4 {
/**
* @param args
*/
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
gtest t = new gtest("");
t.pack();
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setLocationRelativeTo(null);
}
}
class gtest extends JFrame
{
private static JTable table;
private int index;
public gtest(String title)
{
Object cols[] = {"A","B"};
double data[][] = {{2,10},{5,20},{20,11}};
table = new JTable(3,2);
for (int i = 0; i< data.length; i++)
{
for (int j=1; j<cols.length; i++)
{
double val = data[i][j] + 5*data[i][j]-1;
table.getColumnModel().getColumn(j).setCellRenderer(new ColorRenderer());
// here I want to put a Thread.sleep or something similar to
// visualize the filling out of a table
}
}
add(table);
}
}
class ColorRenderer extends JLabel implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
public ColorRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
setText(value.toString());
setFont(new Font("SansSerif", Font.PLAIN, 10));
setBackground(Color.lightGray);
return this;
}
}
答案 0 :(得分:3)
TableCellRenderer
设置为整列,只更改一些行,需要在getTableCellRendererComponent()
方法中实现行号验证。
例如rowIndex = 1的chage颜色:
setBackground(row == 1 ? Color.lightGray : table.getBackground());
阅读TableCellRenderer
的文档。