Java Swing How to - Create image out of a JTable








Question

We would like to know how to create image out of a JTable.

Answer

/*from ww  w  . j  a  va  2s. c  o 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;
  }
}