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

前端 未结 2 359
难免孤独
难免孤独 2021-01-14 07:56

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

相关标签:
2条回答
  • 2021-01-14 08:35
    • you can painting JTable's backgroung, same/similair as for rest of JComponents

    • you have to override paintComponent() instead of method paint()

    • example about paintComponent() including customized rows selection(s)

    • you can painting to the JXLayer(Java6), there is JLayer (Java7) also

    • you can painting to the GlassPane

    • you can painting to the JViewport

    0 讨论(0)
  • 2021-01-14 08:44

    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);
    }
    
    0 讨论(0)
提交回复
热议问题