1

I have a JTable and to set a picture as background in JTable and other properties i used this code.

tblMainView= new JTable(dtModel){
        public Component prepareRenderer(TableCellRenderer renderer, int row, 
                   int column) 
        {
        Component c = super.prepareRenderer( renderer, row, column);
        // We want renderer component to be transparent so background image 
        // is visible
        if( c instanceof JComponent )
        ((JComponent)c).setOpaque(false);
        return c;
        }
        ImageIcon image = new ImageIcon( "images/watermark.png" );          
          public void paint( Graphics g )
        {
        // First draw the background image - tiled 
        Dimension d = getSize();
        for( int x = 0; x < d.width; x += image.getIconWidth() )
        for( int y = 0; y < d.height; y += image.getIconHeight() )
        g.drawImage( image.getImage(), x, y, null, null );
        // Now let the regular paint code do it's work
        super.paint(g);
        }       

        public boolean isCellEditable(int rowIndex, int colIndex) {
          return false;
        }
        public Class getColumnClass(int col){
            if (col == 0)  
            {  
            return Icon.class;  
            }else if(col==7){
                return String.class;
            } else
            return String.class; 
        }   
        public boolean getScrollableTracksViewportWidth() {
            if (autoResizeMode != AUTO_RESIZE_OFF) {
                if (getParent() instanceof JViewport) {
                return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
                }
            } 
            return false;
            }

    };

    tblMainView.setOpaque(false);

Every thing is working correctly. But when i select a row, the row data hides.it shows my row like this

i want the result same like this,enter image description here dtModel is the deafultTableModel for my JTable named tblMainView

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Asghar
  • 2,336
  • 8
  • 46
  • 79
  • Did you check that it is really hidden? Maybe it is just white text on your white background? – Howard Jul 29 '11 at 14:17
  • @Howard: its just a white background, because i am getting values by getValueAt(row,col); method. – Asghar Jul 29 '11 at 14:21
  • Post your [SSCCE](http://sscce.org) that demonstrates the problem. – camickr Jul 29 '11 at 14:51
  • 1
    The problem is only that when i set setOpaque(true); its working fine and everything is OK, watermark is also behind the Table and row selection is also working fine. But when i set setOpaque(false); the row selection is getting the problem as described. – Asghar Aug 01 '11 at 05:44

1 Answers1

6

Overriding prepareRenderer() is a recommended way to do custom rendering for an entire table row, but you can't make it do everything. In particular, the default renderer for Icon should do what you want, and there's no reason to override paint(), at all.

Addendum: Looking closer, your selected field appears empty because setOpaque(false) interferes with the optimization mentioned in the DefaultTableCellRenderer API. The example you copied won't work.

For reference, the example below overrides the getColumnClass() of DefaultTableModel to obtain the default renderer for types Icon and Date.

Java GUI

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.Calendar;
import java.util.Date;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** @see https://stackoverflow.com/questions/6873665 */
public class JavaGUI extends JPanel {

    private static final int ICON_COL = 0;
    private static final int DATE_COL = 1;
    private static final Icon icon = UIManager.getIcon("Tree.closedIcon");
    private final Calendar calendar = Calendar.getInstance();

    public JavaGUI() {
        CustomModel model = new CustomModel();
        JTable table = new JTable(model) {

            @Override
            public Component prepareRenderer(
                    TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                if (isRowSelected(row)) {
                    c.setBackground(Color.blue);
                } else {
                    c.setBackground(Color.white);
                }
                return c;
            }
        };
        for (int i = 1; i <= 16; i++) {
            model.addRow(newRow(i));
        }
        this.add(table);
    }

    private Object[] newRow(int i) {
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return new Object[]{icon, calendar.getTime()};
    }

    private static class CustomModel extends DefaultTableModel {

        private final String[] columnNames = {"Icon", "Date"};

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == ICON_COL) {
                return Icon.class;
            } else if (col == DATE_COL) {
                return Date.class;
            }
            return super.getColumnClass(col);
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }

    private void display() {
        JFrame f = new JFrame("JavaGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JavaGUI().display();
            }
        });
    }
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Using `prepareRenderer()` I was able to add instance variables to conditionally change the highlighted background color.. ( ie. 'active' ) using this method... whereas overriding `getTableCellRendererComponent` failed. – Edward J Beckett Feb 25 '16 at 18:49
  • @EddieB: This [example](http://stackoverflow.com/a/5799016/230513) contrasts the two approaches. – trashgod Feb 25 '16 at 21:44
  • @trashgod Yes... I reviewed that too... thanks for the great resources. – Edward J Beckett Feb 25 '16 at 21:58