一个效果不错的Java Swing模拟屏幕截图工具类

一个效果不错的Java Swing模拟屏幕截图工具类

原理:

点击截图时,获取当前屏幕的图像,然后再这个静态的图像上进行选择操作。

 

代码:

ScreenShot.java

package com.qiu.util;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ScreenShot extends JFrame {
 private static final long serialVersionUID = 1L;
 private Image image;
 private JLabel imageLabel;
 private int width = Toolkit.getDefaultToolkit().getScreenSize().width;
 private int height = Toolkit.getDefaultToolkit().getScreenSize().height;
 private int isExit;
 private String filename;
 private int x, y, xEnd, yEnd; // 用于记录鼠标点击开始和结束的坐标
 /**
  * 
  * 
  * @param isExit
  * 选择是否退出
  * 0-- 退出系统
  * !0 -- 只是隐藏
  * @param filename
  * 截图生成文件名
  * @throws AWTException
  * @throws InterruptedException
  */
 public ScreenShot(int isExit,String filename) throws AWTException, InterruptedException {
  this.isExit=isExit;
  this.filename=filename;
 
  image = GraphicsUtils.getScreenImage(0, 0, width,
    height);

  imageLabel = new JLabel(new ImageIcon(image));
  
  imageLabel.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
  createAction();
  getContentPane().add(imageLabel);
  setUndecorated(true); 
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setVisible(true);
  setExtendedState(JFrame.MAXIMIZED_BOTH);  }
 /**
  * 实现监听动作
  */
 private void createAction() {
  imageLabel.addMouseListener(new MouseAdapter() {
   public void mouseClicked(MouseEvent e) {
    if (e.isMetaDown()) {   
     if(isExit==0){
      System.exit(0);
     }else{
      ScreenShot.this.dispose();
     }
    }
   }
   public void mousePressed(MouseEvent e) {
    x = e.getX();
    y = e.getY();
   }
   public void mouseReleased(MouseEvent e) {
    xEnd = e.getX();
    yEnd = e.getY();
        try {
         image = GraphicsUtils.getScreenImage(Math.min(x, xEnd),
       Math.min(y, yEnd), Math.abs(xEnd - x),
       Math.abs(yEnd - y));
    } catch (AWTException e1) {
     e1.printStackTrace();
    } catch (InterruptedException e1) {
     e1.printStackTrace();
    }
    // 为了查看截图效果,将区域截图的部分代替全屏的截图展示
     imageLabel.setIcon(new ImageIcon(image));
/**
 
休眠1S,为了查看截图区域在全屏的位置
     try {
     Thread.sleep(1000);
    } catch (InterruptedException e1) {
     e1.printStackTrace();
    }
  */
  
    if (image != null) {
     new ShowWindow(new ImageIcon(image),isExit,filename);
     ScreenShot.this.dispose();
    }
   }
  });
  imageLabel.addMouseMotionListener(new MouseMotionListener() {
   public void mouseDragged(MouseEvent e) {

    xEnd = e.getX();
    yEnd = e.getY();
    BufferedImage bi = new BufferedImage(image.getWidth(null),
      image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) bi.getGraphics();
    g2d.drawImage(image, 0, 0, null);
    g2d.setColor(Color.RED);
    g2d.drawRect(Math.min(x, xEnd) - 1, Math.min(y, yEnd) - 1,
      Math.abs(xEnd - x) + 1, Math.abs(yEnd - y) + 1);
    g2d.dispose();
   
    Graphics g = imageLabel.getGraphics();
    g.drawImage(bi, 0, 0, null);
    g.dispose();
   }
   public void mouseMoved(MouseEvent e) {
    x = e.getX();
    y = e.getY();
    
    
    BufferedImage bi = new BufferedImage(image.getWidth(null),
      image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) bi.getGraphics();
    g2d.drawImage(image, 0, 0, null);
    g2d.setColor(Color.RED);
    g2d.drawLine(x, 0, x, height);
    g2d.drawLine(0, y,width, y);
    g2d.dispose();
    Graphics g = imageLabel.getGraphics();
    g.drawImage(bi, 0, 0, null);
    g.dispose();
   }
  });
 }
 public static void main(String[] args) throws AWTException,
   InterruptedException {
  String filename = new SimpleDateFormat("MM-dd-HH-mm-ss").format(new Date())+".png";
  new ScreenShot(0,filename);
 }
}
class GraphicsUtils {
 /**
  * 截图屏幕中制定区域的图片
  * 
  * @param x
  * @param y
  * @param w
  * @param h
  * @return 被截部分的BufferedImage对象
  * @throws AWTException
  * @throws InterruptedException
  */
 public static BufferedImage getScreenImage(int x, int y, int w, int h)
   throws AWTException, InterruptedException {
  Robot robot = new Robot();
  BufferedImage screen = null;
  if(w-x>0){
    screen = robot.createScreenCapture(new Rectangle(x, y, w,h));
  }
  return screen;
 }
}

