Background Image in JScrollpane with JTable

I am trying to add a centered background image behind a JTable in JScrollPane. The background position relative to the viewport should be centered and static.

Ive tried adding JScrollPane to the JPanel with the drawn image and making everything else translucent, but the result was ugly and had rendering problems.

+3
source share
3 answers

See WatermarkDemo at the end of the article for a complete example.

+5
source

You must subclass JTableand override its method paintso that it draws a background image. Here is a sample code:

final JTable table = new JTable(10, 5) {

    final ImageIcon image = new ImageIcon("myimage.png");

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        final Component c = super.prepareRenderer(renderer, row, column);
        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);
    }
};
table.setOpaque(false);

final JScrollPane sp = new JScrollPane(table);

final JFrame f = new JFrame();
f.getContentPane().add(sp);
f.setSize(200,200);
f.setVisible(true);
+3
source
+1
source

Source: https://habr.com/ru/post/1787627/


All Articles