setSelectionBackGround()不为自定义渲染的单元格设置颜色

我正在使用自定义CellRenderer(TableCellRenderer的一个实例)来渲染下面描述的CLOSE列的Cells。 我为表格的setSelectionBackGround设置了一种颜色,但是所选列的bg颜色的单元格在选中时不会被绘制。 请给我任何见解,我将非常感激。

在此处输入图像描述

这是我的TablecellRenderer类

class LabelRenderer extends JLabel implements TableCellRenderer { Font f; Color selectionBG; Color upDirection; LabelRenderer(){ super(); f=new java.awt.Font("Trebuchet MS", 0, 12); selectionBG = new java.awt.Color(204, 255, 255); upDirection= new Color(0,102,0); } @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { //structure of passing array (value) // new Object[]{boolean direction, String close (change%)} Object arr[] = (Object[])value; Boolean direction = (Boolean)arr[0]; if( direction ) this.setForeground(upDirection);//GREEN else this.setForeground(Color.red); this.setText(arr[1].toString()); this.setFont(f); return this; } 

}

您的渲染器扩展了JLabel ,默认情况下它不是不透明的。 您可以在渲染器中执行setOpaque(true) 。 或者,您可以扩展DefaultTableCellRenderer ,默认情况下它是不透明的。 例如:

在此处输入图像描述

 import java.awt.Color; import java.awt.Component; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class TableBgDemo { private static void createAndShowGUI() { JFrame frame = new JFrame("TableDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Object[][] rows = { { "Column 1", "Column 2" }, { "Column 1", "Column 2" }, { "Column 1", "Column 2" }, { "Column 1", "Column 2" } }; Object[] columns = { "Column 1", "Column 2" }; DefaultTableModel model = new DefaultTableModel(rows, columns); JTable table = new JTable(model); table.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer()); table.setSelectionBackground(Color.CYAN); frame.add(new JScrollPane(table)); frame.pack(); frame.setVisible(true); } static public class MyRenderer extends DefaultTableCellRenderer { @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); c.setForeground(Color.RED); return c; } } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } 

我正在使用自定义CellRenderer(TableCellRenderer的一个实例)来渲染下面描述的CLOSE列的Cells。 我为表格的setSelectionBackGround设置了颜色,但是所选列的bg颜色的单元格在选中时不会被绘制。 请给我任何见解,我将非常感激。

问题是由两个错误引起的

  1. 你的渲染器,不要使用这个代码,这里有一些优秀的代码,(我将使用prepareRenderer for RowRenderer)

  2. 永远不要设置,修改,添加来自Model的值,意思是代码行this.setText(arr[1].toString()); ,Renderer是关于荧光笔,装饰者