JTable如何设置部分单元格的背景色
1、JTable是Java编程语言中用来显示和编辑常规二维单元表的工具,同时提供了这些功能的默认设置,从而可以轻松地设置简单表。
2、具体使用时,首先要导入相关的库引用,然后定义表对象,如下:
import javax.swing.JTable;
private JTable table; //定义个二维数据表格
3、设计使用 JTable 的应用程序时,务必要注意用来表示表数据的数据结构。我们假定有如下的表数据结构:
Object[] columnNames = {"编号", "名称", "类别", "数量"};
4、对于具体数据,我们定义如下Demo数据:
Object[][] rowData = {
{"1001", "肥皂", "日杂", new Double(3000)},
{"1002", "葡萄汁", "快消", new Double(3100)},
{"1003", "香米", "粮油", new Double(3000)},
{"1004", "酸奶", "快消", new Double(4000)},
{"1005", "筷子", "日杂", new Double(4000)}
};
5、使用以上数据创建表格:
dtm = new DefaultTableModel(rowData, columnNames) {
public boolean isCellEditable(int rowIndex, int columnIndex) {
boolean f = (0 <= rowIndex && rowIndex < getRowCount() && columnIndex == 0) ? false : true;
return f;
}
};
table = new JTable(dtm);
6、绘制某列的背景颜色:
//获取某一列
TableColumn tableColumn = table.getColumn("类别");
//DefaultTableCellRenderer类可以绘制单元格的背景、字体颜色等功能
DefaultTableCellRenderer backGroundColor = new DefaultTableCellRenderer();
//绘制类别列的背景为黄色
backGroundColor.setBackground(Color.yellow);
tableColumn.setCellRenderer(backGroundColor);