Java programming screenshot of screenshot code summary

  • 2020-04-01 04:23:00
  • OfStack

This example summarizes the common methods of implementing screenshots in Java programming. Share with you for your reference, as follows:

Method one:


import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class CaptureScreen {
 public static void captureScreen(String fileName, String folder) throws Exception {
  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  Rectangle screenRectangle = new Rectangle(screenSize);
  Robot robot = new Robot();
  BufferedImage image = robot.createScreenCapture(screenRectangle);
  //Save the path
  File screenFile = new File(fileName);
  if (!screenFile.exists()) {
   screenFile.mkdir();
  }
  File f = new File(screenFile, folder);
  ImageIO.write(image, "png", f);
  //Automatically open
  if (Desktop.isDesktopSupported()
     && Desktop.getDesktop().isSupported(Desktop.Action.OPEN))
     Desktop.getDesktop().open(f);
 }
 public static void main(String[] args) {
  try {
   captureScreen("e:\ hello ","11.png");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Method 2:


package com.qiu.util;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;

public class ScreenCapture {
  // test main
  public static void main(String[] args) throws Exception {
    String userdir = System.getProperty("user.dir");
    File tempFile = new File("d:", "temp.png");
    ScreenCapture capture = ScreenCapture.getInstance();
    capture.captureImage();
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    JLabel imagebox = new JLabel();
    panel.add(BorderLayout.CENTER, imagebox);
    imagebox.setIcon(capture.getPickedIcon());
    capture.saveToFile(tempFile);
    capture.captureImage();
    imagebox.setIcon(capture.getPickedIcon());
    frame.setContentPane(panel);
    frame.setSize(400, 300);
    frame.show();
    System.out.println("Over");
  }
  private ScreenCapture() {
    try {
      robot = new Robot();
    } catch (AWTException e) {
      System.err.println("Internal Error: " + e);
      e.printStackTrace();
    }
    JPanel cp = (JPanel) dialog.getContentPane();
    cp.setLayout(new BorderLayout());
    labFullScreenImage.addMouseListener(new MouseAdapter() {
      public void mouseReleased(MouseEvent evn) {
        isFirstPoint = true;
        pickedImage = fullScreenImage.getSubimage(recX, recY, recW,
            recH);
        dialog.setVisible(false);
      }
    });
    labFullScreenImage.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent evn) {
        if (isFirstPoint) {
          x1 = evn.getX();
          y1 = evn.getY();
          isFirstPoint = false;
        } else {
          x2 = evn.getX();
          y2 = evn.getY();
          int maxX = Math.max(x1, x2);
          int maxY = Math.max(y1, y2);
          int minX = Math.min(x1, x2);
          int minY = Math.min(y1, y2);
          recX = minX;
          recY = minY;
          recW = maxX - minX;
          recH = maxY - minY;
          labFullScreenImage.drawRectangle(recX, recY, recW, recH);
        }
      }
      public void mouseMoved(MouseEvent e) {
        labFullScreenImage.drawCross(e.getX(), e.getY());
      }
    });
    cp.add(BorderLayout.CENTER, labFullScreenImage);
    dialog.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    dialog.setAlwaysOnTop(true);
    dialog.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize());
    dialog.setUndecorated(true);
    dialog.setSize(dialog.getMaximumSize());
    dialog.setModal(true);
  }
  // Singleton Pattern
  public static ScreenCapture getInstance() {
    return defaultCapturer;
  }
  
  public Icon captureFullScreen() {
    fullScreenImage = robot.createScreenCapture(new Rectangle(Toolkit
        .getDefaultToolkit().getScreenSize()));
    ImageIcon icon = new ImageIcon(fullScreenImage);
    return icon;
  }
  
  public void captureImage() {
    fullScreenImage = robot.createScreenCapture(new Rectangle(Toolkit
        .getDefaultToolkit().getScreenSize()));
    ImageIcon icon = new ImageIcon(fullScreenImage);
    labFullScreenImage.setIcon(icon);
    dialog.setVisible(true);
  }
  
  public BufferedImage getPickedImage() {
    return pickedImage;
  }
  
  public ImageIcon getPickedIcon() {
    return new ImageIcon(getPickedImage());
  }
  
  @Deprecated
  public void saveToFile(File file) throws IOException {
    ImageIO.write(getPickedImage(), defaultImageFormater, file);
  }
  
  public void saveAsPNG(File file) throws IOException {
    ImageIO.write(getPickedImage(), "png", file);
  }
  
  public void saveAsJPEG(File file) throws IOException {
    ImageIO.write(getPickedImage(), "JPEG", file);
  }
  
  public void write(OutputStream out) throws IOException {
    ImageIO.write(getPickedImage(), defaultImageFormater, out);
  }
  // singleton design pattern
  private static ScreenCapture defaultCapturer = new ScreenCapture();
  private int x1, y1, x2, y2;
  private int recX, recY, recH, recW; //Captured image
  private boolean isFirstPoint = true;
  private BackgroundImage labFullScreenImage = new BackgroundImage();
  private Robot robot;
  private BufferedImage fullScreenImage;
  private BufferedImage pickedImage;
  private String defaultImageFormater = "png";
  private JDialog dialog = new JDialog();
}

