swing设置字体颜色的一个问题

在系统中需要设置,表格中数据符合某中情况的行字体为绿色,使用覆盖DefaultTableCellRenderer中的方法去实现,发现父容器组件的焦点改变时可能导致颜色混乱,原因未知,必须重新加上对当行背景色,字体颜色的重新按照默认方式的手动设置的代码在前面才可解决,如下红色代码。

 private void setTbAbnormalColor(JTable tb) {
        int count = tb.getColumnModel().getColumnCount();
        for (int i = 1; i < count; i++) {
            tb.getColumnModel().getColumn(i).setCellRenderer(
                    new DefaultTableCellRenderer() {
                        public Component getTableCellRendererComponent(
                                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                            super.getTableCellRendererComponent(table, value,
                                    isSelected, hasFocus, row, column);
                            if (row == table.getSelectedRow()) {
                                setForeground(table.getSelectionForeground());
                                setBackground(table.getSelectionBackground());
                            } else {
                                setForeground(table.getForeground());
                                setBackground(table.getBackground());
                            }
                            Merger curRow = (Merger) ((JTableListModel) table.getModel()).getDataByRow(row);
                            boolean isHandNoNull = curRow.getGoods().getHandBookNO() == null
                                    || curRow.getGoods().getHandBookNO().trim().length() == 0;
                            boolean isGoodsBackNoNull = curRow.getGoods().getGoodsBackNO() == null;
                            if (isHandNoNull && isGoodsBackNoNull) {
                                setForeground(Color.green);
                            }
                            return this;
                        }
                    });
        }
    }

你可能感兴趣的:(btpls)