Dan*_*iel 8 java swing jtable colors cell
我试图让我的表在单击一个单元格时选择整行(这可以通过关闭列选择来完成),但是,我不希望您单击的特定单元格周围的额外粗边框突出显示.我希望这很容易,但显然它涉及渲染器所以我做了很多研究,我能得到的最接近的是:
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());
Run Code Online (Sandbox Code Playgroud)
我从示例中复制了渲染器,只更改了hasFocus()函数以使用我想要的颜色.设置颜色isSelected()没有做任何事情.
这段代码的问题是:
它仅适用于底部的vColIndex指定的一列.显然,我希望将其应用于所有列,因此单击一个单元格会突出显示整行.我可以创建一个for循环来将其更改为每个单元格,但我认为这是一种更好的方法,可以立即更改所有列的cellRenderer.
setForegroundColor()用于更改文本但setBackgroundColor()不对单元格背景执行任何操作.我希望它实际上改变了属性所暗示的背景颜色.
this.setOpaque(true);在分配backgroundcolor之前使用.当渲染器工作时,它只适用于单个Cell.如何让它为行中的所有单元格着色?
hasFocus()如果启用行选择(table.setRowSelectionAllowed(true)),则不使用仅影响单个单元格,而是将颜色更改为if(isSelected)语句.然后整行被认为是选中的,它会为所有细胞着色!3是最重要的,但如果有人知道#1或者可以向我解释为什么它的设计使得你一次只能将渲染器应用于一列,我将不胜感激.
小智 14
太直接只是添加线
tablename.setSelectionBackground(Color.red);
Run Code Online (Sandbox Code Playgroud)
在我的情况下
jtbillItems.setSelectionBackground(Color.red);
Run Code Online (Sandbox Code Playgroud)
教程文章Concepts:Editors and Renderers解释说"单个单元格渲染器通常用于绘制包含相同类型数据的所有单元格",如模型getColumnClass()方法返回的那样.
或者,覆盖prepareRenderer()(为所有单元格调用),以选择性地更改行的外观.此示例比较了这两种方法,文章表格行渲染扩展了该方法的多功能性.
| 归档时间: |
|
| 查看次数: |
30955 次 |
| 最近记录: |