Why does my java custom cell renderer not highlight when rows / cells are selected?

I have a custom cell renderer to wrap cells with words, so more content can be read This is the code:

import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;

import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;

public class textwrapCellRenderer extends JTextArea implements TableCellRenderer {
    private static final long serialVersionUID = 1L;

    public textwrapCellRenderer() {
        setLineWrap(true);
        setWrapStyleWord(true);
        setMargin(new Insets(0,5,5));
        setSelectionColor(Color.GREEN);
    }

    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
        setText((String)value);
        setSize(table.getColumnModel().getColumn(column).getWidth(),getPreferredSize().height);
        setSelectionColor(Color.GREEN);

        return this;
    }
}

Update: the cell renderer is used correctly, but when the user selects a row in JTable, it only shows the highlighting of non custom rendered cells Highlight all other cells for the row This leaves only one cell with a white background, while the remaining cells have blue (in my case) as the highlighted background color

Solution

You must check the isselected parameter to see if the cell is selected, similar to:

public Component getTableCellRendererComponent(JTable table,int column) 
{
        setText((String)value);
        setSize(table.getColumnModel().getColumn(column).getWidth(),getPreferredSize().height);
        setSelectionColor(Color.GREEN);

        if (isSelected)
        {
            setBackground(table.getSelectionBackground());
            setForeground(table.getSelectionForeground());
        }
        else
        {
            setBackground(table.getBackground());
            setForeground(table.getForeground());
        }
        return this;
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>