我试图让我的表格在您单击单元格时选择整行(可以通过关闭列选择来完成),但是,我不希望您单击的特定单元格周围的超厚边框突出显示。我希望这很容易,但显然它涉及渲染器,所以我做了很多研究,我能得到的最接近的是:
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);
在分配背景颜色之前。
-
当渲染器工作时,它仅在单个 Cell 上工作。如何让它为行中的所有单元格着色?
- #3 的解决方案:我想出来了!而不是使用
hasFocus()
,如果启用行选择(table.setRowSelectionAllowed(true)
)然后你把颜色改变放在if(isSelected)
陈述。然后整行被认为被选中,并且它为所有单元格着色!
3 是最重要的,但如果有人知道#1 或者可以向我解释为什么它被设计成一次只能将渲染器应用到一列,我将不胜感激。
太直接了,只需添加一行
tablename.setSelectionBackground(Color.red);
就我而言
jtbillItems.setSelectionBackground(Color.red);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)