欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java编程实现屏幕截图(截屏)代码总结

程序员文章站 2024-03-07 23:22:27
本文实例总结了常见的java编程实现屏幕截图方法。分享给大家供大家参考,具体如下: 方法一: import java.awt.desktop; import...

本文实例总结了常见的java编程实现屏幕截图方法。分享给大家供大家参考,具体如下:

方法一:

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);
  //保存路径
  file screenfile = new file(filename);
  if (!screenfile.exists()) {
   screenfile.mkdir();
  }
  file f = new file(screenfile, folder);
  imageio.write(image, "png", f);
  //自动打开
  if (desktop.isdesktopsupported()
     && desktop.getdesktop().issupported(desktop.action.open))
     desktop.getdesktop().open(f);
 }
 public static void main(string[] args) {
  try {
   capturescreen("e:\\你好","11.png");
  } catch (exception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
 }
}

方法二:

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);
  }
  /** 得到捕捉后的bufferedimage */
  public bufferedimage getpickedimage() {
    return pickedimage;
  }
  /** 得到捕捉后的icon */
  public imageicon getpickedicon() {
    return new imageicon(getpickedimage());
  }
  /**
   * 储存为一个文件,为png格式
   * 
   * @deprecated replaced by saveaspng(file file)
   **/
  @deprecated
  public void savetofile(file file) throws ioexception {
    imageio.write(getpickedimage(), defaultimageformater, file);
  }
  /** 储存为一个文件,为png格式 */
  public void saveaspng(file file) throws ioexception {
    imageio.write(getpickedimage(), "png", file);
  }
  /** 储存为一个jpeg格式图像文件 */
  public void saveasjpeg(file file) throws ioexception {
    imageio.write(getpickedimage(), "jpeg", file);
  }
  /** 写入一个outputstream */
  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; // 截取的图像
  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();
}
/** 显示图片的label */
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;
}

方法三:

因为有最小化到系统托盘,还是需要一张名为bg.gif作为托盘图标,图片应放在同级目录下,否则会空指针异常。

主要的截屏代码部分是:

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);

