根据msyql的结果集值更改Jtable单元格的颜色

时间:2016-01-30 22:25:42

标签: java swing jdbc jtable tablecellrenderer

我使用Netbeans开发一个java应用程序,我有一个来自MYSQL数据库的结果集,我想将这些数据放在一个JTable中。 当我想根据其值更改JTable单元格的背景颜色时出现问题(例如:如果Jtable中单元格的值不等于1,则其颜色必须为红色)。 这是我的代码:

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * 
 */
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.sql.*;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Cell2 {

    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/db";

    //  Database credentials
    static final String USER = "root";
    static final String PASS = "(abdc)";

    public void queryABTS(JTable table) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //STEP 2: Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            //STEP 4: Execute a query
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * from dbn;";
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData rsmt = rs.getMetaData();
            int c = rsmt.getColumnCount();
            Vector column = new Vector(c);
            for (int i = 1; i <= c; i++) {
                column.add(rsmt.getColumnName(i));
            }
            Vector data = new Vector();
            Vector row = new Vector();
            while (rs.next()) {
                row = new Vector(c);
                for (int i = 1; i <= c; i++) {
                    row.add(rs.getString(i));
                }
                data.add(row);
            }

            table.setModel(new javax.swing.table.DefaultTableModel(data, column));
            table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 13));
           // table.getValueAt(1, 1);

            TableColumn column1 = null;

            for (int i = 0; i < 5; i++) {
                column1 = table.getColumnModel().getColumn(i);
                if (i == 3) {
                    column1.setPreferredWidth(150); //third column is bigger

                } else {
                    column1.setPreferredWidth(50);

                }
            }

            setCellRenderer(table);
            //color cell =======================================================================

             // end color cell ==================================================================


//========================================================

//=======================================================
            //STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            //finally block used to close resources
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se2) {
            }// nothing we can do
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }//end finally try
        }//end try
        System.out.println("Goodbye!");
    }//end main  


public static TableCellRenderer createCellRenderer() {
    return new DefaultTableCellRenderer() {
        @Override
        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);

            if (column == 4 && "1".equals((String) value)) {
    c.setBackground(Color.RED);
    }

            return c;
        }
    };
}

public static void setCellRenderer(JTable table) {
    TableCellRenderer cellRenderer = createCellRenderer();
    table.setDefaultRenderer(Object.class, cellRenderer);
}





}

1 个答案:

答案 0 :(得分:1)

试试这个

public static TableCellRenderer createCellRenderer() {
    return new DefaultTableCellRenderer() {
        @Override
        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);

            c.setBackground(Color.GREEN);

            return c;
        }
    };
}

public static void setCellRenderer(JTable table) {
    TableCellRenderer cellRenderer = createCellRenderer();
    table.setDefaultRenderer(Object.class, cellRenderer);
}

通过调用table.setModel(new javax.swing.table.DefaultTableModel(data, column));,您将数据放入表模型中。 JTable默认使用DefaultTableCellRenderer实例来渲染单元格,可以通过调用table.setDefaultRenderer(Integer.class, cellRenderer)替换为您自己的单元格渲染器 - 这会将自定义cellrenderer设置为所有Integer列({ {1}}使用DefaultTableModel列)。当显示表时,表的每个单元格都由表的cellrenderer的Object方法自定义。在此方法中,您具有当前组件(单元格)及其值和位置(请参阅参数),您可以使用它们在渲染之前自定义单元格。

因此,如果您想为第二列中值为1的每个单元格将背景颜色设置为RED,您可以写:

getTableCellRendererComponent(...)

将表的if (column == 1 && ((Integer) value) == 1) { c.setBackground(Color.RED); } 传递给单元格渲染器

data