为什么我的Java自定义单元格渲染器在选择行/单元格时不显示高亮显示? [英] Why does my Java custom cell renderer not show highlighting when the row/cell is selected?
问题描述
我有一个自定义单元格渲染器,用于单元格进行自动换行,以便可以读取更多内容。以下是代码:
I have a custom cell renderer for a cell to do a word wrap so more content can be read. Here 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, 0, 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;
}
}
更新:单元格正确使用渲染器但是当用户在JTable中选择一行时,它仅显示非自定义渲染单元格的突出显示。突出显示该行的所有其他单元格。这只留下一个带有白色背景的单元格,而行的其余部分则为蓝色(在我的情况下)作为突出显示的背景颜色。
Update: The cell renderer is used properly but when the user selects a row in the JTable, then it only shows the highlighting for the non-custom rendered cells. The highlighting shows for all other cells for that row though. This leaves just one cell with a white background while the rest of the row has blue (in my case) as the highlighted background color.
推荐答案
您必须检查 isSelected
参数以查看是否选择了单元格,例如:
You have to check the isSelected
argument to see if the cell is selected or not, something like:
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);
if (isSelected)
{
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
else
{
setBackground(table.getBackground());
setForeground(table.getForeground());
}
return this;
}
这篇关于为什么我的Java自定义单元格渲染器在选择行/单元格时不显示高亮显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!