Alex Rivera | Logout

Java - Swing - JTable - Set Color for Selected Row, but not Cell

Asked 2012-04-04T18:55:16.887
11

I am trying to make my table select an entire row when you click on a cell (which can be done by turning off column select), but, I don't want the extra thick border around the specific cell you clicked to be highlighted. I was hoping this would be easy but apparently it involves renderers so I did a lot of research and the closest I can get is this:

    JTable contactTable = new JTable(tableModel);

    contactTable.setCellSelectionEnabled(true);
    contactTable.setColumnSelectionAllowed(false);
    contactTable.setRowSelectionAllowed(false);
    contactTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // This renderer extends a component. It is used each time a
    // cell must be displayed.
    class MyTableCellRenderer extends JLabel implements TableCellRenderer {
        // This method is called each time a cell in a column
        // using this renderer needs to be rendered.
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
            // 'value' is value contained in the cell located at
            // (rowIndex, vColIndex)

            if (isSelected) {
                // cell (and perhaps other cells) are selected

            }

            if (hasFocus) {
                // this cell is the anchor and the table has the focus
                this.setBackground(Color.blue);
                this.setForeground(Color.green);
            } else {
                this.setForeground(Color.black);
            }

            // Configure the component with the specified value
            setText(value.toString());

            // Set tool tip if desired
            // setToolTipText((String)value);

            // Since the renderer is a component, return itself
            return this;
        }

        // The following methods override the defaults for performance reasons
 
Edit
Report

2 Answers

16

too direct just do add line

tablename.setSelectionBackground(Color.red);

in my case

jtbillItems.setSelectionBackground(Color.red);
answered 2012-05-24T18:13:19.883
0

For the second question you can try setSelectionBackground(Color) and setSelectionForeGround(Color) methods. I'm not sure how you can solve the first one. And one last suggestion you can use some swing designer plugin such ass JBuilder. It would help lot.

answered 2012-04-04T19:32:43.807

Your Answer