Java學習筆記之 swing 基本實現QQ截屏功能__swing

來源:互聯網
上載者:User

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() {@Overridepublic 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);        }      }    }  }}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.