How to add watermark or background image to the JTable?

How to add watermark or background image to the JTable?



Many times we need to add watermark or insert image behind the JTable. Following tutorial will explain how to add image watermark or insert an image behind the JTable.

1. Adding a single image as a watermark or as background image in JTable.


As shown in the code below we need to create a table cell renderer which will create the cell component as transparent by setting opaque as false
We need to extend the JScrollPane to as we have done in ScrollPanelwithWaterMark to draw the image which we want to show as background image of the JTable.
We are overriding paintComponent method to draw an image and add it in the background of JTable. Also we are doing scrollpane and viewport transparent by using setOpaque( false )

Using this method if you scroll the table the background image will remain at fixed position.

Example for adding watermark in JTable


public class ScrollPanelwithWaterMark extends JScrollPane {
    BufferedImage backgroundImage;
    public ScrollPanelwithWaterMark(JTable table, URL url ) {
            super(table);
            try{
                backgroundImage = ImageIO.read(url);
            }catch(Exception es){
                
            }
            setOpaque(false);
            getViewport().setOpaque(false);
            
        
    }
    protected void paintComponent(Graphics g) {
        final int imageWidth = backgroundImage.getWidth();
        final int imageHeight = backgroundImage.getHeight();
        final Dimension d = getSize();
        final int x = (d.width - imageWidth)/2;
        final int y = (d.height - imageHeight)/2;
        g.drawImage(backgroundImage, x, y, null, null);
            super.paintComponent(g);
        
    }
}

// JTableBackground.java

public class JTableBackground {

    public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame("JTable Watermark Example");
        String data[][] = {{"001", "Ivan", "HR", "Manager"},
            {"002", "Jenny", "HR", "Asst. Manager"},
            {"003", "Thomas", "Marketing", "Manager"},
            {"004", "Charles", "Marketing", "Sales Man"},
            {"005", "Tessa", "Research", "Engineer"},
            {"006", "Alan", "Research", "Engineer"},
            {"007", "Maria", "Research", "Engineer"},
            {"008", "Steve", "Research", "Manager"},
            {"009", "Terry", "Admin", "Manager"},
            {"010", "Robert", "Admin", "Executive"},
            {"011", "John", "Marketing", "Executive"},
            {"012", "Mark", "Marketing", "Marketing"},
            {"013", "Anna", "Research", "Consultant"},};
        String col[] = {"ID", "Name", "Department", "Role"};
        final JTable table = new JTable(data, col) {

            @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;
            }
        };
        table.setRowHeight(25);
        table.setOpaque(false);
        JTableHeader header = table.getTableHeader();
        header.setBackground(Color.DARK_GRAY);
        header.setForeground(Color.WHITE);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        frame.getContentPane().add(new ScrollPanelwithWaterMark(table, new File("D:\\images\\backgroundlogo.png").toURL()));
        
        frame.pack();
        frame.setSize(360, 320);
        frame.show();
    }
}




2. Adding bakground image on the total background area as tiles.

To add an image to the to the total background we need to extend JViewPort because the component which does the real scrolling is JViewPort.

So in this example also we need to make sure each cell component is transparent by using table cell renderer to make setOpaque(false).



Here we are using a TexturePaint class which provides a way to fill a shape with a texture specified in terms of image.
When TexturePaint is constructed the texture is anchored to the upper left corner and replicated in all directions indefinately.

In the example below, in constructor we are creating a rectangle using the image and also creating a TexturePaint object using image and rectangle.
In paintComponent method calling super. paintComponent() first, and then drawing the texture on top of the component. This is because the existing background might need to show through where the texture has translucent sections.

Example for adding watermark in JTable



public class ViewPortWithWaterMark extends JViewport {
   BufferedImage backgroundImage;
   TexturePaint texturePaint;
   
   public ViewPortWithWaterMark(URL url) {
       try{
           backgroundImage = ImageIO.read(url);
           Rectangle rect = new Rectangle(0,0,
                   backgroundImage.getWidth(null),backgroundImage.getHeight(null));
           texturePaint = new TexturePaint(backgroundImage, rect);
       }catch(Exception es){
           
       }
    }
   
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        if(texturePaint != null) {
                    Graphics2D g2 = (Graphics2D)g;
                    g2.setPaint(texturePaint);
                    g.fillRect(0,0,getWidth(),getHeight());

            }
      }
    
    public void setView(JComponent view) {
        view.setOpaque(false);
 super.setView(view);

    }
}
//JTableBackground.java

public class JTableBackground {

    public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame("JTable Watermark Example");
        String data[][] = {{"001", "Ivan", "HR", "Manager"},
            {"002", "Jenny", "HR", "Asst. Manager"},
            {"003", "Thomas", "Marketing", "Manager"},
            {"004", "Charles", "Marketing", "Sales Man"},
            {"005", "Tessa", "Research", "Engineer"},
            {"006", "Alan", "Research", "Engineer"},
            {"007", "Maria", "Research", "Engineer"},
            {"008", "Steve", "Research", "Manager"},
            {"009", "Terry", "Admin", "Manager"},
            {"010", "Robert", "Admin", "Executive"},
            {"011", "John", "Marketing", "Executive"},
            {"012", "Mark", "Marketing", "Marketing"},
            {"013", "Anna", "Research", "Consultant"},};
        String col[] = {"ID", "Name", "Department", "Role"};
        final JTable table = new JTable(data, col) {

            @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;
            }
        };
        table.setRowHeight(25);
        table.setOpaque(false);
        JTableHeader header = table.getTableHeader();
        header.setBackground(Color.DARK_GRAY);
        header.setForeground(Color.WHITE);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
          ViewPortWithWaterMark viewPortWithWaterMark = new ViewPortWithWaterMark(new File("D:\\images\\backgroundlogo.png").toURL());
            viewPortWithWaterMark.setView(table);
            JScrollPane scroll = new JScrollPane();
            scroll.setViewport(viewPortWithWaterMark);
            frame.getContentPane().add(scroll);
         
        frame.pack();
        frame.setSize(360, 320);
        frame.show();
    }
}



Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment