java拖动画矩形并截图

来源:互联网 发布:自己能干淘宝秒杀群吗 编辑:程序博客网 时间:2024/05/20 16:34
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class Server extends JFrame{
 int w,h;
 MyPanel mp;
 public static void main(String[] args) {
  new Server();
 }
 public Server(){
  mp=new MyPanel();
  this.add(mp);
  this.addMouseListener(mp);
  this.addMouseMotionListener(mp);
  w=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
  h=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
  this.setSize(w, h);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setUndecorated(true);
  this.setVisible(true);
 }
}
class MyPanel extends JPanel implements MouseListener,MouseMotionListener{
 Robot r;
 BufferedImage[] img;
 int state=0;
 int x,y,xx,yy;
 public MyPanel(){
  img=new BufferedImage[2];
  try {
   r=new Robot();
   img[0]=r.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 public void paint(Graphics g){
  super.paint(g);
   g.drawImage(img[0], 0, 0, this);
  if(state==3){
   g.drawImage(img[1], 0, 0,this);
  }
  if(state==1){
   g.setColor(Color.red);
   g.drawRect(x, y, xx-x, yy-y);
   g.setColor(Color.black);
   g.fillRect(x, y-30, 70, 30);
   g.setColor(Color.orange);
   g.drawString(Math.abs(xx-x)+"  "+Math.abs(yy-y), x+5,y-10);
  }
 }
 public void mousePressed(MouseEvent e) {
  if(state==0){
   state=1;//截图片中
   x=e.getX();
   y=e.getY();
  }
 }
 public void mouseReleased(MouseEvent e) {
  img[1]=img[0].getSubimage(x, y, xx-x, yy-y);
  state=3;//得到了大小
  this.repaint();
 }
 public void mouseDragged(MouseEvent e) {
  if(state==1){
   xx=e.getX();
   yy=e.getY();
   this.repaint();
  }
 }
 public void mouseClicked(MouseEvent e) {
 
 }
 public void mouseEntered(MouseEvent e) {}
 public void mouseMoved(MouseEvent e) {}
 public void mouseExited(MouseEvent e) {}
}