How to add an image background to a JTable that does not scroll when the JTable is scrolled

I need to add a background image behind my JTable without scrolling through the JTable. I currently have added an image displaying 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 work
                super.paint(g);
            }

      

the problem is this. This JTable is in the JScrollPane. and when scrolling the panel. also scrolls the image down. and repeats the image on every scroll.

is there a way to restrict scrolling to only the background. thank

+2


source to share


2 answers


Paint the background on JScrollPane

. You should also make a transparent JTable

and transparent box using setOpaque(false)

. (And use the method paintComponent

when overridden).

The code below is a 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);
}

      

+8


source


  • you can paint JTable backgroung

    the same / similair as for restJComponents

  • you need to override the paintComponent()

    method insteadpaint()

  • example about paintComponent () including selecting individual lines

  • you can draw on JXLayer(Java6)

    , there is JLayer (Java7)

    also

  • you can draw on GlassPane

  • you can draw in JViewport



+4


source







All Articles