1

全部 - 我正在尝试在单击特定单元格并成功操作后设置它的背景颜色。我好像做不到。这是代码:

JTable table = new JTable(new DefaultTableModel());
String [] colNames = {"col1", "col2", "ClickMe"};
for (String name : colNames)
  table.addColumn(name);

.... some code .....

String [] someArray = {"t", "t2", "t3"};

....
for (int i=0; i<someArray.length;i++) {
  Object [] row = new Object[3];
  row[0] = "bla";
  row[1] = "bla";
  row[2] = "Update";
  ((DefaultTableModel)table.getModel()).addRow(row);
  ((DefaultTableCellRenderer)gameTable.getCellRenderer(i, 2)).setBackground(Color.LIGHT_GRAY);
  ((DefaultTableCellRenderer)gameTable.getCellRenderer(i, 2)).setHorizontalAlignment(JLabel.CENTER);
}

table.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
  int row = gameTable.rowAtPoint(e.getPoint());
  int col = gameTable.columnAtPoint(e.getPoint());
  if (col == 2) {
  Color cellColor = ((DefaultTableCellRenderer)gameTable.getCellRenderer(row,col)).getBackground();
  if (cellColor == Color.LIGHT_GREY) {
    String val1 = (String)table.getModel().getValueAt(row,1);
    String val2 = (String)table.getModel().getValueAt(row,0);
    if (doSomething(val1, val2)) {  //this returns either true or false, its a Database operations
      ((DefaultTableCellRenderer)table.getCellRenderer(row, 2)).setBackground(Color.BLUE);
      }
   }
 }
};

即使我在行和列上具体调用 setBackground,它也会使“2”列中每一行中的每个单元格都更改背景颜色,而不仅仅是一个特定的颜色。

customRenderers 的所有示例似乎只是根据单击它的时间来更改颜色,只是将其更改为其他颜色,我还需要进行一些处理。

这里有什么想法吗?

谢谢-

4

1 回答 1

1
Try this


table.setDefaultRenderer(Object.class, new TableCellRenderer(){
            private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();
            private Component comp;

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if(isSelected){

                    c.setBackground(Color.YELLOW);
                }else{
                if (row%2 == 0){
                if (column==2){
                    c.setBackground(Color.WHITE);

                }
                else {
                    c.setBackground(Color.LIGHT_GRAY);
                } }    }

                return c;
            }

        });
于 2013-12-23T06:20:52.210 回答