单击按钮后如何更改JTable单元的颜色?

时间:2015-10-22 16:29:26

标签: java swing jtable tablecellrenderer

此代码创建一个表格,其单元格为ImageIcon.class。通过单击我想要的按钮可以更改相应单元格中ImageIcon的颜色。如果我删除“c instanceof Icon”,代码会设置整个单元格的背景。否则,颜色根本不会改变。我想准确更改渲染器中指定的16x16图标的颜色。

public class Test {

public static void main(String[] args) 
{
    EventQueue.invokeLater(new Runnable() {

    @Override
    public void run() {
        JFrame f = new JFrame("CheckTable");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTable tableCabin = new JTable(new CabinTableModel(nrows,ncols));

        TableCellRenderer defaultRenderer = tableCabin.getDefaultRenderer(ImageIcon.class);

        tableCabin.setDefaultRenderer(ImageIcon.class, new CabinColumnRenderer(defaultRenderer)
        {
             @Override
             public Component getTableCellRendererComponent(JTable table,
                   Object value, boolean isSelected, boolean hasFocus, int row,
                   int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                                                                            row, column);
                if (c instanceof Icon)
                {  
                    if (row == selectedRow && column == 1)
                    {
                        c.setForeground(Color.black);
                        c.setBackground(Color.red);
                    }
                    else 
                    {
                        c.setForeground(Color.black);
                        c.setBackground(null);
                    }
                }
                return c;
             }
            });

            JTextField textfield = new JTextField(10);
            textfield.setText("5");

            JButton but = new JButton("Set");
            but.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                selectedRow = Integer.parseInt(textfield.getText().toString());
                table.repaint();
            }
            });

            f.add(table);
            f.add(textfield);
            f.add(but);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            }
        });
    }
}


import java.awt.Color;
import java.awt.Component;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class CabinColumnRenderer implements TableCellRenderer
{
    private TableCellRenderer delegate;

    public CabinColumnRenderer(TableCellRenderer defaultRenderer)
    {
        this.delegate = defaultRenderer;
    }

    public Component getTableCellRendererComponent(JTable table, Object value, 
                               boolean isSelected, boolean hasFocus, int row, int column) 
    {
        Component c = delegate.getTableCellRendererComponent(table, value, isSelected, 
                                                                    hasFocus, row, column);
        if (c instanceof Icon)
        {  
          c.setBackground(Color.red);
        }  
        return c;
    }
}



import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.table.AbstractTableModel;

@SuppressWarnings("serial")
public class CabinTableModel extends AbstractTableModel
{
  private String columnNames[];
  private Class<?>[] columns;
  private int rows;
  private int cols;
  private ArrayList<Object[]> data;

  public CabinTableModel(int rows, int cols)
  {
    this.rows = rows;
    this.cols = cols;
    columnNames = new String[cols];
    columns = new Class<?>[cols];
    for (int i=0; i<cols; i++)
    {
        columns[i] = ImageIcon.class;
        columnNames[i] = "A"+i;
    }
    this.data = new ArrayList<Object[]>();
    for (int i = 0; i < rows; i++)
    {
      Object[] row = new Object[this.cols];
      this.data.add(row);
      for (int j=1; j<cols; j++)
          row[j] = createIcon();
    }
  }

  private Icon createIcon()
  {
    return new Icon()
    {
      private Color color = Color.green;

      public int getIconHeight()
      {
        return 16;
      }

      public int getIconWidth()
      {
        return 16;
      }

      public void paintIcon(Component c, Graphics g, int x, int y)
      {
        g.setColor(color);
        g.fillRect(x, y, getIconWidth(), getIconHeight());
      }
    };
  }

  @Override
  public Class<?> getColumnClass(int columnIndex)
  {
    return this.columns[columnIndex];
  }

  public int getColumnCount()
  {
    return cols;
  }

  public int getRowCount()
  {
    return rows;
  }

  public Object getValueAt(int row, int col)
  {
    return data.get(row)[col];
  }

  @Override
  public String getColumnName(int col) 
  {
    return columnNames[col];
  }

  @Override
  public boolean isCellEditable(int rowIndex, int columnIndex)
  {
    return false;
  }

  @Override
  public void setValueAt(Object value, int row, int col)
  {
    data.get(row)[col] = value;
    fireTableCellUpdated(row, col);
  }

  public void deleteRows(int startIndex, int count)
  {
    int index = startIndex + count - 1;
    while (index >= startIndex)
    {
      data.remove(index);
      index--;
    }
    fireTableRowsDeleted(startIndex, startIndex + count - 1);
  }
}

0 个答案:

没有答案