我试图让我的表格在您单击一个单元格时选择整行(这可以通过关闭列选择来完成),但是,我不希望您单击的特定单元格周围有额外的粗边框被突出显示。我希望这会很容易,但显然它涉及渲染器,所以我做了很多研究,我能得到的最接近的是:
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()
对单元格背景没有任何作用。我希望它像属性暗示的那样实际更改背景颜色。- #2 的解决方案:在分配背景色之前使用
this.setOpaque(true);
。
- #2 的解决方案:在分配背景色之前使用
当渲染器工作时,它只在单个 Cell 上工作。我怎样才能让它为行中的所有单元格着色?
- #3 的解决方案:我想通了!如果您启用行选择 (
table.setRowSelectionAllowed(true)
),而不是使用仅影响单个单元格的hasFocus()
,那么您可以将颜色更改放在if(isSelected)
语句。然后整行被认为是选中的,并且它为所有单元格着色!
- #3 的解决方案:我想通了!如果您启用行选择 (
3 是大问题,但如果有人知道 #1 或者可以向我解释为什么它被设计成一次只能将渲染器应用于一列,我们将不胜感激。
最佳答案
太直接了就加行
tablename.setSelectionBackground(Color.red);
以我为例
jtbillItems.setSelectionBackground(Color.red);
关于Java - Swing - JTable - 为选定行设置颜色,但不为单元格设置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10017517/