class BackgroundImage extends JLabel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(x, y, w, h);
    String area = Integer.toString(w) + " * " + Integer.toString(h);
    g.drawString(area, x + (int) w / 2 - 15, y + (int) h / 2);
    g.drawLine(lineX, 0, lineX, getHeight());
    g.drawLine(0, lineY, getWidth(), lineY);
  }
  public void drawRectangle(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    h = height;
    w = width;
    repaint();
  }
  public void drawCross(int x, int y) {
    lineX = x;
    lineY = y;
    repaint();
  }
  int lineX, lineY;
  int x, y, h, w;
}

Method 3:

Since there is a minimum to the system tray, we still need a tray icon named bg.gif, the picture should be placed in the same directory, otherwise the null pointer will be abnormal.

The main screenshots of the code are:


Robot ro=new Robot();
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension di=tk.getScreenSize();
Rectangle rec=new Rectangle(0,0,di.width,di.height);
BufferedImage bi=ro.createScreenCapture(rec);

(source code from CSDN)


import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class CaptureScreen extends JFrame implements ActionListener{
 private JButton start,cancel,saveAll;
 private JPanel c;
 private BufferedImage get;
 private JTabbedPane jtp;//Put many pictures in one place
 private int index;//An index that always increments to identify images
 private JRadioButton java,system;//JAVA interface, system interface
 
 public CaptureScreen() {
  super(" Screen capture software ( The third edition )");
  try{
   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  }catch(Exception exe){
   exe.printStackTrace();
  }
  initWindow();
  initOther();
  initTrayIcon();
 }
 private void initOther(){
  jtp=new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
 }
 private void initWindow(){
  start=new JButton(" Began to intercept ");
  saveAll=new JButton(" Save all ");
  cancel=new JButton(" exit ");
  start.addActionListener(this);
  saveAll.addActionListener(this);
  cancel.addActionListener(this);
  JPanel buttonJP=new JPanel();
  c=new JPanel(new BorderLayout());
  c.setBackground(Color.BLACK);
  JLabel jl=new JLabel(" The screen capture ",JLabel.CENTER);
  jl.setFont(new Font(" blackbody ",Font.BOLD,40));
  jl.setForeground(Color.RED);
  c.add(jl,BorderLayout.CENTER);
  buttonJP.add(start);
  buttonJP.add(saveAll);
  buttonJP.add(cancel);
  buttonJP.setBorder(BorderFactory.createTitledBorder(" Common operating area "));
  JPanel jp=new JPanel();//Panel for two radio buttons
  jp.add(java=new JRadioButton("java interface "));
  jp.add(system=new JRadioButton(" The system interface ",true));
  java.addActionListener(this);
  system.addActionListener(this);
  jp.setBorder(BorderFactory.createTitledBorder(" Interface style "));
  ButtonGroup bg=new ButtonGroup();
  bg.add(java);
  bg.add(system);
  JPanel all=new JPanel();
  all.add(jp);
  all.add(buttonJP);
  this.getContentPane().add(c,BorderLayout.CENTER);
  this.getContentPane().add(all,BorderLayout.SOUTH);
  this.setSize(500,400);
  this.setLocationRelativeTo(null);
  this.setVisible(true);
  this.setAlwaysOnTop(true);
  this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  this.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent we){
    CaptureScreen.this.setVisible(false);
   }
  });
 }
 private void initTrayIcon(){
  try{
   SystemTray st=SystemTray.getSystemTray();
   Image im=ImageIO.read(this.getClass().getResource("bg.gif"));
   PopupMenu pm=new PopupMenu(" The popup menu ");
   pm.add(new MenuItem(" about ")).addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
     JOptionPane.showMessageDialog(CaptureScreen.this,"<html><Font color=red><center><h2> about </h2></center></Font>" +
       " This is a pure one JAVA Screen interceptor <br> Some common functions have been added on the basis of the previous ones ,<br>" +
       " Such as , Batch saving , Multiple image capture , Copy to system sticker board ...<br>" +
       " There are any problems during use , Welcome to contact .<br>" +
       "<Font size=5 color=blue> The author : freeze <br>" +
       "<i>QQ:24325142</i><br></Font></html>");
    }
   });
   pm.addSeparator();
   pm.add(new MenuItem(" Display main window ")).addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
     CaptureScreen.this.setVisible(true);
    }
   });
   pm.add(new MenuItem(" Began to intercept ")).addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
     doStart();
    }
   });
   pm.add(new MenuItem(" Exit the program ")).addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
     System.exit(0);
    }
   });
   TrayIcon ti=new TrayIcon(im,"JAVA The screen capture ",pm);
   st.add(ti);
   ti.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
     CaptureScreen.this.setVisible(true);
    }
   });
  }catch(Exception exe){
   exe.printStackTrace();
  }
 }
 private void updates(){
  this.setVisible(true);
  if(get!=null){
   //If the index is zero, then none of the images have been added,
   //Clear the current thing and put the tabpane back in
   if(index==0){
    c.removeAll();
    c.add(jtp,BorderLayout.CENTER);
   }else{//Otherwise, simply add the panel to the tabpane
    //You don't have to do anything
   }
   PicPanel pic=new PicPanel(get);
   jtp.addTab(" The picture "+(++index),pic);
   jtp.setSelectedComponent(pic);
   SwingUtilities.updateComponentTreeUI(c);
  }
 }
 private void doStart(){
  try{
   this.setVisible(false);
   Thread.sleep(500);//500 milliseconds to make the main window disappear completely
   Robot ro=new Robot();
   Toolkit tk=Toolkit.getDefaultToolkit();
   Dimension di=tk.getScreenSize();
   Rectangle rec=new Rectangle(0,0,di.width,di.height);
   BufferedImage bi=ro.createScreenCapture(rec);
   JFrame jf=new JFrame();
   Temp temp=new Temp(jf,bi,di.width,di.height);
   jf.getContentPane().add(temp,BorderLayout.CENTER);
   jf.setUndecorated(true);
   jf.setSize(di);
   jf.setVisible(true);
   jf.setAlwaysOnTop(true);
  } catch(Exception exe){
   exe.printStackTrace();
  }
 }
 
 public void doSaveAll(){
  if(jtp.getTabCount()==0){
   JOptionPane.showMessageDialog(this," The picture cannot be empty !!"," error ",JOptionPane.ERROR_MESSAGE);
   return;
  }
  JFileChooser jfc=new JFileChooser(".");
  jfc.addChoosableFileFilter(new GIFfilter());
  jfc.addChoosableFileFilter(new BMPfilter());
  jfc.addChoosableFileFilter(new JPGfilter());
  jfc.addChoosableFileFilter(new PNGfilter());
  int i=jfc.showSaveDialog(this);
  if(i==JFileChooser.APPROVE_OPTION){
   File file=jfc.getSelectedFile();
   String about="PNG";
   String ext=file.toString().toLowerCase();
   javax.swing.filechooser.FileFilter ff=jfc.getFileFilter();
   if(ff instanceof JPGfilter){
    about="JPG";
   } else if(ff instanceof PNGfilter){
    about="PNG";
   }else if(ff instanceof BMPfilter){
    about="BMP";
   }else if(ff instanceof GIFfilter){
    about="GIF";
   }
   if(ext.endsWith(about.toLowerCase())){
    ext=ext.substring(0,ext.lastIndexOf(about.toLowerCase()));
   }
   //Start a thread to save the images and display the progress bar
   new SaveAllThread(ext,about).setVisible(true);
  }
 }
 //A thread class that is dedicated to saving all images, and it also displays the saved progress bar
 private class SaveAllThread extends JDialog implements Runnable{
  private String name;//Filename header
  private String ext;//The file format
  private JProgressBar jpb;//A progress bar
  private JLabel info;//A message display bar
  private int allTask,doneTask;//All tasks completed
  public SaveAllThread(String name,String ext){
   super(CaptureScreen.this," save ",true);
   this.name=name;
   this.ext=ext;
   initWindow();
  }
  private void initWindow(){
   jpb=new JProgressBar();
   allTask=jtp.getTabCount();
   jpb.setMaximum(allTask);
   jpb.setMinimum(0);
   jpb.setValue(0);
   jpb.setStringPainted(true);
   setProgressBarString();
   info=new JLabel(" Saving to :");
   this.getContentPane().setBackground(Color.CYAN);
   this.add(info,BorderLayout.NORTH);
   this.add(jpb,BorderLayout.SOUTH);
   this.setUndecorated(true);
   this.setSize(300,100);
   this.setLocationRelativeTo(CaptureScreen.this);
   new Thread(this).start();
  }
  private void setProgressBarString(){
   jpb.setString(""+doneTask+"/"+allTask);
  }
  public void run(){
   try{
    for(int i=0;i<allTask;i++){
     PicPanel pp=(PicPanel)jtp.getComponentAt(i);
     BufferedImage image=pp.getImage();
     File f= new File(name+(doneTask+1)+"."+ext.toLowerCase());
     info.setText("<html><b> Saving to :</b><br>"+f.toString()+"</html>");
     ImageIO.write(image,ext,f);
     doneTask++;
     jpb.setValue(doneTask);
     setProgressBarString();
     Thread.sleep(500);
    }
    JOptionPane.showMessageDialog(this," Save the finished !!");
    this.dispose();
   }catch(Exception exe){
    exe.printStackTrace();
    this.dispose();
   }
  }
 }
 
 public void doSave(BufferedImage get){
  try{
   if(get==null){
    JOptionPane.showMessageDialog(this," The picture cannot be empty !!"," error ",JOptionPane.ERROR_MESSAGE);
    return;
   }
   JFileChooser jfc=new JFileChooser(".");
   jfc.addChoosableFileFilter(new GIFfilter());
   jfc.addChoosableFileFilter(new BMPfilter());
   jfc.addChoosableFileFilter(new JPGfilter());
   jfc.addChoosableFileFilter(new PNGfilter());
   int i=jfc.showSaveDialog(this);
   if(i==JFileChooser.APPROVE_OPTION){
    File file=jfc.getSelectedFile();
    String about="PNG";
    String ext=file.toString().toLowerCase();
    javax.swing.filechooser.FileFilter ff=jfc.getFileFilter();
    if(ff instanceof JPGfilter){
     about="JPG";
     if(!ext.endsWith(".jpg")){
      String ns=ext+".jpg";
      file=new File(ns);
     }
    } else if(ff instanceof PNGfilter){
     about="PNG";
     if(!ext.endsWith(".png")){
      String ns=ext+".png";
      file=new File(ns);
     }
    }else if(ff instanceof BMPfilter){
     about="BMP";
     if(!ext.endsWith(".bmp")){
      String ns=ext+".bmp";
      file=new File(ns);
     }
    }else if(ff instanceof GIFfilter){
     about="GIF";
     if(!ext.endsWith(".gif")){
      String ns=ext+".gif";
      file=new File(ns);
     }
    }
    if(ImageIO.write(get,about,file)){
     JOptionPane.showMessageDialog(this," Save successful! ");
    } else
     JOptionPane.showMessageDialog(this," Save failed! ");
   }
  } catch(Exception exe){
   exe.printStackTrace();
  }
 }
 
 public void doCopy(final BufferedImage image){
  try{
   if(get==null){
    JOptionPane.showMessageDialog(this," The picture cannot be empty !!"," error ",JOptionPane.ERROR_MESSAGE);
    return;
   }
   Transferable trans = new Transferable(){
    public DataFlavor[] getTransferDataFlavors() {
     return new DataFlavor[] { DataFlavor.imageFlavor };
    }
    public boolean isDataFlavorSupported(DataFlavor flavor) {
     return DataFlavor.imageFlavor.equals(flavor);
    }
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
     if(isDataFlavorSupported(flavor))
      return image;
     throw new UnsupportedFlavorException(flavor);
    }
   };
   Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
   JOptionPane.showMessageDialog(this," Copied to system sticker board !!");
  }catch(Exception exe){
   exe.printStackTrace();
   JOptionPane.showMessageDialog(this," Error copying to system sticker board !!"," error ",JOptionPane.ERROR_MESSAGE);
  }
 }
 //Handle shutdown events
 private void doClose(Component c){
  jtp.remove(c);
  c=null;
  System.gc();
 }
 public void actionPerformed(ActionEvent ae){
  Object source=ae.getSource();
  if(source==start){
   doStart();
  } else if(source==cancel){
   System.exit(0);
  }else if(source==java){
   try{
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    SwingUtilities.updateComponentTreeUI(this);
   }catch(Exception exe){
    exe.printStackTrace();
   }
  }else if(source==system){
   try{
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    SwingUtilities.updateComponentTreeUI(this);
   }catch(Exception exe){
    exe.printStackTrace();
   }
  }else if(source==saveAll){
   doSaveAll();
  }
 }
 //An inner class that represents a panel, a panel that can be put into a tabpane
 //It also has its own set of methods for handling preservation and replication
 private class PicPanel extends JPanel implements ActionListener{
  JButton save,copy,close;//Save, copy, close button
  BufferedImage get;//The resulting picture
  public PicPanel(BufferedImage get){
   super(new BorderLayout());
   this.get=get;
   initPanel();
  }
  public BufferedImage getImage(){
   return get;
  }
  private void initPanel(){
   save=new JButton(" save (S)");
   copy=new JButton(" Copy to clipping board (C)");
   close=new JButton(" Shut down (X)");
   save.setMnemonic('S');
   copy.setMnemonic('C');
   close.setMnemonic('X');
   JPanel buttonPanel=new JPanel();
   buttonPanel.add(copy);
   buttonPanel.add(save);
   buttonPanel.add(close);
   JLabel icon=new JLabel(new ImageIcon(get));
   this.add(new JScrollPane(icon),BorderLayout.CENTER);
   this.add(buttonPanel,BorderLayout.SOUTH);
   save.addActionListener(this);
   copy.addActionListener(this);
   close.addActionListener(this);
  }
  public void actionPerformed(ActionEvent e) {
   Object source=e.getSource();
   if(source==save){
    doSave(get);
   }else if(source==copy){
    doCopy(get);
   }else if(source==close){
    get=null;
    doClose(this);
   }
  }
 }
 //Save the filter in the BMP format
 private class BMPfilter extends javax.swing.filechooser.FileFilter{
  public BMPfilter(){
  }
  public boolean accept(File file){
   if(file.toString().toLowerCase().endsWith(".bmp")||
     file.isDirectory()){
    return true;
   } else
    return false;
  }
  public String getDescription(){
   return "*.BMP(BMP image )";
  }
 }
 //Save the JPG filter
 private class JPGfilter extends javax.swing.filechooser.FileFilter{
  public JPGfilter(){
  }
  public boolean accept(File file){
   if(file.toString().toLowerCase().endsWith(".jpg")||
     file.isDirectory()){
    return true;
   } else
    return false;
  }
  public String getDescription(){
   return "*.JPG(JPG image )";
  }
 }
 //Save the filter in GIF format
 private class GIFfilter extends javax.swing.filechooser.FileFilter{
  public GIFfilter(){
  }
  public boolean accept(File file){
   if(file.toString().toLowerCase().endsWith(".gif")||
     file.isDirectory()){
    return true;
   } else
    return false;
  }
  public String getDescription(){
   return "*.GIF(GIF image )";
  }
 }
 //Save the filter in PNG format
 private class PNGfilter extends javax.swing.filechooser.FileFilter{
  public boolean accept(File file){
   if(file.toString().toLowerCase().endsWith(".png")||
     file.isDirectory()){
    return true;
   } else
    return false;
  }
  public String getDescription(){
   return "*.PNG(PNG image )";
  }
 }
 //A temporary class that displays the current screen image
 private class Temp extends JPanel implements MouseListener,MouseMotionListener{
  private BufferedImage bi;
  private int width,height;
  private int startX,startY,endX,endY,tempX,tempY;
  private JFrame jf;
  private Rectangle select=new Rectangle(0,0,0,0);//Represents the selected area
  private Cursor cs=new Cursor(Cursor.CROSSHAIR_CURSOR);//Represents the mouse state in general
  private States current=States.DEFAULT;//Represents the current edit status
  private Rectangle[] rec;//An area that represents eight edit points
  //The following four constants represent who is the endpoint of the selected line
  public static final int START_X=1;
  public static final int START_Y=2;
  public static final int END_X=3;
  public static final int END_Y=4;
  private int currentX,currentY;//The only ones that need to change are the currently selected X and Y
  private Point p=new Point();//The current mouseover location
  private boolean showTip=true;//If the left mouse button is pressed, the prompt is no longer displayed
  public Temp(JFrame jf,BufferedImage bi,int width,int height){
   this.jf=jf;
   this.bi=bi;
   this.width=width;
   this.height=height;
   this.addMouseListener(this);
   this.addMouseMotionListener(this);
   initRecs();
  }
  private void initRecs(){
   rec=new Rectangle[8];
   for(int i=0;i<rec.length;i++){
    rec[i]=new Rectangle();
   }
  }
  public void paintComponent(Graphics g){
   g.drawImage(bi,0,0,width,height,this);
   g.setColor(Color.RED);
   g.drawLine(startX,startY,endX,startY);
   g.drawLine(startX,endY,endX,endY);
   g.drawLine(startX,startY,startX,endY);
   g.drawLine(endX,startY,endX,endY);
   int x=startX<endX?startX:endX;
   int y=startY<endY?startY:endY;
   select=new Rectangle(x,y,Math.abs(endX-startX),Math.abs(endY-startY));
   int x1=(startX+endX)/2;
   int y1=(startY+endY)/2;
   g.fillRect(x1-2,startY-2,5,5);
   g.fillRect(x1-2,endY-2,5,5);
   g.fillRect(startX-2,y1-2,5,5);
   g.fillRect(endX-2,y1-2,5,5);
   g.fillRect(startX-2,startY-2,5,5);
   g.fillRect(startX-2,endY-2,5,5);
   g.fillRect(endX-2,startY-2,5,5);
   g.fillRect(endX-2,endY-2,5,5);
   rec[0]=new Rectangle(x-5,y-5,10,10);
   rec[1]=new Rectangle(x1-5,y-5,10,10);
   rec[2]=new Rectangle((startX>endX?startX:endX)-5,y-5,10,10);
   rec[3]=new Rectangle((startX>endX?startX:endX)-5,y1-5,10,10);
   rec[4]=new Rectangle((startX>endX?startX:endX)-5,(startY>endY?startY:endY)-5,10,10);
   rec[5]=new Rectangle(x1-5,(startY>endY?startY:endY)-5,10,10);
   rec[6]=new Rectangle(x-5,(startY>endY?startY:endY)-5,10,10);
   rec[7]=new Rectangle(x-5,y1-5,10,10);
   if(showTip){
    g.setColor(Color.CYAN);
    g.fillRect(p.x,p.y,170,20);
    g.setColor(Color.RED);
    g.drawRect(p.x,p.y,170,20);
    g.setColor(Color.BLACK);
    g.drawString(" Please hold down the left mouse button to select the screenshot area ",p.x,p.y+15);
   }
  }
  //The X and Y coordinates selected to be modified are determined according to the eight directions of the southeast and northwest
  private void initSelect(States state){
   switch(state){
    case DEFAULT:
     currentX=0;
     currentY=0;
     break;
    case EAST:
     currentX=(endX>startX?END_X:START_X);
     currentY=0;
     break;
    case WEST:
     currentX=(endX>startX?START_X:END_X);
     currentY=0;
     break;
    case NORTH:
     currentX=0;
     currentY=(startY>endY?END_Y:START_Y);
     break;
    case SOUTH:
     currentX=0;
     currentY=(startY>endY?START_Y:END_Y);
     break;
    case NORTH_EAST:
     currentY=(startY>endY?END_Y:START_Y);
     currentX=(endX>startX?END_X:START_X);
     break;
    case NORTH_WEST:
     currentY=(startY>endY?END_Y:START_Y);
     currentX=(endX>startX?START_X:END_X);
     break;
    case SOUTH_EAST:
     currentY=(startY>endY?START_Y:END_Y);
     currentX=(endX>startX?END_X:START_X);
     break;
    case SOUTH_WEST:
     currentY=(startY>endY?START_Y:END_Y);
     currentX=(endX>startX?START_X:END_X);
     break;
    default:
     currentX=0;
     currentY=0;
     break;
   }
  }
  public void mouseMoved(MouseEvent me){
   doMouseMoved(me);
   initSelect(current);
   if(showTip){
    p=me.getPoint();
    repaint();
   }
  }
  //A method is specifically defined to handle mouse movement so that the selected locale can be initialized each time
  private void doMouseMoved(MouseEvent me){
   if(select.contains(me.getPoint())){
    this.setCursor(new Cursor(Cursor.MOVE_CURSOR));
    current=States.MOVE;
   } else{
    States[] st=States.values();
    for(int i=0;i<rec.length;i++){
     if(rec[i].contains(me.getPoint())){
      current=st[i];
      this.setCursor(st[i].getCursor());
      return;
     }
    }
    this.setCursor(cs);
    current=States.DEFAULT;
   }
  }
  public void mouseExited(MouseEvent me){
  }
  public void mouseEntered(MouseEvent me){
  }
  public void mouseDragged(MouseEvent me){
   int x=me.getX();
   int y=me.getY();
   if(current==States.MOVE){
    startX+=(x-tempX);
    startY+=(y-tempY);
    endX+=(x-tempX);
    endY+=(y-tempY);
    tempX=x;
    tempY=y;
   }else if(current==States.EAST||current==States.WEST){
    if(currentX==START_X){
     startX+=(x-tempX);
     tempX=x;
    }else{
     endX+=(x-tempX);
     tempX=x;
    }
   }else if(current==States.NORTH||current==States.SOUTH){
    if(currentY==START_Y){
     startY+=(y-tempY);
     tempY=y;
    }else{
     endY+=(y-tempY);
     tempY=y;
    }
   }else if(current==States.NORTH_EAST||current==States.NORTH_EAST||
     current==States.SOUTH_EAST||current==States.SOUTH_WEST){
    if(currentY==START_Y){
     startY+=(y-tempY);
     tempY=y;
    }else{
     endY+=(y-tempY);
     tempY=y;
    }
    if(currentX==START_X){
     startX+=(x-tempX);
     tempX=x;
    }else{
     endX+=(x-tempX);
     tempX=x;
    }
   }else{
    startX=tempX;
    startY=tempY;
    endX=me.getX();
    endY=me.getY();
   }
   this.repaint();
  }
  public void mousePressed(MouseEvent me){
   showTip=false;
   tempX=me.getX();
   tempY=me.getY();
  }
  public void mouseReleased(MouseEvent me){
   if(me.isPopupTrigger()){
    if(current==States.MOVE){
     showTip=true;
     p=me.getPoint();
     startX=0;
     startY=0;
     endX=0;
     endY=0;
     repaint();
    } else{
     jf.dispose();
     updates();
    }
   }
  }
  public void mouseClicked(MouseEvent me){
   if(me.getClickCount()==2){
    //Rectangle rec=new Rectangle(startX,startY,Math.abs(endX-startX),Math.abs(endY-startY));
    Point p=me.getPoint();
    if(select.contains(p)){
     if(select.x+select.width<this.getWidth()&&select.y+select.height<this.getHeight()){
      get=bi.getSubimage(select.x,select.y,select.width,select.height);
      jf.dispose();
      updates();
     }else{
      int wid=select.width,het=select.height;
      if(select.x+select.width>=this.getWidth()){
       wid=this.getWidth()-select.x;
      }
      if(select.y+select.height>=this.getHeight()){
       het=this.getHeight()-select.y;
      }
      get=bi.getSubimage(select.x,select.y,wid,het);
      jf.dispose();
      updates();
     }
    }
   }
  }
 }
 public static void main(String args[]){
  SwingUtilities.invokeLater(new Runnable(){
   public void run(){
    new CaptureScreen();
   }
  });
 }
}
//Some enumerations that represent states
enum States{
 NORTH_WEST(new Cursor(Cursor.NW_RESIZE_CURSOR)),//Northwest corner
 NORTH(new Cursor(Cursor.N_RESIZE_CURSOR)),
 NORTH_EAST(new Cursor(Cursor.NE_RESIZE_CURSOR)),
 EAST(new Cursor(Cursor.E_RESIZE_CURSOR)),
 SOUTH_EAST(new Cursor(Cursor.SE_RESIZE_CURSOR)),
 SOUTH(new Cursor(Cursor.S_RESIZE_CURSOR)),
 SOUTH_WEST(new Cursor(Cursor.SW_RESIZE_CURSOR)),
 WEST(new Cursor(Cursor.W_RESIZE_CURSOR)),
 MOVE(new Cursor(Cursor.MOVE_CURSOR)),
 DEFAULT(new Cursor(Cursor.DEFAULT_CURSOR));
 private Cursor cs;
 States(Cursor cs){
  this.cs=cs;
 }
 public Cursor getCursor(){
  return cs;
 }
}

I hope this article has been helpful to you in Java programming.


Related articles: