我需要截取屏幕区域的截图,以便在Java中使用“Robot”。但是,如果用户将窗口放在该区域中,则窗口将显示在屏幕截图上而不是背景上。
我尝试通过放置:
来解决我的问题myframe.setVisible(false);
但是当我看到屏幕截图时,窗户就出现了。我以为是因为窗户没有足够的时间消失,或者因为屏幕的渲染还没有更新,所以我尝试了不同的东西,比如使用:
repaint();
或者放置一个
try{}finally{}
阻止以确保try块中的操作已完成。 但是这些解决方案中没有一个可行。这些是我脑海中的其他方式,但它们看起来很糟糕,因为它们使用函数来等待。
那么我的问题有一个很好的解决方案吗?
答案 0 :(得分:1)
当窗口关闭时,你可以使用窗口监听器来触发屏幕截图:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MainFrame extends JFrame implements WindowListener {
public MainFrame() {
super("Test Frame");
JLabel displayMsg = new JLabel(" Close window");
getContentPane().add(displayMsg);
addWindowListener(this);
setSize(400, 300);
setVisible(true);
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("WindowListener method called: windowClosing.");
//add you screen capture code here
}
//--Not used
@Override
public void windowClosed(WindowEvent e) {
//do nothing
}
@Override
public void windowOpened(WindowEvent e) {
//do nothing
}
@Override
public void windowIconified(WindowEvent e) {
//do nothing
}
@Override
public void windowDeiconified(WindowEvent e) {
//do nothing
}
@Override
public void windowActivated(WindowEvent e) {
//do nothing
}
@Override
public void windowDeactivated(WindowEvent e) {
//do nothing
}
public void windowGainedFocus(WindowEvent e) {
//do nothing
}
public void windowLostFocus(WindowEvent e) {
//do nothing
}
public static void main(String[] args) {
new MainFrame();
}
}
答案 1 :(得分:0)
使用SwingUtilities.invokeLater()
获取实际屏幕截图。不是100%肯定,但我认为myframe.setVisible(false);
在程序流程返回到事件调度循环之前不会生效。
编辑: 而不是
useRobotToMakeScreenshot();
写
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
useRobotToMakeScreenshot();
}
}
(当然,您必须将useRobotToMakeScreenshot()
替换为执行屏幕检测的方法的实际调用)