Asghar
Asghar

Reputation: 2346

How to add image background on JTable , that does not scroll when scrolling JTable

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

Upvotes: 3

Views: 3244

Answers (2)

dacwe
dacwe

Reputation: 43504

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

Upvotes: 8

mKorbel
mKorbel

Reputation: 109813

Upvotes: 3

Related Questions