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

1.2k views Asked by At

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();
        }
    }
}
2

There are 2 answers

1
Rajeev On BEST ANSWER

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;
    }

  };;
0
mKorbel On

on this site or java oracle doc

  • TableCellRenderer is just about painting, is statics painting based on settings in XxxTableCellRenderer, isn't interactive, is about painting illusion,

  • painting in XxxTableCellRenderer is quite intesive and is invoked from all key and mouse events, methods implemented in rellated APIs

  • it could be separate definition for JTable or separate class thats returns rulles, painting definitions for JTables view

  • JDBC isn't good place to set or define the Renderer, about add a new data from database to DefaultTableModel,

  • ResultSet.CONCUR_UPDATABLE could not be set for JTable, is snapshot from ResultSet, it hasn't any action back to database

  • why is returns from JDBC restricted to String s[] = new String[8];, set data typed correctly by override getColumnClass

  • set alignment in Renderer (data typed returns alingment by default), e,g, by cast to JLabel, then all methods implemented in JLabels API can be used there

  • by default there are used prepareRenderer, getTableCellRendererComponent, both for whole JTables view and many various attempts for Renderer applied just for the concrete Columns