Java Swing How to - Paint JTable








Question

We would like to know how to paint JTable.

Answer

//w  ww . j  ava2 s .  co  m
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JTable;
import javax.swing.table.JTableHeader;

public class Main {
  public static BufferedImage createImage(JTable table) {
    JTableHeader tableHeaderComp = table.getTableHeader();
    int totalWidth = tableHeaderComp.getWidth() + table.getWidth();
    int totalHeight = tableHeaderComp.getHeight() + table.getHeight();
    BufferedImage tableImage = new BufferedImage(totalWidth, totalHeight,
        BufferedImage.TYPE_INT_RGB);
    Graphics2D g2D = (Graphics2D) tableImage.getGraphics();
    tableHeaderComp.paint(g2D);
    g2D.translate(0, tableHeaderComp.getHeight());
    table.paint(g2D);
    return tableImage;
  }
}