`
lushuaiyin
  • 浏览: 674734 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java swing 基本实现QQ截屏功能,很简陋但有学习价值

 
阅读更多

CpFrame.java ,CaptureScreenhh.java和icon.png

CpFrame.java

package captuhhhhh;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;

//VS4E -- DO NOT REMOVE THIS LINE!
public class CpFrame extends JFrame {

	private static final long serialVersionUID = 1L;
	private JButton jButton0;
	private JButton jButton1;
	private JLabel jLabel0;
	private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
	public CpFrame() {
		initComponents();
	}

	private void initComponents() {
		setLayout(new GroupLayout());
		add(getJButton1(), new Constraints(new Leading(40, 198, 12, 12), new Leading(109, 10, 10)));
		add(getJButton0(), new Constraints(new Leading(40, 199, 12, 12), new Leading(47, 10, 10)));
		add(getJLabel0(), new Constraints(new Leading(44, 10, 10), new Leading(151, 10, 10)));
		setSize(320, 240);
	}

	private JLabel getJLabel0() {
		if (jLabel0 == null) {
			jLabel0 = new JLabel();
			jLabel0.setText("双击选区保存");
		}
		return jLabel0;
	}

	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("选区保存");
			jButton1.addActionListener(new ActionListener() {
	
				public void actionPerformed(ActionEvent event) {
					jButton1ActionActionPerformed(event);
				}
			});
		}
		return jButton1;
	}

	private JButton getJButton0() {
		if (jButton0 == null) {
			jButton0 = new JButton();
			jButton0.setText("全屏保存");
			jButton0.addActionListener(new ActionListener() {
	
				public void actionPerformed(ActionEvent event) {
					jButton0ActionActionPerformed(event);
				}
			});
		}
		return jButton0;
	}

	private static void installLnF() {
		try {
			String lnfClassname = PREFERRED_LOOK_AND_FEEL;
			if (lnfClassname == null)
				lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
			UIManager.setLookAndFeel(lnfClassname);
		} catch (Exception e) {
			System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
					+ " on this platform:" + e.getMessage());
		}
	}

	/**
	 * Main entry of the class.
	 * Note: This class is only created so that you can easily preview the result at runtime.
	 * It is not expected to be managed by the designer.
	 * You can modify it as you like.
	 */
	public static void main(String[] args) {
		installLnF();
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				CpFrame frame = new CpFrame();
				frame.setDefaultCloseOperation(CpFrame.EXIT_ON_CLOSE);
				frame.setTitle("CpFrame");
				frame.getContentPane().setPreferredSize(frame.getSize());
				frame.pack();
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		});
	}
//全屏
	private void jButton0ActionActionPerformed(ActionEvent event) {
		this.setVisible(false);
	    try{
	    	FileInputStream fis2=null;
			InputStreamReader isr2=null;
			BufferedReader br2=null;
			FileOutputStream fos2=null;
			OutputStreamWriter osw2=null;
			BufferedWriter bw2=null;
			
			JFileChooser dlg = new JFileChooser(); 
			dlg.setDialogType(JFileChooser.SAVE_DIALOG);
			dlg.showSaveDialog(null);
			
			File getNewFile=dlg.getSelectedFile();
			
			if(getNewFile==null){
				this.setVisible(true);
			}else{
				String getNewPath=getNewFile.getPath();
				String getNewName=getNewFile.getPath();
				String getNewParent=getNewFile.getParent();
				
				//写入新文件
				try {
					Robot robot = new Robot();
					BufferedImage get = robot.createScreenCapture(new Rectangle(Toolkit
							.getDefaultToolkit().getScreenSize()));
			        int wideth=get.getWidth(null); //得到源图宽
			        int height=get.getHeight(null); //得到源图长

			        //写新文件
			        File newFile=new File(getNewPath);
			        if(!newFile.exists()){
			        	newFile.createNewFile();
			        }
			        fos2=new FileOutputStream(newFile);
					osw2=new OutputStreamWriter(fos2);
					
					ImageIO.write(get,"jpg",newFile);//此方法直接保存,或用以下方法保存
					

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}finally{
					if(bw2!=null){ bw2.close();}
					if(osw2!=null){ osw2.close();}
					if(fos2!=null){ fos2.close();}
					if(br2!=null){ br2.close();}
					if(isr2!=null){ isr2.close();}
				}
				JOptionPane.showMessageDialog(null, "保存成功!");
		    	this.setVisible(true);
			}
	    } catch(Exception exe){
	      exe.printStackTrace();
	    }
	  }
//选区
	private void jButton1ActionActionPerformed(ActionEvent event) {
		this.setVisible(false);
		 new CaptureScreenhh();
		 this.setVisible(true);
	}

}


CaptureScreenhh.java//这段代码改别人的

package captuhhhhh;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;

import javax.imageio.*;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.image.*;
/**
 * @author jacky.zhu
 *  
 */
public class CaptureScreenhh extends JFrame implements ActionListener{
  private JButton start,cancel,save;
  private static BufferedImage get;
  /** Creates a new instance of CaptureScreen */
  
  public CaptureScreenhh() {
      doStart();
  }

  private void doStart(){
    try{
      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();
      jf.getContentPane().add(new Temp(jf,bi,di.width,di.height));
      jf.setUndecorated(true);
      jf.setSize(di);
      jf.setVisible(true);
      jf.setAlwaysOnTop(true);
    }catch(Exception exe){
      exe.printStackTrace();
    }
  }

  public static  void doSave(BufferedImage get)throws NullPointerException{
    try{
    	FileInputStream fis2=null;
		InputStreamReader isr2=null;
		BufferedReader br2=null;
		FileOutputStream fos2=null;
		OutputStreamWriter osw2=null;
		BufferedWriter bw2=null;
		
		JFileChooser dlg = new JFileChooser(); 
		dlg.setDialogType(JFileChooser.SAVE_DIALOG);
		dlg.showSaveDialog(null);
		
		File getNewFile=dlg.getSelectedFile();
		
		if(getNewFile==null){
			
		}else{
			String getNewPath=getNewFile.getPath();
			String getNewName=getNewFile.getPath();
			String getNewParent=getNewFile.getParent();
			
			//写入新文件
			try {
		        int wideth=get.getWidth(null); //得到源图宽
		        int height=get.getHeight(null); //得到源图长

		        //写新文件
		        File newFile=new File(getNewPath);
		        if(!newFile.exists()){
		        	newFile.createNewFile();
		        }
		        fos2=new FileOutputStream(newFile);
				osw2=new OutputStreamWriter(fos2);
				
				ImageIO.write(get,"jpg",newFile);//此方法直接保存,或用以下方法保存
				
//				//用Graphics操作,可以改变保存图像的大小,wideth,wideth
//				BufferedImage tag = new BufferedImage(wideth,wideth,BufferedImage.TYPE_INT_RGB);
//		        tag.getGraphics().drawImage(get,0,0,wideth,height,null); 
//		        fos2=new FileOutputStream(getNewPath); //输出到文件流
//		        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos2);
//		        encoder.encode(tag); //JPEG编码

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}finally{
				if(bw2!=null){ bw2.close();}
				if(osw2!=null){ osw2.close();}
				if(fos2!=null){ fos2.close();}
				if(br2!=null){ br2.close();}
				if(isr2!=null){ isr2.close();}
			}
			JOptionPane.showMessageDialog(null, "保存成功!");
	    	
		}
    } catch(Exception exe){
      exe.printStackTrace();
    }
  }

  public void actionPerformed(ActionEvent ae){
    if(ae.getSource()==start){
      doStart();
    } else if(ae.getSource()==cancel){
      //System.exit(0);
    } else if(ae.getSource()==save){
      doSave(get);
    }
  }

  public static void main(String args[]){
    new CaptureScreenhh();
  }
}


///////CaptureScreenhh-end---////////////////////////////////////////////////////////////////////////////////////////////


//显示当前的屏幕图像
class Temp extends JPanel implements MouseListener,MouseMotionListener{
	
	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;
		  }
		}
	
  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;//表示一般情况下的鼠标状态
  private States current=States.DEFAULT;// 表示当前的编辑状态
  private Rectangle[] rec;//表示八个编辑点的区域
  
  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);
    Image icon=Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("icon.png"));
    cs=Toolkit.getDefaultToolkit().createCustomCursor(icon,new Point(0,0),"icon");
    this.setCursor(cs);
    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);
  }

  public void mouseMoved(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){
      if(startX>endX){
        startX+=(x-tempX);
        tempX=x;
      } else{
        endX+=(x-tempX);
        tempX=x;
      }
    }else if(current==States.NORTH){
      if(startY<endY){
        startY+=(y-tempY);
        tempY=y;
      }else{
        endY+=(y-tempY);
        tempY=y;
      }
    }else if(current==States.WEST){
      if(startX<endX){
        startX+=(x-tempX);
        tempX=x;
      } else{
        endX+=(x-tempX);
        tempX=x;
      }
    }else if(current==States.SOUTH){
      if(startY>endY){
        startY+=(y-tempY);
        tempY=y;
      }else{
        endY+=(y-tempY);
        tempY=y;
      }
    } else if(current==States.NORTH_EAST){
      if(startX>endX){
        startX+=(x-tempX);
        tempX=x;
      } else{
        endX+=(x-tempX);
        tempX=x;
      }
      if(startY<endY){
        startY+=(y-tempY);
        tempY=y;
      }else{
        endY+=(y-tempY);
        tempY=y;
      }
    }else if(current==States.NORTH_WEST){
      if(startX<endX){
        startX+=(x-tempX);
        tempX=x;
      } else{
        endX+=(x-tempX);
        tempX=x;
      }
      if(startY<endY){
        startY+=(y-tempY);
        tempY=y;
      }else{
        endY+=(y-tempY);
        tempY=y;
      }
    }else if(current==States.SOUTH_EAST){
      if(startY>endY){
        startY+=(y-tempY);
        tempY=y;
      }else{
        endY+=(y-tempY);
        tempY=y;
      }
      if(startX>endX){
        startX+=(x-tempX);
        tempX=x;
      } else{
        endX+=(x-tempX);
        tempX=x;
      }
    }else if(current==States.SOUTH_WEST){
      if(startY>endY){
        startY+=(y-tempY);
        tempY=y;
      }else{
        endY+=(y-tempY);
        tempY=y;
      }
      if(startX<endX){
        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){
    tempX=me.getX();
    tempY=me.getY();
  }

  public void mouseReleased(MouseEvent me){
       System.out.println("mouseReleased");
    if(me.isPopupTrigger()){
      if(current==States.MOVE){
        startX=0;
        startY=0;
        endX=0;
        endY=0;
        repaint();
      } else{
        jf.dispose();
      }
    }
  }

  public void mouseClicked(MouseEvent me){
	  BufferedImage  get;
    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();
          //save.setEnabled(true);
          CaptureScreenhh.doSave(get);
        }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();
          //save.setEnabled(true);
          CaptureScreenhh.doSave(get);
        }
      }
    }
  }
}



//运行一下试试

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics