当我点击一个单元格时,我试图让我的表格选择整行(可以通过关闭列选择来完成),但是,我不想要特定单元格周围的超厚边框点击突出显示。我希望这很容易,但显然它涉及渲染器,所以我做了很多研究,我能得到的最接近的是:
JTable contactTable = new JTable(tableModel);
contactTable.setCellSelectionEnabled(true);
contactTable.setColumnSelectionAllowed(false);
contactTable.setRowSelectionAllowed(false);
contactTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// This renderer extends a component. It is used each time a
// cell must be displayed.
class MyTableCellRenderer extends JLabel implements TableCellRenderer {
// This method is called each time a cell in a column
// using this renderer needs to be rendered.
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
// 'value' is value contained in the cell located at
// (rowIndex, vColIndex)
if (isSelected) {
// cell (and perhaps other cells) are selected
}
if (hasFocus) {
// this cell is the anchor and the table has the focus
this.setBackground(Color.blue);
this.setForeground(Color.green);
} else {
this.setForeground(Color.black);
}
// Configure the component with the specified value
setText(value.toString());
// Set tool tip if desired
// setToolTipText((String)value);
// Since the renderer is a component, return itself
return this;
}
// The following methods override the defaults for performance reasons
public void validate() {}
public void revalidate() {}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
}
int vColIndex = 0;
TableColumn col = contactTable.getColumnModel().getColumn(vColIndex);
col.setCellRenderer(new MyTableCellRenderer());
我从示例中复制了渲染器,只更改了hasFocus()函数以使用我想要的颜色。在isSelected()
中设置颜色没有做任何事情。
此代码的问题是:
它只适用于底部的vColIndex指定的一列。显然,我希望将其应用于所有列,因此单击一个单元格会突出显示整行。我可以创建一个for循环来将其更改为每个单元格,但我认为这是一种更好的方法,可以立即更改所有列的cellRenderer。
setForegroundColor()
可以更改文字,但setBackgroundColor()
对细胞背景不做任何操作。我希望它能像实际所暗示的那样改变背景颜色。
this.setOpaque(true);
。当渲染器工作时,它只适用于单个Cell。如何让它为行中的所有单元格着色?
hasFocus()
),则不要使用仅影响单个单元格的table.setRowSelectionAllowed(true)
,而是将颜色更改为if(isSelected)
语句。然后整行被认为是选中的,它为所有单元格着色!3是最重要的一个,但如果有人知道#1或者可以向我解释为什么它的设计使得你一次只能将渲染器应用于一个列,我将非常感激。
答案 0 :(得分:14)
过于直接只需添加行
tablename.setSelectionBackground(Color.red);
在我的情况下
jtbillItems.setSelectionBackground(Color.red);
答案 1 :(得分:5)
教程文章Concepts: Editors and Renderers解释说“单个单元格渲染器通常用于绘制包含相同类型数据的所有单元格”,由模型的{{返回1}}方法。
或者,覆盖为{em>所有单元格调用的getColumnClass()
,以选择性地更改行的外观。这个example比较了这两种方法,文章Table Row Rendering扩展了该方法的多功能性。
答案 2 :(得分:0)
对于第二个问题,您可以尝试使用setSelectionBackground(Color)和setSelectionForeGround(Color)方法。我不确定你怎么能解决第一个问题。最后一个建议你可以使用一些摇摆设计插件,如JBuilder。这会有很多帮助。