简体   繁体   English

在netbeans中着色jtable行

[英]Colouring jtable row in netbeans

I'm new to java. 我是java的新手。 What i am trying to do is to create a table that shows a list of objects. 我想要做的是创建一个显示对象列表的表。 What i want is to give color for specific rows in the JTable based upon the value of the member of an object. 我想要的是根据对象成员的值为JTable中的特定行赋予颜色。 I saw a lot of option like using "TableCellRender" and all.I have tried them too. 我看到很多选项,比如使用“TableCellRender”和所有。我也试过了。 But the problem is that am using the Netbeans IDE so that i am not creating the table by code. 但问题是我使用Netbeans IDE,所以我不是通过代码创建表。 Can some one please help me to change row color where the table is defined by the NetBeans?? 有人可以帮我改变NetBeans定义表格的行颜色吗?

Thanks in advance. 提前致谢。

You can use DefaultTableCellRenderer to color alternate row from JTable . 您可以使用DefaultTableCellRendererJTable备用行着色。

table.setDefaultRenderer(Object.class, new TableCellRenderer(){
    private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if(isSelected){
                    c.setBackground(Color.YELLOW);
                }else{
                if (row%2 == 0){
                    c.setBackground(Color.WHITE);

                }
                else {
                    c.setBackground(Color.LIGHT_GRAY);
                }     }

       //Add below code here
                return c;
            }

        });

If you want to color your row using the value of a particular row then you can use something like this. 如果要使用特定行的值为行着色,则可以使用类似的行。 Add these line to above 将这些行添加到上面

if(table.getColumnModel().getColumn(column).getIdentifier().equals("Status")){//Here `Status` is column name
    if(value.toString().equals("OK")){//Here `OK` is the value of row

        c.setBackground(Color.GREEN);
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM