This article summarizes common Java programming implementation screenshot methods. Share it for your reference, as follows:
Method 1:
import java.awt.Desktop;import java.awt.Dimension;import java.awt.Rectangle;import java.awt.Robot;import java.awt.Toolkit;import java.aww t.image.BufferedImage;import java.io.File ;import javax.imageio.ImageIO;public class CaptureScreen { public static void captureScreen(String fileName, String folder) throws Exception { Dimens ion screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize); Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(screenRectangle); //Save path File screenFile = new File(fileName); if (!screenFile.exists()) { screenFile.mkdir(); } File f = new File(screenFile, folder); ImageIO.write(image, "png", f); //Open automatically if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desk top.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.*;im port javax.imageio .*;/** * A simple screen capture* **/public class ScreenCapture { // test main public static void main(String[] args) throws Exception { String userdir = Systeme m.getProperty("user.dir" ); File tempFile = new File("d:", "temp.png"); ScreenCapture capture = ScreenCapture.getInstance(); capture.captureImage(); JFrame frame = new JFram e(); JPanel panel = new JPanel() ; panel.setLayout(new BorderLayout()); JLabel imagebox = new JLabel(); panel.add(BorderLayout.CENTER, imagebox); imagebox.setIcon(capture.getPi ckedIcon()); 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(MouseEven t evn) { isFirstPoint = true; pickedImage = fullScreenImage.getSubimage(recX, recY, recW, recH); dialog.setVisible(false); } }); labFullScreenImage.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e vn) { 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(rec X, recY, recW, recH); } } public void mouseMoved(MouseEvent e) { labFullScreenImage.drawCross(e.getX(), e.getY()); } }); cp.add(BorderLayout.CENTER, la bFullScreenImage); dialog.setCursor(Cursor .getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); dialog.setAlwaysOnTop(true); dialog.setMaximumSize(Toolkit.getDefaultToolkit().get ScreenSize()); dialog.setUndecorated(true); dialog.setSize(dialog.getMaximumSize()); dialog .setModal(true); } // Singleton Pattern public static ScreenCapture getInstance() { return defaultCapturer; } /** Capture full screen*/ public Icon captureFullSc reen() { fullScreenImage = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit() .getScreenSize())); ImageIcon icon = new ImageIcon(fullScreenImage); return icon; } /** Capture an orthopedic area of the screen*/ public void captureImage() { fullSc reenImage = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit( ).getScreenSize())); ImageIcon icon = new ImageIcon(fullScreenImage); labFullScreenImage.setIcon(icon); dialog.setVisible(true); } /** Get caught BufferedImage after capture */ public BufferedImage getPickedImage() { return pickedImage ; } /** Get the captured Icon */ public ImageIcon getPickedIcon() { return new ImageIcon(getPickedImage()); } /** * Save as a file, in PNG format * * @deprecat ed replaced by saveAsPNG(File file ) **/ @Deprecated public void saveToFile(File file) throws IOException { ImageIO.write(getPickedImage(), defaultImageFormater, file); } /** Save For a file, in PNG format */ public void saveAsPNG(File file) throws IOException { ImageIO.write(getPickedImage(), "png", file); } /** Save as a JPEG format image file*/ public void saveAsJPEG(File file) throws IOE xception { ImageIO.write(getPickedImage(), " JPEG", file); } /** Write an OutputStream */ public void write(OutputStream out) throws IOException { ImageIO.write(getPickedImage(), defaultIma geFormater, out); } // singleton design pattern private static ScreenCapture defaultCapturer = new ScreenCapture(); private int x1, y1, x2, y2; private int recX, recY, recH, recW; // Intercepted image private boolean isFirstPoint = true; private Backgrou ndImage labFullScreenImage = new BackgroundImage(); private Robot robot; private BufferedImage fullScreenImage; private BufferedImage pickedImage; private String defaultImageFormater = "png"; private JDialog dialog = new JDial og();}/** Label showing the picture */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:
Because it is minimized to the system pallet, a pallet icon is still needed. The image should be placed in the same directory, otherwise the pointer will be an exception.
The main screenshot code part is:
Robot ro=new Robot();Toolkit tk=Toolkit.getDefaultToolkit();Dimension di=tk.getScreenSize();Rectangle rec=new Rectangle(0,0,di.widt h,di.height);BufferedImage bi=ro. createScreenCapture(rec);
(Source code is from CSDN)
import java.awt.*;import java.awt.datatransfer.DataFlavor;import java.awt.datatransfer.Transferable;import java.awt.datatransfer.UnsupportedFlavorE xception;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 J Button start,cancel,saveAll; private JPanel c; private BufferedImage get; private JTabbedPane jtp ;//A single place many pictures private int index;//A index that will always increase, used to identify pictures private JRadioButton java,system;//JAVA interface, system interface/** Creates a new instance of CaptureScreen */ : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : public CaptureScreen() { super("Screen Capture Software (Third Edition)"); try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Excepti on exe){ exe.printStackTrace(); } initWindow(); initOther(); initTrayIcon(); } private void initOther(){ jtp=new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT); } private void initWindow(){ start=new JButton("Start intercept"); saveAll=new JButton("Save all"); cancel=new JButton("Exit"); start.addActionListener(this); saveAll.addActionListener(this); cancel.addActionListener(this); JPanel b uttonJP=new JPanel(); c=new JPanel(new BorderLayout()); c.setBackground(Color.BLACK); JLabel jl=new JLabel("Screen capture",JLabel.CENTER); jl.setFont(new Font("Bold",Font.BOLD,4 0) ); jl.setForeground(Color.RED); c.add(jl,BorderLayout.CENTER); buttonJP.add(start); buttonJP.add(saveAll); buttonJP.add(cancel); buttonJP.add(cancel); buttonJP. setBorder(BorderFactory.createTitledBorder ("public operation area")); JPanel jp=new JPanel();//The panel with two radio buttons jp.add(java=new JRadioButton("java interface")); jp.add(system=new JRadioButton("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.setA lwaysOnTop(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("popup menu"); pm.add(new MenuItem("about")).addActionList ener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ JOptionPane.showMessageDialog(CaptureScreen.this,"<html><Font color=red><center><h 2>About</h2></center></Font>" + "This is a pure JAVA screen capture program<br>Add to the previous basis, some commonly used functions,<br>" + "For example, batch save, multiple clips, and copy to the system paste board. .<br>" + "If you have any questions during use, please feel free to contact us.<br>" + "<Font size=5 color=blue>Author: Qianli Bingfeng<br>" + "<i>QQ:24325142 </i><br></Font></html>"); } }); pm.addSeparator(); pm.add(new MenuItem("Show main window")).addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ CaptureScreen.this.setVisible(true); } }); pm.add(new MenuItem("Start intercept")).addActionListener(new Act ionListener(){ public void actionPerformed(ActionEvent ae){ doStart(); } }); pm.add(new MenuItem("Exit program")).addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.exit(0) ; } }); TrayIcon ti =new TrayIcon(im,"JAVA screen capture",pm); st.add(ti); ti.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ CaptureS creen.this.setVisible(true); } } ); }catch(Exception exe){ exe.printStackTrace(); } } private void updates(){ this.setVisible(true); if(get!=null){ //If the index is 0, it means an image None of them have been added, //The current thing needs to be cleared and the tabpane is put in again if(index==0){ c.removeAll(); c.add(jtp,BorderLayout.CENTER); }else{// Otherwise, just add a panel to the tabpane directly // and you don't have to do anything} PicPanel pic=new PicPanel(get); jtp.addTab("pic"+(++index),pic); jtp.setSelectedComponent( pic); SwingUtilities.updateComponentTreeUI(c); } } private void doStart(){ try{ this.setVisible(false); Thread.sleep(500);//Sleep for 500 milliseconds is to make the main window completely unavailable See 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.setUnde corated(true); jf.setSize(di); jf.setVisible(true); jf.setAlwaysOnTop(true); } catch(Exception exe){ exe.printStackTrace(); } } /** *Public method, process and save all pictures */ public void doSaveAll(){ if(jtp.getTabCount()==0){ JOptionPane.showMessageDialog(this,"The picture cannot be empty!!","Error",JOptionPane.ERROR_MESSAGE); re turn; } JFileChooser jfc=new JFileChooser ("."); jfc.addChoosableFileFilter(new GIFfilter()); jfc.addChoosableFileFilter(new BMPfilter()); jfc.addChoosableFileFilter(new JPGfilter()); 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.toStrin g().toLowerCase(); javax.swing.filechooser .FileFilter ff=jfc.getFileFilter(); if(ff instanceof JPGfilter){ about="JPG"; } else if(ff instanceof PNGfilter){ about="PNG"; }else if(f f instanceof BMPfilter){ about=" BMP"; }else if(ff instanceof GIFfilter){ about="GIF"; } if(ext.endsWith(about.toLowerCase())){ ext=ext.substring(0,ext.lastIndexOf(ab out.toLowerCase() )); } //Get a thread to save these pictures and display the progress bar new SaveAllThread(ext,about).setVisible(true); } } //The thread class specially used to save all pictures, it also needs to display it Saved progress bar private class SaveAllThread extends JDialog implements Runnable{ private String name;//File name header private String ext;//File format private JProgressBar j pb;//A progress bar private JLabel info;//A information display bar private int allTask,doneTask;//All tasks, completed tasks 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 b.setValue(0); jpb.setStringPainted( true); setProgressBarString(); info=new JLabel("Save to:"); this.getContentPane().setBackground(Color.CYAN); this.add(info,BorderLayout.NOR TH); 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); Buffere dImage 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 it!!"); this.dispose(); }catch(Exception exe){ exe.printStackTrace(); this.dispose(); } } } /** *Public Process and save pictures Method *This method is no longer private*/ public void doSave(BufferedImage get){ try{ if(get==null){ JOptionPane.showMessageDialog(this,"The image cannot be empty!!","Error",JOpti onPane. 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 successfully! "); } else JOptionPane.showMessageDialog(this,"Save failed!"); } } catch(Exception exe){ exe.printStackTrace(); } } /** *Public processing adds the current image to the clipboard Method */ public void doCopy(final BufferedImage image){ try{ if(get==null){ JOptionPane.showMessageDialog(this,"The image cannot be empty!!","Error",JOptionPane. ERROR_MESSAGE); return; } Transferable trans = new Transferable(){ public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } public boolean isDataFl avorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } public Object getTransferData( DataFlavor flavor) throws UnsupportedFlavorException, IOException { if(isDataFlavorSupported(flavor)) return image; throw new UnsupportedFlavorE xception(flavor); } }; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null); JOptionPane.showMessageDialog(this ,"Copy to the system paste board!!"); }catch(Exception exe){ exe.printStackTrace(); JOptionPane.showMessageDialog(this,"Error copying to the system paste board!!","Error",JOptionPane .ERROR_MESSAGE); } } //handle the close event 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.setL ookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(this); }catch(Exception exe){ exe.printStackTrace(); } }el se if(source==system){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(this); }catch(Exception exe){ exe.printStackTrace(); } }else if(source==saveAll){ doSaveAll(); } } // An internal class, which represents a panel, and one can Put into the tabpane panel // There is also its own set of methods for handling saving and copying private class PicPanel extends JPanel implements ActionListener{ JButton save,copy,close;//BufferedImag, which indicates saving, copy,close,button BufferedImag e get;//Get Image of 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 post clipboard(C)"); close=new JButton("Close(X)"); save.setMnemonic('S'); copy.setMnemonic( 'C'); close.setMnemonic('X'); JPanel buttonPanel=new JPanel(); buttonPanel.add(copy); buttonPanel.add(save); buttonPanel.add(close); JLab el 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 filters in 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 getDe script(){ return " *.BMP(BMP image)"; } } //Save filters in JPG format private class JPGfilter extends javax.swing.filechooser.FileFilter{ public JPGfilter(){ } public boolean acc ept(File file){ if(file.toString ().toLowerCase().endsWith(".jpg")|| file.isDirectory()){ return true; } else return false; } public String getDescription(){ return "*.J PG(JPG image)"; } } //Save filters in GIF format private class GIFfilter extends javax.swing.filechooser.FileFilter{ public GIFfilter(){ } public boolean accept(File file){ if(fi le.toString().toLowerCase().endsWith(" .gif")|| file.isDirectory()){ return true; } else return false; } public String getDescription(){ return "*.GIF(GIF Image)"; } } //Save PNG format filter 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 used to display the current screen image private class Temp extends JPanel imple ments 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);//Indicate the selected area private Cursor cs=new Cursor(Cursor.CROSSHAIR_CURSOR);//Indicate the mouse state in general private States current=States.DEFAULT;// Indicate the current editing state private Rectangle[] rec;// Indicate the area of eight editing points/ : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : /The following four constants indicate who is the endpoint on 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 fin al int END_Y=4 ; private int currentX, currentY;//The current X and Y are currently selected, only these two need to be changed private Point p=new Point();//The current location of the mouse move private boolean showTip=true;//Whether to display a prompt .If you press the left mouse button, the prompt will no longer display 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,e ndX, 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(px,py,170,20 ); g.setColor(Color.RED); g.drawRect(px,py,170,20); g.setColor(Color.BLACK); g.drawString("Please hold down the left mouse button and not place the screenshot area" ,px,p.y+15); } } //Defend the coordinates of X and Y to be modified based on eight directions such as southeast, west, etc. 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); b reak; 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=(en dX>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); ini tSelect(current); if(showTip){ p=me. getPoint(); repaint(); } } //Specially define a method to handle mouse movement in order to initialize the region you want to select 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.leng th; 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 mouseDrag ged(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{ e ndX+=( x-tempX); tempX=x; } }else if(current==States.NORTH||current==States.SOUTH){ if(currentY==START_Y){ startY+=(y-tempY); temp Y=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){ start X+=(x -tempX); tempX=x; }else{ endX+=(x-tempX); tempX=x; } }else{ startX=tempX; startY=tempY; endX=me.getX(); endY=me.g etY() ; } this.repaint(); } public void mousePressed(MouseEvent me){ showTip=false; tempX=me.getX(); tempY=me.getY(); } public void mouse eReleased(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(star tX, 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(); u pdates (); } } } } } } public static void main(String args[]){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ new CaptureScreen(); } }); }}//Some represent status enum enum States{ NORTH_WEST(new Cursor(Cursor.NW_RESIZE_CURSOR)), // indicates the northwest corner of 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 sor getCursor(){ return cs; }}I hope this article will be helpful to everyone's Java programming.