获取 Java 小程序的屏幕截图 [英] Getting a screenshot of a Java applet

查看:28
本文介绍了获取 Java 小程序的屏幕截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java Robot 类对我参与过的各种项目进行一些自动化测试,但在获取任何非全屏程序的屏幕截图时遇到了一些问题.

I'm trying to use the Java Robot class to do some automated testing for various projects I've worked on and I'm having some trouble getting screen shots of any program that isn't full screen.

对于全屏程序,我只使用:

For full screen programs I just use:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();BufferedImage image = robots.createScreenCapture (dim);

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); BufferedImage image = robot.createScreenCapture (dim);

我知道我通常无法获得特定窗口的屏幕截图,因为我很确定 Java 不知道每个窗口在屏幕上的位置(因为它特定于操作系统).

I know that I can't get a screenshot of a particular window in general, since I'm pretty sure Java doesn't know where on the screen each window is (since its OS specific).

但我希望我仍然可以在小程序查看器中获得小程序的屏幕截图,因为窗口以某种方式连接到 JVM.

But I'm hoping I could still get a screeenshot of an applet in an applet-viewer, since the window is connected to the JVM in one way or another.

那么,关于这是否可行的任何想法?如果是这样,我该怎么做?

So, any ideas on whether or not this is possible? And if so, how I might go about doing it?

推荐答案

假设你有一个对你的小程序(或任何其他组件)的引用,你创建一个离屏 Graphics2D 实例并让组件自己绘制它.

Assuming you have a reference to your applet (or any other Component), you create an off-screen Graphics2D instance and have the component paint itself to that.

  Component applet = ...;    // the applet

  Dimension size = applet.getSize();
  BufferedImage offScreenImage = (BufferedImage) applet.createImage(size.width, size.height);
  Graphics2D g2 = offScreenImg.createGraphics();
  g2.setBackground(applet.getBackground());

  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

  g2.clearRect(0, 0, size.width, size.height);

  applet.paint(g2);

  // now you can use BufferedImage as before

关键是Component.createImage为双缓冲创建离屏图像.

The key is Component.createImage which creates an off-screen image for double buffering.

这篇关于获取 Java 小程序的屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