Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

Ex No.

28
Date:
Generating Screenshot
Aim:
To write a java program to capture the screenshot of your monitor using
interactive GUI.
Source Code:
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class Screenshot {
public static void main(String[] args) throws Exception {
Screenshot ss = new Screenshot();
}
public Screenshot(){
JFrame frame = new JFrame("Screen Shot Frame.");
JButton button = new JButton("Capture Screen Shot");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent ae){
try{
String fileName = JOptionPane.showInputDialog(nu
ll, "Enter file name : ", "Screencapture", 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Err
or: file name must end with \".gif\".", "Screencapture", 1);
}
else{
Robot robot = new Robot();
BufferedImage image = robot.createScreen
Capture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "gif", new File(fil
eName));
JOptionPane.showMessageDialog(null, "Scr
een captured successfully.", "Screencapture", 1);
}
}
catch(Exception e){}
}
}
}
Output:
Javac Screenshot.java
Java Screenshot
Result:
Thus a java program has been written to capture the screenshot of the mo
nitor.

You might also like