JTable CustomRenderer 问题 [英] JTable CustomRenderer Issue

查看:33
本文介绍了JTable CustomRenderer 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 Jtable.这个表由两列名称和时间戳组成.如果名称是jane",我想将行的颜色设为黄色.以下是代码:-

I have created one Jtable.This table consist of two columns name and timestamp. I want to make color of row yellow if name is "jane". Following is the code for that :-

    class CustomRenderer extends DefaultTableCellRenderer {

    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);
        String name = table.getModel().getValueAt(row, 0).toString();

        if (name.trim().equals("jane")) {
            c.setBackground(Color.YELLOW);
        }
        return c;
    }
}

但是,不是将特定名称的行颜色更改为黄色,而是更改每一行的颜色.我将表的数据设置如下

However instead of changing color of row to yellow for particular name, it is changing color of every row.I am setting data of table as following

tableModelName = (DefaultTableModel)jTableName.getModel();

jTableName.setDefaultRenderer(Object.class,new CustomRenderer());

for(int i=0; i<records.size(); i++)
         {
            tableModelName.addRow(records.get(i));          

         }

我做错了什么?

推荐答案

如果名称不是jane",您需要一个 else 子句将背景颜色设置为黄色以外的颜色.单个渲染器实例用于所有渲染,因此一旦您在该实例上将颜色设置为黄色,它就会保持黄色.

You need an else clause to set the background color to something besides yellow if the name is not "jane". A single renderer instance is used for all rendering, so once you set the color to yellow on that instance, it stays yellow.

查看 JTable 源代码以了解内置渲染器的工作原理:

Take a look at the JTable source code to see how the built-in renderers work:

    if (isSelected) {
        setForeground(table.getSelectionForeground());
        super.setBackground(table.getSelectionBackground());
    }
    else {
        setForeground(table.getForeground());
        setBackground(table.getBackground());
    }

为了更简单的方法,您可以尝试子类化 JTable 并覆盖 准备渲染器.这对于像这样影响整个行的更改非常方便,因此您可以为单个单元格使用自定义渲染器,并在 prepareRenderer 方法中调整一行的所有渲染器.

For an easier way of doing this, you might try subclassing JTable and overriding prepareRenderer. This is handy for changes that affect entire rows like this, so you can use custom renderers for the individual cells, and tweak all renderers for a row in the prepareRenderer method.

这篇关于JTable CustomRenderer 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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