3
votes

I need to add an image background behind my JTable, should not scrole down while scrolling my JTable. currently i have added a Image behing my JTable. using the paint method.

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);
            }

problem is that. This JTable is at JScrollPane. and when scrolling the pane. also scrolls down the image. and repeats the image at each scroll.

is there any way to restrict scroll on background only. thanks

2

2 Answers

8
votes

Paint the background on the JScrollPane instead. You also need to make both the JTable and the cell renderer transparent by using setOpaque(false). (And use the paintComponent method when overriding).

The code below produced this screenshot:

screenshot

public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame("Test");

    final BufferedImage image = ImageIO.read(new URL(
            "http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

    JTable table = new JTable(16, 3) {{
        setOpaque(false);
        setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {{
            setOpaque(false);
        }});
    }};

    frame.add(new JScrollPane(table) {{
            setOpaque(false);
            getViewport().setOpaque(false);
        }
        @Override
        protected void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            super.paintComponent(g);
        }

    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
4
votes