简单的问题,但我似乎无法在网上找到答案。
如何使用自定义TableCellRenderer以粗体显示某些表格单元格?
我知道如何使用TableCellRenderer逐个单元地设置背景颜色。你做了类似的事情:
public class MyTableCellRenderer extends DefaultTableCellRenderer
{
@Override public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
// modify the component "c" to have whatever attributes you like
// for this particular cell
}
}
我会假设更改渲染文本样式是类似的,但是如何将字体设置为与默认表格字体相同但以粗体显示?
答案 0 :(得分:5)
如果您已经可以获得默认表格字体(我认为它是c.getFont()
),那么只需使用deriveFont(Font.BOLD)
。
答案 1 :(得分:5)
您可能还需要考虑Table Row Rendering Approach,它可以让您更灵活地控制更改字体的单元格。我用它来粗体化所选行的所有列中的文本。
答案 2 :(得分:1)
如此处所述,通过缓存将字体设置为粗体将起作用。
如果您只需要设置粗体文本的一部分 - 请使用HTML。表格单元格渲染器基于JLabel
(或者您可以返回一个)。将文本转换为html几乎可以更改任何文本属性。
我们广泛使用这种技术,并没有发现任何显着的性能下降。
答案 3 :(得分:1)
这是懒人的方法:使用DefaultTableCellRenderer
(JLabel
的子类)并使用HTML指定何时使用粗体字。
它不像定义自己的自定义渲染器和直接控制字体那样高效,但代码通常更紧凑,因此适用于简单的应用程序。
/**
* Renderer implementation for rendering Strings.
* Strings beginning with 'A' are rendered in bold.
*/
public class MyRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
String txt = String.valueOf(value);
if (txt != null && txt.startsWith("A")) {
// Reassign value as an HTML string.
// Obviously need to consider replacing HTML special characters
// if doing this properly.
value = String.format("<body><b>%s</b></body>", txt);
}
// Delegate to superclass which will set the label text, background, etc.
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
答案 4 :(得分:0)
你也可以使用它..
class SampleRenderer extends DefaultTableCellRenderer
{
public Component getJtableCellRendererComponent(Jtable table,Object value,boolean isSelected , boolean hasFocus , int row, int column)
{
JLabel c = (JLabel)super.getJtableCellRendererComponent(table,value,isSelected ,hasFocus , row, column);
Font f = c.getFont();
c.setFont(f.getName(),Font.BOLD,f.getSize()));
return c;
}
}