Java Paint component into bitmap(Java Paint 组件转换成位图)
问题描述
我需要在位图中绘制一个组件及其所有子组件的内容.如果我想绘制整个组件,以下代码可以完美运行:
I need to draw the content of a component and all its subcomponents in a bitmap. The following code works perfectly if i want to draw the entire component :
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));
}
但我没有找到仅绘制此组件的 区域 的方法.有什么想法吗?
but i didn't find a way for drawing only a region of this component. Any idea ?
推荐答案
你需要这样翻译:
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.translate(-100, -100);
c.paintComponent(g);
g.dispose();
<小时>
带有输出的完整示例:
Full example with output:
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"));
}
这篇关于Java Paint 组件转换成位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Paint 组件转换成位图
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01