Search code examples
javaswingjtablebackground-colordefaulttablemodel

JTable : how to align data in the center or how to set row background color alternate


How can I set the row background color in JTable and also align the data to the center.The JTable1 is dynamic. JTable uses defaultTableModel for setting the data. I want to if i%==0 than background color is #Color.GRAY else #Color.WHITE I read about render class but can not understand about renderer class

import java.awt.Dimension;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

class FacultyList extends JPanel {

    static DefaultTableModel dm;
    JTable table;
    JScrollPane jsp_table;
    static Connection conn;
    static Statement stmt;
    static ResultSet rs;

    public FacultyList(Connection c) {
        conn = c;
        String col_name[] = {"S.No.", "Name", "Father Name", "College ID", 
            "Gender", "Date of Birth", "Branch", "Contact No."};
        dm = new DefaultTableModel(null, col_name);
        table = new JTable(dm);
        table.getTableHeader().setFont(new Font("Goudy Old Style", Font.BOLD, 15));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.getColumnModel().getColumn(0).setPreferredWidth(50);
        table.getColumnModel().getColumn(1).setPreferredWidth(150);
        table.getColumnModel().getColumn(2).setPreferredWidth(150);
        table.getColumnModel().getColumn(3).setPreferredWidth(125);
        table.getColumnModel().getColumn(4).setPreferredWidth(50);
        table.getColumnModel().getColumn(5).setPreferredWidth(125);
        table.getColumnModel().getColumn(6).setPreferredWidth(225);
        table.getColumnModel().getColumn(7).setPreferredWidth(150);
        jsp_table = new JScrollPane(table);
        jsp_table.setPreferredSize(new Dimension(975, 520));
        addRowTable();
        add(jsp_table);
    }

    public static void addRowTable() {
        try {
            int a = dm.getRowCount();
            int i = 0;
            while (i < a) {
                dm.removeRow(0);
                i++;
            }
            String fac = "Faculty";
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                    ResultSet.CONCUR_UPDATABLE);
            rs = stmt.executeQuery("SELECT NAME, FNAME, CLG_ID, GANDER, "
                    + "DOB, BRANCH, CONTACT FROM PROFILE "
                    + "where I_AM = '" + fac + "'");
            int count = 1;
            while (rs.next()) {
                String s[] = new String[8];
                s[0] = "" + count;
                s[1] = rs.getString(1);
                s[2] = rs.getString(2);
                s[3] = rs.getString(3);
                s[4] = rs.getString(4);
                s[5] = rs.getString(5);
                s[6] = rs.getString(6);
                s[7] = "" + rs.getLong(7);
                count++;
                if (i % 2 == 0) {
                } else {
                }
                dm.addRow(s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Solution

  • You could use a custom renderer to do this. It can be done as follows :

     table1 = new JTable(){
    
    public Component prepareRenderer(TableCellRenderer tcr, int row,
        int column) {
        Component c = super.prepareRenderer(tcr, row, column);
    
        if (isRowSelected(row)) {
    
            c.setForeground(getSelectionForeground());
            c.setBackground(getSelectionBackground());
    
        } else {
    
            c.setForeground(getForeground());
            c.setBackground((row % 2 == 0) ? getBackground()
                : Color.lightGray);
        }
    
        int rendererWidth = c.getPreferredSize().width;
        TableColumn tableColumn = getColumnModel().getColumn(column);
        tableColumn.setPreferredWidth(Math.max(rendererWidth
            + getIntercellSpacing().width,
            tableColumn.getPreferredWidth()));
    
    DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
    rightRenderer.setHorizontalAlignment(SwingConstants.CENTER);
    table1.getColumnModel().getColumn(column).setCellRenderer(rightRenderer);
    return c;
        }
    
      };;