动态更改JTable单元格的背景颜色

时间:2017-01-24 12:46:24

标签: java swing

我想更改JTable的单元格背景颜色,并希望从MySQL数据库中获取数据。

我在MySQL中使用了一个具有状态字段的数据表。如果状态为1,则单元格背景颜色应为红色,如果状态为0,则应更改为红色。

3 个答案:

答案 0 :(得分:1)

id建议使用自定义单元格渲染器来实现您想要的效果。

public class CellRenderer extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 1L;

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        if (column == /*your column number goes here*/) {
            this.setValue(table.getValueAt(row, column));
            this.setBackground(Color.RED);
        }
        return this;
    }
}

在设置颜色之前,可以检查值是0还是1,然后根据需要更改颜色

我如何使用数据库中的数据创建和填充/重新填充JTable:

表:

private void createTable(Container pane) {
    Object[] namen = { "Datum", "Kategorie", "Essen", "Preise Intern", "Preise Extern" };
    model = new DefaultTableModel(namen, 0);
    table = new JTable(model) {

        public boolean isCellEditable(int x, int y) {
            return false;
        }
    };
    Dimension minimumSize = new Dimension(1000, 500);
    table.setPreferredScrollableViewportSize(minimumSize);
    TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(model);
    table.setRowSorter(sorter);

    sorter.setComparator(3, Sorter.getComparator());
    sorter.setComparator(4, Sorter.getComparator());
    table.getColumnModel().getColumn(3).setCellRenderer(new CellRenderer()); //custom cell renderer
    table.getColumnModel().getColumn(4).setCellRenderer(new CellRenderer()); //custom cell renderer

    JScrollPane sp = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}

以及我如何填写它:

void refreshTableContent(Vector<Gericht> v) {
    for (int i = table.getRowCount() - 1; i >= 0; i--) {
        model.removeRow(i);
    }
    fillTable(v);
}

void fillTable(Vector<Gericht> v) {
    for (int i = 0; i < v.size(); i++) {
        Gericht g = v.get(i);
        Vector<Object> vhelp = new Vector<>();
        vhelp.add(df.format(g.getDate()));
        vhelp.add(g.getClassification());
        vhelp.add(g.getName());
        vhelp.add(g.getPreisIntern());
        vhelp.add(g.getPreisExtern());
        model.addRow(vhelp);
    }
}

modelDefaultTableModel,您可以在其中添加和删除数据。在每次重新填充时,我首先删除所有行,然后将它们添加为新行。这可能不是最好的解决方案,但它有效

在这种情况下,该模型是一顿饭,它有几个领域。所以我创建了一个我自己的对象的矢量,然后创建了一个帮助向量,并将一餐的值存储在其中。然后我将向量作为行添加到JTable中,下一餐被存储在帮助向量中。

我希望你能理解我在这里做了什么

答案 1 :(得分:0)

//This is the code which I have used to change jtable cell background color dynamically
[green color indicates empty(free) cell and red color indicates occupied cells][1]
 int row, col, row1, column;
    TableCellRenderer renderer;
    private static final int STATUS_COL = 1;
String host = "jdbc:mysql://localhost/your_database";
        String username = "root";
        String password = "";
        Statement stmt = null;
try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connect = DriverManager.getConnection(host, username, password);
            stmt = connect.createStatement();
            String sql = "your query";
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData meta = rs.getMetaData();
            Object[][] data = new Object[10][2];
            DefaultTableModel model = new DefaultTableModel(data, col);
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            rs = stmt.executeQuery(sql);
 int rowCnt = 0;
              try{

       rs = stmt.executeQuery(sql);
       if(rs.last()){
           rowCnt = rs.getRow();
       } 
    } catch (Exception e){
       System.out.println("Error getting row count");
       e.printStackTrace();
    }

            int nCol = rs.getMetaData().getColumnCount();
            List<String[]> table = new ArrayList<>();
String[] row = new String[nCol];
for(int l=1; l<rowCnt; l++)
{
    for (int iCol = 1; iCol <= nCol; iCol++) {
                    Object obj = rs.getObject(iCol);
                    row[iCol - 1] = (obj == null) ? null : obj.toString();
jTable1.setDefaultRenderer(Object.class, new EntryCellRender());
 }
                table.add(row);
}
 } catch (Exception e) {
            System.out.println(e);
        }
    }
public class EntryCellRender extends DefaultTableCellRenderer {

    private final Color alt2 = Color.RED;
    private final Color alt1 = Color.GREEN;
    private final Color invalidStatus = Color.RED;

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cr = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ("".equals(table.getValueAt(row, col))) {
             setBackground(alt1);
           } else {
               setBackground(alt2);
           }

        return cr;
    }

    private Color colorAlternator(int row) {
        if ((row % 2) == 0) {
            return alt1;
        } else {
            return alt2;
        }
    }
}   

    enter code here

  [1]: https://i.stack.imgur.com/Fi4LF.png

答案 2 :(得分:-1)

正如 XtremeBaumer 建议的那样,自定义单元格渲染器是实现您想要的标准方法。请记住,只创建了一个(1)单元格渲染器类的实例,并用于渲染所有JTable单元格。
祝你好运!