Greeting all,
i want to convert the JTable to an Image using the method "createImage", but the jtable image doesn't appears i tried to figure out but no result at all..
thanks for any help.
public class JTableImageCreator extends JPanel { public JTableImageCreator() { setBorder(BorderFactory.createLineBorder(Color.black)); } public Dimension getPreferredSize() { return new Dimension(250,200); } public void paintComponent(Graphics2D g) { super.paintComponent(g); BufferedImage table = createImage(getTable()); g.drawImage(table, 0, 0, 100, 100 , null); } public JTable getTable() { String[] columns = {"ColumnA", "ColumnB", "ColumnC"}; Object[][] data = { {"A", new Integer(60), new Boolean(true)}, {"B", new Integer(60), new Boolean(true)}, {"C", new Integer(60), new Boolean(true)}, {"D", new Integer(60), new Boolean(true)} }; return new JTable(data,columns); } /** * This method takes a JTable and returns a BufferedImage of it * * @param table * @return BufferedImage of JTable */ public static BufferedImage createImage(JTable table) { //get the table header component JTableHeader tableHeaderComp = table.getTableHeader(); //Calculate the total width and height of thr table iwth the header int totalWidth = tableHeaderComp.getWidth() + table.getWidth(); int totalHeight = tableHeaderComp.getHeight() + table.getHeight(); //create a BufferedImage object of total width and height BufferedImage tableImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB); //get the graphics object from the image Graphics2D g2D = (Graphics2D)tableImage.getGraphics(); //paint the table header on image graphics tableHeaderComp.paint(g2D); //now translate the origin to (0, height of table header) g2D.translate(0, tableHeaderComp.getHeight()); //now paint the table on the image graphics table.paint(g2D); //return the table image return tableImage; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { System.out.println("Created GUI on EDT? "+ SwingUtilities.isEventDispatchThread()); JFrame f = new JFrame("Swing Paint Demo"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // f.add(new JTableImageCreator()); f.getContentPane().add(new JTableImageCreator()); f.pack(); f.setVisible(true); } }