我需要在位图中绘制组件及其所有子组件的内容。 如果我想绘制整个组件,以下代码可以正常工作:
public void printComponent(Component c, String format, String filename) throws IOException {
// Create a renderable image with the same width and height as the component
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
// Render the component and all its sub components
c.paintAll(image.getGraphics());
// Render the component and ignoring its sub components
c.paint(image.getGraphics());
// Save the image out to file
ImageIO.write(image, format, new File(filename));
}
但是我没有找到只绘制此组件的区域的方法。 有什么想法吗?
答案 0 :(得分:7)
你需要这样翻译:
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.translate(-100, -100);
c.paintComponent(g);
g.dispose();
输出的完整示例:
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame("Test");
frame.add(new JTable(new DefaultTableModel() {
@Override
public int getColumnCount() {
return 10;
}
@Override
public int getRowCount() {
return 10;
}
@Override
public Object getValueAt(int row, int column) {
return row + " " + column;
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.translate(-100, -100);
frame.paintComponents(g);
g.dispose();
ImageIO.write(image, "png", new File("frame.png"));
}
答案 1 :(得分:1)
Screen Image课程为您简化了此过程。