[英]How to change the background color of specific JTable cells depending on their value?
如果第一列中的单元格的值等于Kathy或Jane的颜色,如何将背景色变为红色。
在我的解决方案中,第一列中的每个单元格都涂成红色,但是如果我将其他单元格涂成绿色,则一切正常。 但是我想让它们的背景默认,因为我只想标记特定的单元格。
package com.myswingtest;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
public class SimpleTableDemo extends JPanel {
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name","Last Name"};
Object[][] data = {
{"Kathy", "Black",},
{"John", "Doe",},
{"Jane", "Smith",},
{"Rob", "White",},
{"Joe", "Smith",}
};
final JTable table = new JTable(data, columnNames);
DefaultTableCellRenderer statusCellRenderer = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
int modelRow = table.convertRowIndexToModel(row);
TableModel tableModel = table.getModel();
// Lets color only the cells in the first column what equals Kathy or Jane
if("Kathy".equals(tableModel.getValueAt(modelRow, 0))
|| "Jane".equals(tableModel.getValueAt(modelRow, 0))){
System.out.println("SETTING COLOR TO RED IN ROW: " + modelRow);
l.setBackground(Color.RED);
} else {
// If I uncomment this line, the other lines became green. But I want their background stay default.
//l.setBackground(Color.GREEN);
}
return l;
}
};
// Setting cellrenderer for first column
table.getColumnModel().getColumn(0).setCellRenderer(statusCellRenderer);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new SimpleTableDemo());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.