Java 根据列值更改 JTable 行的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24848314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:12:04  来源:igfitidea点击:

Change background color of JTable row based on column value

javaswingjtabletablecellrenderer

提问by Lileth Hernandez

hi i am new in java jtable cellrendered. I am looking for a way that works in my program but i dont have any luck finding it. Here is my Jtable

嗨,我是 Java jtable cellrendered 的新手。我正在寻找一种适用于我的程序的方法,但我没有找到它。这是我的 Jtable

Employee ID   |   Name     |   Status    |   Position
  00565651        Roger       Active        Manager
  00565652        Gina        Active        Crew
  00565652        Alex        Inactive      Crew
  00565652        Seph        Active        Manager    

the data came from ms access database but i want to change the background/foreground of the rows which has a value of "inactive" in status column. I found many examples in the internet but all of it is not possible in my program. Can someone help me? This is my model

数据来自 ms access 数据库,但我想更改状态列中具有“非活动”值的行的背景/前景。我在互联网上找到了很多例子,但在我的程序中所有这些都是不可能的。有人能帮我吗?这是我的模型

String[] columnNames = {"Employee ID","Name", "Status", "Position"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);

and this is the way to create my table and how i am fetching data from database

这是创建我的表的方式以及我如何从数据库中获取数据

public MyList(){//my constructor
    frame();
    loadListFromDB();
}
public void frame(){//
   //codes for frame setsize,titles etc...
   tblList = new JTable();
   tblList.getTableHeader().setPreferredSize(new Dimension(100, 40));
   tblList.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 25));
   tblList.setAutoCreateRowSorter(true);
   tblList.setModel(model);
   scrollPane.setViewportView(tblList);
   loadListFromDB();

}
public void loadListFromDB(){
   String sql = "SELECT emp_id,lname,fname,positional_status from tblEmployee";
    try{
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            Vector row = new Vector();
            for (int i = 1; i <= 4; i++){
                row.addElement( rs.getObject(i) );
            }
            model.addRow(row);
        }
    }catch(Exception err){
        //for error code
    }
}

How am i suppose to add the tableredered in this way?Can anyone give simple example to change the color of row? Thanks in advance.. My program stop in this problem.

我应该如何以这种方式添加 tableredered?谁能举一个简单的例子来改变行的颜色?提前致谢.. 我的程序停止在这个问题上。

回答by Paul Samsotha

"i want to change the background/foreground of the rows which has a value of "inactive" in status column"

“我想更改状态列中具有“非活动”值的行的背景/前景”

It's really just a matter of getting the value from table/model. if the status for that row is inactive, then set the background/foreground for every every cell in that row. Since the renderer is rendered for every cell, then basically you need to get the value of the [row][statusColumn], and that will be the status value for each row. Something like

这实际上只是从表/模型中获取值的问题。如果该行的状态为非活动状态,则为该行中的每个单元格设置背景/前景。由于渲染器是为每个单元格渲染的,所以基本上你需要获取 的值[row][statusColumn],这将是每一行的状态值。就像是

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){
    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row, int col) {

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

        String status = (String)table.getModel().getValueAt(row, STATUS_COL);
        if ("active".equals(status)) {
            setBackground(Color.BLACK);
            setForeground(Color.WHITE);
        } else {
            setBackground(table.getBackground());
            setForeground(table.getForeground());
        }       
        return this;
    }   
});

Here's a simple example

这是一个简单的例子

enter image description here

在此处输入图片说明

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TableRowDemo {

    private static final int STATUS_COL = 1;

    private static JTable getTable() {
        final String[] cols = {"col 1", "status", "col 3"};
        final String[][] data = {
                {"data", "active", "data"},
                {"data", "inactive", "data"},
                {"data", "inactive", "data"},
                {"data", "active", "data"}
        };
        DefaultTableModel model = new DefaultTableModel(data, cols);
        return new JTable(model) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(350, 150);
            }
        };
    }

    private static JTable getNewRenderedTable(final JTable table) {
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                String status = (String)table.getModel().getValueAt(row, STATUS_COL);
                if ("active".equals(status)) {
                    setBackground(Color.BLACK);
                    setForeground(Color.WHITE);
                } else {
                    setBackground(table.getBackground());
                    setForeground(table.getForeground());
                }       
                return this;
            }   
        });
        return table;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
            }
        });
    }
}

Another option is to @Override prepareRendererof the table. It will give you the same result.

另一种选择是@OverrideprepareRenderer的表。它会给你同样的结果。

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class TableRowDemo {

    private static final int STATUS_COL = 1;

    private static JTable getTable() {
        final String[] cols = {"col 1", "status", "col 3"};
        final String[][] data = {
                {"data", "active", "data"},
                {"data", "inactive", "data"},
                {"data", "inactive", "data"},
                {"data", "active", "data"}
        };
        DefaultTableModel model = new DefaultTableModel(data, cols);
        return new JTable(model) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(350, 150);
            }
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
                Component c = super.prepareRenderer(renderer, row, col);
                String status = (String)getValueAt(row, STATUS_COL);
                if ("active".equals(status)) {
                    c.setBackground(Color.BLACK);
                    c.setForeground(Color.WHITE);
                } else {
                    c.setBackground(super.getBackground());
                    c.setForeground(super.getForeground());
                }
                return c;
            }
        };
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JOptionPane.showMessageDialog(null, new JScrollPane(getTable()));
            }
        });
    }
}