简单的问题,但我似乎无法在网上的任何地方找到答案。

如何使用自定义的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
    }
  }

我将承担改变呈现文本样式是相似的,但你怎么设置字体是一样的默认表字体,但黑体字?

有帮助吗?

解决方案

如果你已经可以得到表的默认字体(我想会c.getFont()),那么就使用的 deriveFont(Font.BOLD)

其他提示

您可能还需要考虑表行渲染方法其可以给你在控制更改为字体哪些小区一点更多的灵活性。我已经使用了加粗文本中所选择的行的所有列。

设置字体加粗与高速缓存,如已经在此描述,将工作。

在情况下,你需要设置以粗体显示的只是一部分 - 使用HTML。表的单元格渲染是基于JLabel(或者你可以返回一个)。转换你的文本到HTML将使几乎所有的文本属性变化。

我们广泛使用这种技术并没有看到任何显著的性能下降。

下面是懒人的做法:使用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);
  }
}

也可以用这个..

        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;

    }

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top