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

本文实例总结了常见的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程序设计有所帮助。

(0)

相关推荐

  • Java实现屏幕截图及剪裁

    Java标准API中有个Robot类,该类可以实现屏幕截图,模拟鼠标键盘操作这些功能.这里只展示其屏幕截图. 截图的关键方法createScreenCapture(Rectangle rect) ,该方法需要一个Rectangle对象,Rectangle就是定义屏幕的一块矩形区域,构造Rectangle也相当容易: new Rectangle(int x, int y, int width, int height),四个参数分别是矩形左上角x坐标,矩形左上角y坐标,矩形宽度,矩形高度.截图方法返

  • java实现区域内屏幕截图示例

    这是一个java版的截图程序 复制代码 代码如下: package com.hongyuan.test; import java.awt.AWTException;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.EventQueue;import java.awt.FlowLayout;import java.awt.Graphics;import java.

  • Java根据Request获取客户端IP

    在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr() ,这种方法在大部分情况下都是有效的.但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了. 如果使用了反向代理软件,将http://192.168.1.110:2046/ 的URL反向代理为http://www.xxx.com/ 的URL时,用request.getRemoteAddr() 方法获取的IP地址是:127.0.0.1 或 192.168.1.110 ,而并不是客

  • java图片缩放实现图片填充整个屏幕

    在Android中因为不同像素手机的多样化,对于一张图片,放大不同的手机上因像素不同显示上也会有区别. 现有如下需求:将一张图片宽度充满整个屏幕并显示. 我们常常做的可能是如下两种方式对图片进行处理. 通过<ImageView>,定义属性layout_parent="match_parent"和layout_parent="wrap_content",同时利用<ImageView>的scaleType属性进行缩放. - scaleType=&

  • java实现屏幕共享功能实例分析

    本文实例讲述了java实现屏幕共享功能的方法.分享给大家供大家参考.具体分析如下: 最近在做软件软件工程的课程设计,做一个用于实验室的屏幕监控系统,参考各种前人代码,最后领悟之后要转换自己的代码,初学者都是这样模仿过来的. 说到屏幕监控系统,有教师端和学生端,教师端就是Server端,学生端就做Client端.系统里比较有趣的一个地方应该算是屏幕广播与屏幕监控吧,其余什么点名签到,锁屏,定时关机的,就相对来说简单点. 屏幕广播,在功能实现上面,说白了,就是教师端的机器不断截取屏幕信息,以图片的形

  • Java编程获取当前屏幕分辨率的方法示例

    本文实例讲述了Java编程获取当前屏幕分辨率的方法.分享给大家供大家参考,具体如下: /** * This class implements the functionality of fetching the size of the screen */ package com.leo.util; /** * @author Leo Share * @since 07/16/2007 * @version 1.0 */ class ScreenSize{ private int screenWid

  • java通过ip获取客户端Mac地址的小例子

    复制代码 代码如下: package com.yswc.dao.sign; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *  * 获取MAC地址 *  * @author *  * 2011-12 *  */ public class GetMacAddress { publi

  • javacript获取当前屏幕大小

    在使用html5在android下做开发的时候,要获取屏幕实际的大小,直接上代码,可以通过如下代码测试. 复制代码 代码如下: <html> <script> function a(){ document.write( "屏幕分辨率为:"+screen.width+"*"+screen.height +"<br />"+ "屏幕可用大小:"+screen.availWidth+"*

  • 如何把Java程序窗口在屏幕中间显示

    举例说明: 1.有一个200*200像素的窗口,想要把它放在800*600像素的屏幕中间,屏幕的位置应是(800/2,600/2)=(400,300) 2.为了设置该窗口左上角的位置,以使窗口中心与屏幕中心相吻合,必须符合2个小条件(1)窗口的一半或100像素必须落在屏幕的中心的左边(2)窗口的一半或100像素必须落在屏幕的中心的上方,因此窗口左上角的位置必须定位于(400-100,300-100)=(300,200) 如下图所示: 但在实际程序运行的过程中,程序的运行环境显示屏幕的实际尺寸和像

  • java获取鼠标在屏幕上坐标的方法

    介绍 java作为目前最为流行的计算机开发语言之一,学习java是高薪就业的好选择,本文介绍的这个小工具主要是使用MouseInfo类实时获取鼠标的信息,然后再JDialog上显示出来.希望下面的内容介绍,能够让大家对于如何获取鼠标在屏幕上的坐标更加了解,一起来学习下吧. 代码如下: import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JD

  • java代码实现截图功能(屏幕截图)

    复制代码 代码如下: 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; /*****************************************************

随机推荐