多个以不同方式着色到JTable的同一单元格中的字符串 [英] Multiple Strings colored in different way into the same cell of a JTable

查看:64
本文介绍了多个以不同方式着色到JTable的同一单元格中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个JTable,并且要为每个单元格显示三个颜色不同的字符串,例如value1(红色),value2(蓝色),value3(绿色).

Suppose you have a JTable and for each cell you want to display three strings with different color, say value1 (red), value2 (blue), value3 (green).

我覆盖了DefaultTableCellRenderergetTableCellRendererComponent,但是setForeground(Color)方法为单元格中显示的所有字符串提供了唯一的颜色.

I overrode the getTableCellRendererComponent of DefaultTableCellRenderer but setForeground(Color) method gives an unique color for all the string showed in the cell.

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    String s = table.getModel().getValueAt(row,column).toString();

    StringTokenizer st = new StringTokenizer(s," ");
    int nToken=st.countTokens();

    value1=st.nextToken();
    value2=st.nextToken();
    value3=st.nextToken();
    // so now all the values are blue...
    setForeground(Color.blue);

    return super.getTableCellRendererComponent(table, value, isSelected,
            hasFocus, row, column);

}

推荐答案

单元格表的默认渲染器是JLabel.该组件支持HTML标记.您可以使用的最简单的解决方案是使用HTML渲染具有不同颜色的字符串.因此,您可以构建一个字符串,例如:

The default renderer for a cell table is a JLabel. This component supports HTML tags. The easiest solution you can have is to use HTML to render the Strings with different colours. So you can build a String such as:

 <html><font color="blue">A String</font><font color="red">Another String</font></html>

并将其设置为单元格,您不必担心渲染器.

And set it to the cell, and you don't have to worry about the renderer.

大多数swing组件都允许您使用HTML,这是不仅限于表格.

另一种可能性是,您创建一个从JComponent扩展的类,并对paintComponent()进行编程,以使其以不同的颜色绘制这三个字符串.然后,您可以将此组件设置为渲染器.但这要复杂得多.由于渲染器的工作方式类似于邮票",因此在绘制单元格时它将标记正确的颜色.如果您需要在单元格上绘制极其复杂和自定义的图形,这将很有用.

Another possibility is that you create a class that extends from JComponent, and program paintComponent() so it draws these three strings in different colors. Then you can set this component as the renderer. But this is way more complicated. Because the renderer works like a "stamp", it will stamp the right colors when the cells are drawn. This is useful if your needs are to, for example, draw extremely complex and custom graphics on a cell.

如果您没有大量的单元格,我会坚持使用HTML.

I would stick with using HTML if you don't have a humongous amount of cells.

这篇关于多个以不同方式着色到JTable的同一单元格中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