截屏和透明组件

截屏和透明组件

桌面截图功能

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

/**
 * 用Java模拟出QQ桌面截图功能
 */

public class Test extends JFrame {

 private static final long serialVersionUID = -267804510087895906L;

 private JButton button = null;
 
 private JLabel imgLabel = null;

 public Test() {
  button = new JButton("模拟屏幕(点右键退出)");
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    try {
     new ScreenWindow(imgLabel);
    } catch (Exception e1) {
     JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
    }
   }
  });
  JPanel pane = new JPanel();
  pane.setBackground(Color.WHITE);
  imgLabel = new JLabel();
  pane.add(imgLabel);
  JScrollPane spane = new JScrollPane(pane);
  this.getContentPane().add(button, BorderLayout.NORTH);
  this.getContentPane().add(spane);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setSize(300, 200);
  this.setLocationRelativeTo(null);
  this.setVisible(true);
 }

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

class ScreenWindow extends JFrame {

 private static final long serialVersionUID = -3758062802950480258L;
 
 private boolean isDrag = false;

 private int x = 0;

 private int y = 0;

 private int xEnd = 0;

 private int yEnd = 0;

 public ScreenWindow(final JLabel imgLabel) throws AWTException, InterruptedException {
  Dimension screenDims = Toolkit.getDefaultToolkit().getScreenSize();
  JLabel label = new JLabel(new ImageIcon(ScreenImage.getScreenImage(0, 0, screenDims.width, screenDims.height)));
  label.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
  label.addMouseListener(new MouseAdapter() {
   public void mouseClicked(MouseEvent e) {
    if (e.getButton() == MouseEvent.BUTTON3) {
     dispose();
    }
   }

   public void mousePressed(MouseEvent e) {
    x = e.getX();
    y = e.getY();
   }

   public void mouseReleased(MouseEvent e) {
    if (isDrag) {
     xEnd = e.getX();
     yEnd = e.getY();
     if(x > xEnd){
      int temp = x;
      x = xEnd;
      xEnd = temp;
     }
     if(y > yEnd){
      int temp = y;
      y = yEnd;
      yEnd = temp;
     }
     try {
      imgLabel.setIcon(new ImageIcon(ScreenImage.getScreenImage(x, y, xEnd - x, yEnd - y)));
     } catch (Exception ex) {
      JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
     }
     dispose();
    }
   }
  });
  label.addMouseMotionListener(new MouseMotionListener() {
   public void mouseDragged(MouseEvent e) {
    if(!isDrag)
     isDrag = true;
   }

   public void mouseMoved(MouseEvent e) {
    /** 拖动过程的虚线选取框需自己实现 */
   }
  });
  this.setUndecorated(true);
  this.getContentPane().add(label);
  this.setSize(screenDims.width, screenDims.height);
  this.setVisible(true);
  this.setExtendedState(JFrame.MAXIMIZED_BOTH);
 }
}

class ScreenImage {

 public static Image getScreenImage(int x, int y, int w, int h) throws AWTException, InterruptedException {
  Robot robot = new Robot();
  Image screen = robot.createScreenCapture(new Rectangle(x, y, w, h)).getScaledInstance(w, h, Image.SCALE_SMOOTH);
  MediaTracker tracker = new MediaTracker(new Label());
  tracker.addImage(screen, 1);
  tracker.waitForID(0);
  return screen;
 }
}

截屏

public class GuiCamera {
 private String fileName; //文件的前缀

 private String defaultName = "GuiCamera";

 static int serialNum = 0;

 private String imageFormat; //图像文件的格式

 private String defaultImageFormat = "png";

 Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

 /****************************************************************
  * 默认的文件前缀为GuiCamera,文件格式为PNG格式
  * The default construct will use the default 
  * Image file surname "GuiCamera", 
  * and default image format "png"
  ****************************************************************/
 public GuiCamera() {
  fileName = defaultName;
  imageFormat = defaultImageFormat;

 }

 /****************************************************************
  * @param s the surname of the snapshot file
  * @param format the format of the  image file, 
  * it can be "jpg" or "png"
  * 本构造支持JPG和PNG文件的存储
  ****************************************************************/
 public GuiCamera(String s, String format) {

  fileName = s;
  imageFormat = format;
 }

