1

I am trying to generate a JXTable with a background image ( a text would be fine as well). Here is my extended JXTable class:

public class JXTableWithBackground extends JXTable{

    ImageIcon image;
    public JXTableWithBackground(ParticipantTableModel pTableModel, ImageIcon image){
        super(pTableModel);
        this.image=image;
    }
    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;
    }

    @Override
    public void paint(Graphics g) {
        //draw image in centre
        final int imageWidth = image.getIconWidth();
        final int imageHeight = image.getIconHeight();
        final Dimension d = getSize();
        final int x = (d.width - imageWidth)/2;
        final int y = (d.height - imageHeight)/2;
        g.drawImage(image.getImage(), x, y, null, null);
        super.paint(g);
    }

The image don't shows up - I only see white space. Any idea?

Anthea
  • 3,741
  • 5
  • 40
  • 64
  • The cell component might still render non-opaque pixels due to its background color. Did you try returning non-opaque empty labels as a test? – Thomas Jan 16 '12 at 16:36
  • @Thomas I just tried it and it's still white – Anthea Jan 16 '12 at 16:44
  • Please also note that the table itself might have a background thus calling `super.paint(g)` might actually completely hide your image. – Thomas Jan 16 '12 at 16:46
  • @Thomas right, setting the opaque value to false made the image visible! – Anthea Jan 16 '12 at 16:53
  • Great. I'll add an answer. :) – Thomas Jan 16 '12 at 16:58
  • SwingX or plain vanilla Swing: for custom painting the method to override is paintComponent (_not_ paint). For visual decorations in SwingX, see @Robin's answer. Interesting (and a slight beware), though: opaqueness is not one of visual properties guaranteed to be reset on each config round, so you can't re-use the same ComponentProvider across opaque and not-opaque tables (or lists or trees) – kleopatra Jan 17 '12 at 10:30

2 Answers2

1

For future reference:

The problem seems to be that the table itself is not rendered transparently. Setting the table itself to opaque = false helps.

Thomas
  • 87,414
  • 12
  • 119
  • 157
1

For SwingX the recommended way to for example use an opaque component for rendering is to use the Highlighter interface. So instead of overriding the prepareRenderer method, it is recommended to write your Highlighter and use the JXTable#setHighlighters method to set in on the table

Robin
  • 36,233
  • 5
  • 47
  • 99