ShowWindow .java

package com.qiu.util;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class ShowWindow extends JFrame implements MouseListener{
 private static final long serialVersionUID = 1L;
 static Point origin = new Point();
 private ImageIcon ii;
 private JButton save;
 private JButton cancel;
 private int isExit;
 private String filename;
 
 private JFileChooser chooser;
 public ShowWindow(ImageIcon ii,int isExit,String filename) {
  this.filename=filename;
  this.isExit=isExit;
  this.ii = ii;
  initUI();
  initLayout();
  setSize(ii.getIconWidth(), ii.getIconHeight() + 30);
  setUndecorated(true);
  setLocationRelativeTo(null);
  WindowMove();
  setVisible(true);
 }
 private void initUI() {
  save = new JButton("保存");
  cancel = new JButton("取消");
  save.addMouseListener(this);
  cancel.addMouseListener(this);
  chooser = new JFileChooser();
  FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG Images", "jpg", "png");
  chooser.setFileFilter(filter);
 }
 private void initLayout() {
  JPanel main = new JPanel(new BorderLayout());
  main.setBorder(BorderFactory.createLineBorder(Color.BLUE));
  JPanel btnpane = new JPanel(new GridLayout(1, 8));
  btnpane.add(save);
  btnpane.add(cancel);
  main.add(new JLabel(ii), BorderLayout.CENTER);
  main.add(btnpane, BorderLayout.SOUTH);
  add(main);
 }
 // 窗体移动函数
 public void WindowMove() {
  // 设置没有标题的窗口可以拖动
  this.addMouseListener(new MouseAdapter() {
   public void mousePressed(MouseEvent e) {
    origin.x = e.getX(); // 当鼠标按下的时候获得窗口当前的位置
    origin.y = e.getY();
   }
  });
  this.addMouseMotionListener(new MouseMotionAdapter() {
   public void mouseDragged(MouseEvent e) {
    Point p = getLocation();
    setLocation(p.x + e.getX() - origin.x, p.y + e.getY()
      - origin.y);
   }
  });
 }
 @Override
 public void mouseClicked(MouseEvent e) {
  if(e.getSource()==cancel){
   if(isExit==0){
    System.exit(0);
   }else{
    ShowWindow.this.dispose();
   }
  }
  if(e.getSource()==save){
   File file = null;
   chooser.setSelectedFile(new File(filename));
   int returnVal = chooser.showSaveDialog(ShowWindow.this);
      if(returnVal == JFileChooser.APPROVE_OPTION) {
         file = chooser.getSelectedFile();
      }
    Image img = ii.getImage();
    
    try {
     if(file != null)  {
      ImageIO.write((BufferedImage)img, "png", file);
      JOptionPane.showMessageDialog(ShowWindow.this, "保存成功", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
      System.exit(0);
     }
    } catch (IOException e1) {
     e1.printStackTrace();
    }
  }
 }
 @Override
 public void mousePressed(MouseEvent e) {
  
 }
 @Override
 public void mouseReleased(MouseEvent e) {
  
 }
 @Override
 public void mouseEntered(MouseEvent e) {
  
 }
 @Override
 public void mouseExited(MouseEvent e) {
  
 }
}

使用方法:在需要用到截图的地方设置监听,在监听中调用new ScreenShot(0, filename);如果是调用的话,isExit参数就不能为0,如果isExit为0,则退出整个系统。

package screenshot;
import java.awt.AWTException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.qiu.util.ScreenShot;
public class Test {
 public static void main(String[] args) {
// 自动生成截图名称
  String filename = new SimpleDateFormat("MM-dd-HH-mm-ss")
    .format(new Date()) + ".png";
  try {
// 调用截图
   new ScreenShot(0, filename);
  } catch (AWTException e) {
   e.printStackTrace();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值