Looking for useful code examples to build your Java applications?
A screenshot, screen capture (or screen-cap) is an image taken by a user to record the visible items displayed on the monitor, television, or other visual output device in use.
In this example we wrote an application that user can take the screenshot of his/her computer screen by simply pressing a button.
/**
* Author : Berk Soysal
* CaptureScreenshot.java
*/
package herrberk;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class CaptureScreenshot {
public static void capture(String fileName) throws Exception {
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
} catch (Exception e) {
System.out.println("Error: cannot capture");
}
}
}
/**
* Author : Berk Soysal
* DrawButton.java
*/
package herrberk;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawButton extends JFrame implements ActionListener {
private JPanel panel = new JPanel();
private JButton button = new JButton("Take A Snapshot !");
public DrawButton(){
panel.add(button);
add(panel);
panel.setBackground(Color.BLACK);
setTitle("Berk's ScreenShot Program");
button.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == button) {
try {
// You need to modify the image directory
CaptureScreenshot.capture("C:\\Users\\Herrberk\\Desktop\\Screenshot.png");
System.out.println("Capture Successful !");
} catch (Exception e1) {
e1.printStackTrace();
}
}
else System.out.println("Error in Button");
}
public static void main(String args[]) throws Exception{
DrawButton db = new DrawButton();
db.setVisible(true);
db.setSize(260,80);
db.setLocation(650, 300);
}
}
If you do everything right the result should be like the figure below;
Please comment below if you have any questions. Thanks.
Continue Reading Useful Java Code Snippets 7 - Animated GIF on JFrame
Disqus Comments Loading..