Java JTable 更改单元格颜色 [英] Java JTable change cell color

查看:28
本文介绍了Java JTable 更改单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个可编辑的表格,然后检查数据以确保其有效.我不确定如何更改一个单元格的颜色.我想获取一个单元格,例如 (0,0) 并将前景着色为红色.我已经阅读了关于 SO 和 Oracle 的其他关于自定义 ColorRenderer 的帖子,但我不知道我将如何使用它.

I would like to make an editable table and then check the data to make sure its valid. Im not sure how to change the color of just one cell. I would like to get a cell, for example (0,0) and color the foreground to red. I have read the other posts on SO as well as Oracle about the custom ColorRenderer, but i just don't get how i would use this.

谢谢.

推荐答案

说你想用不同颜色渲染的单元格代表一个状态(我会以 Rejected 和 Approved 为例).然后,我将在我的表模型中实现一个名为 getStatus(int row) 的方法,该方法返回任何给定行的状态.

Say that the cell you would like to render with a different color represents a status (I'll take Rejected and Approved as examples). I'd then implement a method in my table model called getStatus(int row) which returns the status for any given row.

然后,当它到位时,我将着手创建一个单元格渲染器,负责渲染单元格所属的列.单元格渲染器将是以下代码行中的内容.

Then, when that is in place, I'd go about creating a cell renderer responsible for rendering the column which the cell belongs to. The cell renderer would be something in the lines of the below code.

public class StatusColumnCellRenderer extends DefaultTableCellRenderer {
  @Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

    //Cells are by default rendered as a JLabel.
    JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

    //Get the status for the current row.
    CustomTableModel tableModel = (CustomTableModel) table.getModel();
    if (tableModel.getStatus(row) == CustomTableModel.APPROVED) {
      l.setBackground(Color.GREEN);
    } else {
      l.setBackground(Color.RED);
    }

  //Return the JLabel which renders the cell.
  return l;

}

然后,当渲染器就位时,只需使用以下代码将渲染器应用"到表格:

Then, when the renderer is in place, simply "apply" the renderer to the table with the following piece of code:

Table.getColumnModel().getColumn(columnIndex).setCellRenderer(new StatusColumnCellRenderer());

关于使单元格可编辑,只需实现 isCellEditable(int rowIndex, int columnIndex) 表模型中的方法.您还需要实现该方法setValueAt(Object value, int rowIndex, int columnIndex) 如果您想保留用户提供的值(我假设您这样做了!).

With regard to making a cell editable, simply implement the isCellEditable(int rowIndex, int columnIndex) method in your table model. You also need to implement the method setValueAt(Object value, int rowIndex, int columnIndex) if you would like to keep the value which the user provides (which i assume you do!).

这篇关于Java JTable 更改单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