 /****************************************************************
  * 对屏幕进行拍照
  * snapShot the Gui once
  ****************************************************************/
 public void snapShot() {

  try {
   //拷贝屏幕到一个BufferedImage对象screenshot
   BufferedImage screenshot = (new Robot())
     .createScreenCapture(new Rectangle(0, 0,
       (int) d.getWidth(), (int) d.getHeight()));
   serialNum++;
   //根据文件前缀变量和文件格式变量,自动生成文件名
   String name = fileName + String.valueOf(serialNum) + "."
     + imageFormat;
   File f = new File(name);
   System.out.print("Save File " + name);
   //将screenshot对象写入图像文件
   ImageIO.write(screenshot, imageFormat, f);
   System.out.print("..Finished!\n");
  } catch (Exception ex) {
   System.out.println(ex);
  }
 }

 public static void main(String[] args) {
  GuiCamera cam = new GuiCamera("d:\\Hello", "png");//

  cam.snapShot();
 }
}

透明窗体
public class TransparentBackground extends JComponent implements
  ComponentListener, WindowFocusListener, Runnable {
 private JFrame frame;

 private Image background;

 private long lastupdate = 0;

 public boolean refreshRequested = true;

 public TransparentBackground(JFrame frame) {
  this.frame = frame;
  updateBackground();
  frame.addComponentListener(this);
  frame.addWindowFocusListener(this);
  new Thread(this).start();
 }

 public void componentShown(ComponentEvent evt) {
  repaint();
 }

 public void componentResized(ComponentEvent evt) {
  repaint();
 }

 public void componentMoved(ComponentEvent evt) {
  repaint();
 }

 public void componentHidden(ComponentEvent evt) {
 }

 public void windowGainedFocus(WindowEvent evt) {
  refresh();
 }

 public void windowLostFocus(WindowEvent evt) {
   refresh();
 }

 public void refresh() {
  if (frame.isVisible()) {
   repaint();
   refreshRequested = true;
   lastupdate = new Date().getTime();
  }
 }

 public void run() {
  try {
   while (true) {
    Thread.sleep(250);
    long now = new Date().getTime();
    if (refreshRequested && ((now - lastupdate) > 1000)) {
     if (frame.isVisible()) {
      Point location = frame.getLocation();
//      frame.setVisible(false);
      updateBackground();
//      frame.setVisible(true);
      frame.setLocation(location);
      refresh();
     }
     lastupdate = now;
     refreshRequested = false;
    }
   }
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }

 public static void main(String[] args) {
  JFrame frame = new JFrame("Transparent Window");
  frame.setUndecorated(true);

  TransparentBackground bg = new TransparentBackground(frame);
  // bg.snapBackground();
  bg.setLayout(new BorderLayout());

  JPanel panel = new JPanel() {
   public void paintComponent(Graphics g) {
    g.setColor(Color.blue);
    Image img = new ImageIcon("d:/moon.gif").getImage();
    g.drawImage(img, 150, 150, null);
   // g.drawLine(0,0, 600, 500);
   }
  };
  panel.setOpaque(false);
  JLabel jl=new JLabel(new ImageIcon("d:/moon.gif"));
  
  
  bg.add("North", jl);
  bg.add("Center", panel);

  frame.getContentPane().add("Center", bg);
  frame.pack();
  Toolkit tk = Toolkit.getDefaultToolkit();
  Dimension dim = tk.getScreenSize();
  frame.setSize((int) dim.getWidth(), (int) dim.getHeight());
  frame.setLocationRelativeTo(null);
  frame.show();
 }

 public void updateBackground() {
  try {
   Robot rbt = new Robot();
   Toolkit tk = Toolkit.getDefaultToolkit();
   Dimension dim = tk.getScreenSize();
   background = rbt.createScreenCapture(new Rectangle(0, 0, (int) dim
     .getWidth(), (int) dim.getHeight()));
  } catch (Exception ex) {
   // p(ex.toString( ));
   // 此方法没有申明过,因为无法得知上下文。因为不影响执行效果,先注释掉它
   ex.printStackTrace();
  }
 }

 public void paintComponent(Graphics g) {
  Point pos = this.getLocationOnScreen();
  Point offset = new Point(-pos.x, -pos.y);
  g.drawImage(background, offset.x, offset.y, null);
 }
}

你可能感兴趣的:(截屏和透明组件)