我有一个小问题,我真的不知道如何解决,基本上我想拍摄我的桌面的截图(使用"机器人"类),不包括实际的程序GUI组件.最初我相信它可以通过临时隐藏组件来完成,但每次制作新的屏幕截图时,组件都包含在图像中.
这是截取的按钮的actionPerformed方法中包含的块:
if (command.equals("zoom")) { setComponentVisability(false);//try to hide the components from the robot zt.screenShoot();//take the screenshot setComponentVisability(true);//show the components }
"zt.screenShoot"获取屏幕截图并将其返回到新的JFrame(用于调试),在我的主框架中我正在使用
com.sun.awt.AWTUtilities.setWindowOpaque(systemWindow, false);
使背景透明的方法; 不确定这是否与此问题有关.
任何帮助都会很棒,谢谢
在隐藏组件和截屏之间使用短暂的延迟.
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; class TestScreenshot { static JLabel screenshot; public static void main(String[] args) throws Exception { final Robot robot = new Robot(); SwingUtilities.invokeLater( new Runnable() { public void run() { final JFrame f = new JFrame("Screenshot"); JPanel gui = new JPanel(new BorderLayout(3,3)); gui.setBorder(new EmptyBorder(5,5,5,5)); f.setContentPane(gui); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); screenshot = new JLabel(); JScrollPane scroll = new JScrollPane(screenshot); scroll.setPreferredSize(new Dimension(800,600)); gui.add(scroll, BorderLayout.CENTER); final ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent ae) { Rectangle screenSize = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize()); Image image = robot.createScreenCapture(screenSize); setImage(image); f.setVisible(true); } }; JButton grabScreen = new JButton("Grab Screen"); grabScreen.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae) { f.setVisible(false); Timer timer = new Timer(400, al); timer.setRepeats(false); timer.start(); } } ); gui.add(grabScreen, BorderLayout.SOUTH); f.pack(); f.setLocationByPlatform(true); f.setVisible(true); } }); } public static void setImage(Image image) { screenshot.setIcon(new ImageIcon(image)); } }