JTable CustomRenderer Issue

♀尐吖头ヾ 提交于 2019-12-24 11:10:51

问题


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));          

         }

What I am doing wrong ?


回答1:


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.

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());
    }

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.



来源:https://stackoverflow.com/questions/13631535/jtable-customrenderer-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!