(源代码来源于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;//一个放置很多份图片
 private int index;//一个一直会递增的索引,用于标认图片
 private jradiobutton java,system;//java界面,系统界面
 /** creates a new instance of capturescreen */
 public capturescreen() {
  super("屏幕截取软件(第三版)");
  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("开始截取");
  saveall=new jbutton("保存所有");
  cancel=new jbutton("退出");
  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("屏幕截取",jlabel.center);
  jl.setfont(new font("黑体",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("公共操作区"));
  jpanel jp=new jpanel();//放两个单选按钮的面板
  jp.add(java=new jradiobutton("java界面"));
  jp.add(system=new jradiobutton("系统界面",true));
  java.addactionlistener(this);
  system.addactionlistener(this);
  jp.setborder(borderfactory.createtitledborder("界面风格"));
  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("弹出菜单");
   pm.add(new menuitem("关于")).addactionlistener(new actionlistener(){
    public void actionperformed(actionevent ae){
     joptionpane.showmessagedialog(capturescreen.this,"<html><font color=red><center><h2>关于</h2></center></font>" +
       "这是一款纯java的屏幕截取程序<br>在以前的基础上增加了一些常用的功能,<br>" +
       "比如,批量保存,多幅截取,复制到系统粘帖板...<br>" +
       "在使用过程中有任何问题,欢迎联系.<br>" +
       "<font size=5 color=blue>作者:千里冰封<br>" +
       "<i>qq:24325142</i><br></font></html>");
    }
   });
   pm.addseparator();
   pm.add(new menuitem("显示主窗口")).addactionlistener(new actionlistener(){
    public void actionperformed(actionevent ae){
     capturescreen.this.setvisible(true);
    }
   });
   pm.add(new menuitem("开始截取")).addactionlistener(new actionlistener(){
    public void actionperformed(actionevent ae){
     dostart();
    }
   });
   pm.add(new menuitem("退出程序")).addactionlistener(new actionlistener(){
    public void actionperformed(actionevent ae){
     system.exit(0);
    }
   });
   trayicon ti=new trayicon(im,"java屏幕截取",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){
   //如果索引是0,则表示一张图片都没有被加入过,
   //则要清除当前的东西,重新把tabpane放进来
   if(index==0){
    c.removeall();
    c.add(jtp,borderlayout.center);
   }else{//否则的话,直接对tabpane添加面板就可以了
    //就什么都不用做了
   }
   picpanel pic=new picpanel(get);
   jtp.addtab("图片"+(++index),pic);
   jtp.setselectedcomponent(pic);
   swingutilities.updatecomponenttreeui(c);
  }
 }
 private void dostart(){
  try{
   this.setvisible(false);
   thread.sleep(500);//睡500毫秒是为了让主窗完全不见
   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,"图片不能为空!!","错误",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()));
   }
   //起一个线程去保存这些图片并显示出进度条
   new saveallthread(ext,about).setvisible(true);
  }
 }
 //专门用来保存所有图片的线程类,它还要显示出保存的进度条
 private class saveallthread extends jdialog implements runnable{
  private string name;//文件名头部份
  private string ext;//文件格式
  private jprogressbar jpb;//一个进度条
  private jlabel info;// 一个信息显示条
  private int alltask,donetask;//所有任务,已完成任务
  public saveallthread(string name,string ext){
   super(capturescreen.this,"保存",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("正在保存到:");
   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>正在保存到:</b><br>"+f.tostring()+"</html>");
     imageio.write(image,ext,f);
     donetask++;
     jpb.setvalue(donetask);
     setprogressbarstring();
     thread.sleep(500);
    }
    joptionpane.showmessagedialog(this,"保存完毕!!");
    this.dispose();
   }catch(exception exe){
    exe.printstacktrace();
    this.dispose();
   }
  }
 }
 /**
  *公用的处理保存图片的方法
  *这个方法不再私有了
  */
 public void dosave(bufferedimage get){
  try{
   if(get==null){
    joptionpane.showmessagedialog(this,"图片不能为空!!","错误",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,"保存成功!");
    } else
     joptionpane.showmessagedialog(this,"保存失败!");
   }
  } catch(exception exe){
   exe.printstacktrace();
  }
 }
 /**
  *公共的处理把当前的图片加入剪帖板的方法
  */
 public void docopy(final bufferedimage image){
  try{
   if(get==null){
    joptionpane.showmessagedialog(this,"图片不能为空!!","错误",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,"已复制到系统粘帖板!!");
  }catch(exception exe){
   exe.printstacktrace();
   joptionpane.showmessagedialog(this,"复制到系统粘帖板出错!!","错误",joptionpane.error_message);
  }
 }
 //处理关闭事件
 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();
  }
 }
 //一个内部类,它表示一个面板,一个可以被放进tabpane的面板
 //也有自己的一套处理保存和复制的方法
 private class picpanel extends jpanel implements actionlistener{
  jbutton save,copy,close;//表示保存,复制,关闭的按钮
  bufferedimage get;//得到的图片
  public picpanel(bufferedimage get){
   super(new borderlayout());
   this.get=get;
   initpanel();
  }
  public bufferedimage getimage(){
   return get;
  }
  private void initpanel(){
   save=new jbutton("保存(s)");
   copy=new jbutton("复制到剪帖板(c)");
   close=new jbutton("关闭(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);
   }
  }
 }
 //保存bmp格式的过滤器
 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图像)";
  }
 }
 //保存jpg格式的过滤器
 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图像)";
  }
 }
 //保存gif格式的过滤器
 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图像)";
  }
 }
 //保存png格式的过滤器
 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图像)";
  }
 }
 //一个暂时类,用于显示当前的屏幕图像
 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);//表示选中的区域
  private cursor cs=new cursor(cursor.crosshair_cursor);//表示一般情况下的鼠标状态
  private states current=states.default;// 表示当前的编辑状态
  private rectangle[] rec;//表示八个编辑点的区域
  //下面四个常量,分别表示谁是被选中的那条线上的端点
  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;//当前被选中的x和y,只有这两个需要改变
  private point p=new point();//当前鼠标移的地点
  private boolean showtip=true;//是否显示提示.如果鼠标左键一按,则提示不再显了
  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("请按住鼠标左键不放选择截图区",p.x,p.y+15);
   }
  }
  //根据东南西北等八个方向决定选中的要修改的x和y的座标
  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();
   }
  }
  //特意定义一个方法处理鼠标移动,是为了每次都能初始化一下所要选择的地区
  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();
   }
  });
 }
}
//一些表示状态的枚举
enum states{
 north_west(new cursor(cursor.nw_resize_cursor)),//表示西北角
 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;
 }
}

希望本文所述对大家java程序设计有所帮助。