JScrollPane中带有JTable的背景图片

3
我正在尝试在JScrollPane后面添加一个居中的背景图片。该背景图相对于视口的位置应保持静态且居中。
我已经尝试将JScrollPane添加到带有绘制图像的JPanel中,并使其他所有内容透明,但结果很难看并且存在渲染问题。
3个回答

5

请查看文章末尾的WatermarkDemo,以获取完整示例。


3
您应该继承 JTable 并覆盖其 paint 方法,以便它绘制您的背景图像。以下是一些示例代码:
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);

就像我之前所说的,我尝试过这条路线,但最终遇到了表格/滚动窗格透明度方面的问题。 - Robert Foss

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接