今天稍微花了点时间实现了一个java的屏幕截图程序,功能简单,支持全屏截图和选择截图
用JSmooth做了个.exe程序,直接运行就可以了,
附:
程序下载 
http://www.blogjava.net/Files/jht/MyScreenSnap.zipJRE1.4版本的可执行程序 
http://www.blogjava.net/Files/jht/MyScreenSnap_jre1.4.zip关键的有几点
一、做一个透明效果的窗体
二、调用Robot类的捕获屏幕方法
代码比较粗糙,暂时就这样。
代码如下: 
 package cn.heapstack.MyScreenSnap;
package cn.heapstack.MyScreenSnap;

 import java.awt.AWTException;
import java.awt.AWTException;
 import java.awt.Color;
import java.awt.Color;
 import java.awt.Dimension;
import java.awt.Dimension;
 import java.awt.DisplayMode;
import java.awt.DisplayMode;
 import java.awt.FlowLayout;
import java.awt.FlowLayout;
 import java.awt.GraphicsDevice;
import java.awt.GraphicsDevice;
 import java.awt.GraphicsEnvironment;
import java.awt.GraphicsEnvironment;
 import java.awt.Rectangle;
import java.awt.Rectangle;
 import java.awt.Robot;
import java.awt.Robot;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
import java.awt.event.ActionListener;
 import java.awt.image.BufferedImage;
import java.awt.image.BufferedImage;
 import java.io.File;
import java.io.File;
 import java.io.IOException;
import java.io.IOException;

 import javax.imageio.ImageIO;
import javax.imageio.ImageIO;
 import javax.swing.JButton;
import javax.swing.JButton;
 import javax.swing.JFrame;
import javax.swing.JFrame;
 import javax.swing.JPanel;
import javax.swing.JPanel;


 public class MenuFrame
public class MenuFrame  {
{
 
    
 private JFrame frame;
    private JFrame frame;
 private TranslucentFrame tframe;
    private TranslucentFrame tframe;
 private JPanel panel;
    private JPanel panel;
 private JButton button1;
    private JButton button1;
 private JButton button2;
    private JButton button2;
 private JButton button3;
    private JButton button3;
 private FormListener formListener;
    private FormListener formListener;
 private Robot robot;
    private Robot robot;
 
    
 public static     GraphicsEnvironment graphenv = GraphicsEnvironment.getLocalGraphicsEnvironment ();
    public static     GraphicsEnvironment graphenv = GraphicsEnvironment.getLocalGraphicsEnvironment ();
 public static     GraphicsDevice [] screens = graphenv.getScreenDevices ();
    public static     GraphicsDevice [] screens = graphenv.getScreenDevices ();    
 public static     DisplayMode mode = screens [0].getDisplayMode ();
    public static     DisplayMode mode = screens [0].getDisplayMode ();    
 
    
 public MenuFrame()
    public MenuFrame()

 
     {
{
 initComponents();
        initComponents();
 
        
 }
    }
 
    
 public void initComponents()
    public void initComponents()

 
     {
{
 frame = new JFrame("MyScreenSnap Version:1.0 Author:jacky.jihao@gmail.com");
        frame = new JFrame("MyScreenSnap Version:1.0 Author:jacky.jihao@gmail.com");
 
        
 tframe = new TranslucentFrame();
        tframe = new TranslucentFrame();
 panel = new JPanel();
        panel = new JPanel();
 
        

 try
        try  {
{
 
            
 robot = new Robot();
            robot = new Robot();

 } catch (AWTException e)
        } catch (AWTException e)  {
{
 e.printStackTrace();
            e.printStackTrace();
 }
        } 
 
        
 button1 = new JButton("Capture Full Screen");
        button1 = new JButton("Capture Full Screen");
 button2 = new JButton("Capture Selected Screen");
        button2 = new JButton("Capture Selected Screen");
 button3 = new JButton("Exit");
        button3 = new JButton("Exit");
 formListener = new FormListener();
        formListener = new FormListener();
 button1.addActionListener(formListener);
        button1.addActionListener(formListener);    
 button2.addActionListener(formListener);
        button2.addActionListener(formListener);    
 button3.addActionListener(formListener);
        button3.addActionListener(formListener);    
 
        
 //fullScreenFrame.setVisible(false);
        //fullScreenFrame.setVisible(false);
 tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 tframe.setUndecorated(true);
        tframe.setUndecorated(true);
 tframe.setAlwaysOnTop(true);
        tframe.setAlwaysOnTop(true);
 tframe.setSize(2000,2000);
        tframe.setSize(2000,2000);
 
        
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        
 frame.setLayout(null);
        frame.setLayout(null);
 Dimension size = new Dimension(500,80);
        Dimension size = new Dimension(500,80);
 frame.setPreferredSize(size );
        frame.setPreferredSize(size );
 frame.setSize(size);
        frame.setSize(size);
 frame.setLocation(300,300);
        frame.setLocation(300,300);
 frame.setBackground(Color.black);
        frame.setBackground(Color.black);
 
        
 panel.setLocation(0, 0);
        panel.setLocation(0, 0);
 panel.setSize(size);
        panel.setSize(size);
 panel.setPreferredSize(size);
        panel.setPreferredSize(size);
 panel.setLayout(new FlowLayout());
        panel.setLayout(new FlowLayout());
 
        
 panel.setOpaque(false);
        panel.setOpaque(false);
 
        
 panel.add(button1);
        panel.add(button1);
 panel.add(button2);
        panel.add(button2);
 panel.add(button3);
        panel.add(button3);
 
        
 
        
 frame.add(panel);
        frame.add(panel);
 
        
 frame.pack();
        frame.pack();
 
        
 frame.show();
        frame.show();
 
        
 }
    }

 class FormListener implements ActionListener
    class FormListener implements ActionListener

 
     {
{
 
        

 public void actionPerformed(ActionEvent e)
        public void actionPerformed(ActionEvent e)  {
{
 if(e.getSource() == button1)
            if(e.getSource() == button1)

 
             {
{
 System.out.println("Just capture the screen using a robot");
                System.out.println("Just capture the screen using a robot");
 frame.hide();
                frame.hide();
 Rectangle bounds = new Rectangle (0, 0, mode.getWidth (), mode.getHeight ());
                Rectangle bounds = new Rectangle (0, 0, mode.getWidth (), mode.getHeight ());    
 
                
 BufferedImage bimg = robot.createScreenCapture(bounds);
                BufferedImage bimg = robot.createScreenCapture(bounds);
 
                                
 String fileName = String.valueOf(System.currentTimeMillis())+".png";
                String fileName = String.valueOf(System.currentTimeMillis())+".png";
 File outputFile = new File(fileName);
                File outputFile = new File(fileName);
 try
                try 

 
                 {
{
 ImageIO.write(bimg, "png", outputFile);
                    ImageIO.write(bimg, "png", outputFile);
 }
                } 
 catch (IOException e1)
                catch (IOException e1) 

 
                 {
{
 e1.printStackTrace();
                    e1.printStackTrace();
 }
                }

 frame.show();
                frame.show();
 System.out.println("File save as "+fileName);
                System.out.println("File save as "+fileName);
 
                
 }
            }
 else if(e.getSource() == button2)
            else if(e.getSource() == button2)

 
             {
{
 System.out.println("Create a full screen frame");
                System.out.println("Create a full screen frame");
 if(!tframe.isShowing())
                if(!tframe.isShowing())

 
                 {
{
 frame.hide();
                    frame.hide();
 tframe.updateBackground();
                    tframe.updateBackground();
 tframe.show();
                    tframe.show();
 frame.show();
                    frame.show();
 frame.toBack();
                    frame.toBack();
 }
                }
 else
                else
 tframe.show();
                    tframe.show();
 
                
 }
            }
 else if(e.getSource() == button3)
            else if(e.getSource() == button3)

 
             {
{
 System.exit(0);
                System.exit(0);
 }
            }
 
            
 }
        }
 
        
 }
    }
 
    

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

 }
}

 package cn.heapstack.MyScreenSnap;
package cn.heapstack.MyScreenSnap;

 import java.awt.AWTException;
import java.awt.AWTException;
 import java.awt.Color;
import java.awt.Color;
 import java.awt.Dimension;
import java.awt.Dimension;
 import java.awt.Graphics;
import java.awt.Graphics;
 import java.awt.Point;
import java.awt.Point;
 import java.awt.Rectangle;
import java.awt.Rectangle;
 import java.awt.Robot;
import java.awt.Robot;
 import java.awt.Toolkit;
import java.awt.Toolkit;
 import java.awt.event.ComponentEvent;
import java.awt.event.ComponentEvent;
 import java.awt.event.ComponentListener;
import java.awt.event.ComponentListener;
 import java.awt.event.MouseEvent;
import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionListener;
 import java.awt.event.WindowEvent;
import java.awt.event.WindowEvent;
 import java.awt.event.WindowFocusListener;
import java.awt.event.WindowFocusListener;
 import java.awt.image.BufferedImage;
import java.awt.image.BufferedImage;
 import java.awt.image.ImageFilter;
import java.awt.image.ImageFilter;
 import java.io.File;
import java.io.File;
 import java.io.FileFilter;
import java.io.FileFilter;
 import java.io.IOException;
import java.io.IOException;
 import java.util.Iterator;
import java.util.Iterator;

 import javax.imageio.IIOImage;
import javax.imageio.IIOImage;
 import javax.imageio.ImageIO;
import javax.imageio.ImageIO;
 import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriteParam;
 import javax.imageio.ImageWriter;
import javax.imageio.ImageWriter;
 import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
 import javax.swing.ImageIcon;
import javax.swing.ImageIcon;
 import javax.swing.JFileChooser;
import javax.swing.JFileChooser;
 import javax.swing.JFrame;
import javax.swing.JFrame;
 import javax.swing.JOptionPane;
import javax.swing.JOptionPane;

 public class TranslucentFrame extends JFrame implements ComponentListener,
public class TranslucentFrame extends JFrame implements ComponentListener,

 WindowFocusListener, MouseListener, MouseMotionListener
        WindowFocusListener, MouseListener, MouseMotionListener  {
{

 private boolean flag_prepare = true;
    private boolean flag_prepare = true;

 private BufferedImage background;
    private BufferedImage background;

 private Robot robot;
    private Robot robot;

 private Dimension size;
    private Dimension size;

 private Point startPoint;
    private Point startPoint;

 private Point lastPoint;
    private Point lastPoint;

 private int width = 0;
    private int width = 0;
 private int w = 0;
    private int w = 0;
 private int h = 0;
    private int h = 0;
 private int height = 0;
    private int height = 0;


 public TranslucentFrame()
    public TranslucentFrame()  {
{
 init();
        init();
 }
    }


 private void init()
    private void init()  {
{

 try
        try  {
{
 robot = new Robot();
            robot = new Robot();
 size = Toolkit.getDefaultToolkit().getScreenSize();
            size = Toolkit.getDefaultToolkit().getScreenSize();

 } catch (AWTException e)
        } catch (AWTException e)  {
{
 e.printStackTrace();
            e.printStackTrace();
 }
        }
 startPoint = new Point();
        startPoint = new Point();
 lastPoint = new Point();
        lastPoint = new Point();
 this.addWindowFocusListener(this);
        this.addWindowFocusListener(this);
 this.addComponentListener(this);
        this.addComponentListener(this);
 this.addMouseListener(this);
        this.addMouseListener(this);
 this.addMouseMotionListener(this);
        this.addMouseMotionListener(this);

 this.updateBackground();
        this.updateBackground();
 }
    }


 public void updateBackground()
    public void updateBackground()  {
{
 background = robot.createScreenCapture(new Rectangle(0, 0, (int) size
        background = robot.createScreenCapture(new Rectangle(0, 0, (int) size
 .getWidth(), (int) size.getHeight()));
                .getWidth(), (int) size.getHeight()));
 }
    }


 public void refresh()
    public void refresh()  {
{

 this.repaint();
        this.repaint();
 }
    }


 public void repaint()
    public void repaint()  {
{
 Graphics g = this.getGraphics();
        Graphics g = this.getGraphics();

 g.setColor(Color.red);
        g.setColor(Color.red);
 w = lastPoint.x - startPoint.x;
        w = lastPoint.x - startPoint.x;
 h = lastPoint.y - startPoint.y;
        h = lastPoint.y - startPoint.y;
 width = Math.abs(w);
        width = Math.abs(w);
 height = Math.abs(h);
        height = Math.abs(h);

 // don't need to clear Rect now, just paint the background, it feels
        // don't need to clear Rect now, just paint the background, it feels
 // good
        // good
 // g.clearRect(startPoint.x, startPoint.y, width, height);
        // g.clearRect(startPoint.x, startPoint.y, width, height);

 this.paintComponents(g);
        this.paintComponents(g);


 if (!this.flag_prepare)
        if (!this.flag_prepare)  {
{


 if (((w) < 0) && ((h) < 0))
            if (((w) < 0) && ((h) < 0))  {
{
 g.drawRect(lastPoint.x, lastPoint.y, width, height);
                g.drawRect(lastPoint.x, lastPoint.y, width, height);


 } else if (((w) > 0) && ((h) < 0))
            } else if (((w) > 0) && ((h) < 0))  {
{
 g.drawRect(startPoint.x, lastPoint.y, width, height);
                g.drawRect(startPoint.x, lastPoint.y, width, height);


 } else if (((w) < 0) && ((h) > 0))
            } else if (((w) < 0) && ((h) > 0))  {
{
 g.drawRect(lastPoint.x, startPoint.y, width, height);
                g.drawRect(lastPoint.x, startPoint.y, width, height);


 } else if (((w) > 0) && ((h) > 0))
            } else if (((w) > 0) && ((h) > 0))  {
{
 g.drawRect(startPoint.x, startPoint.y, width, height);
                g.drawRect(startPoint.x, startPoint.y, width, height);

 }
            }

 } else
        } else  {
{
 g.drawLine(0, lastPoint.y, size.width, lastPoint.y);
            g.drawLine(0, lastPoint.y, size.width, lastPoint.y);
 g.drawLine(lastPoint.x, 0, lastPoint.x, size.height);
            g.drawLine(lastPoint.x, 0, lastPoint.x, size.height);
 }
        }
 }
    }


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

 private static final long serialVersionUID = 3690836343560995785L;
    private static final long serialVersionUID = 3690836343560995785L;


 public static void main(String[] args)
    public static void main(String[] args)  {
{
 TranslucentFrame frame = new TranslucentFrame();
        TranslucentFrame frame = new TranslucentFrame();
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setUndecorated(true);
        frame.setUndecorated(true);
 frame.setAlwaysOnTop(true);
        frame.setAlwaysOnTop(true);
 frame.setSize(2000, 2000);
        frame.setSize(2000, 2000);
 frame.show();
        frame.show();

 }
    }


 public void componentHidden(ComponentEvent e)
    public void componentHidden(ComponentEvent e)  {
{
 }
    }


 public void componentMoved(ComponentEvent e)
    public void componentMoved(ComponentEvent e)  {
{
 this.refresh();
        this.refresh();
 }
    }


 public void componentResized(ComponentEvent e)
    public void componentResized(ComponentEvent e)  {
{
 }
    }


 public void componentShown(ComponentEvent e)
    public void componentShown(ComponentEvent e)  {
{
 this.refresh();
        this.refresh();
 }
    }


 public void windowGainedFocus(WindowEvent e)
    public void windowGainedFocus(WindowEvent e)  {
{
 this.refresh();
        this.refresh();
 }
    }


 public void windowLostFocus(WindowEvent e)
    public void windowLostFocus(WindowEvent e)  {
{
 }
    }


 public void mouseMoved(MouseEvent e)
    public void mouseMoved(MouseEvent e)  {
{
 // System.out.println(e.getX() + ":" + e.getY());
        // System.out.println(e.getX() + ":" + e.getY());
 this.lastPoint.x = e.getX();
        this.lastPoint.x = e.getX();
 this.lastPoint.y = e.getY();
        this.lastPoint.y = e.getY();
 repaint();
        repaint();
 }
    }


 public void mousePressed(MouseEvent e)
    public void mousePressed(MouseEvent e)  {
{
 System.out.println("Mouse pressed , set the start point,x:" + e.getX()
        System.out.println("Mouse pressed , set the start point,x:" + e.getX()
 + " y:" + e.getY());
                + " y:" + e.getY());

 if (e.getButton() == MouseEvent.BUTTON3)
        if (e.getButton() == MouseEvent.BUTTON3)  {
{
 System.out.println("Get right mouse");
            System.out.println("Get right mouse");
 this.hide();
            this.hide();

 } else
        } else  {
{
 this.flag_prepare = false;
            this.flag_prepare = false;
 this.startPoint.x = e.getX();
            this.startPoint.x = e.getX();
 this.startPoint.y = e.getY();
            this.startPoint.y = e.getY();
 }
        }
 }
    }


 public void mouseReleased(MouseEvent e)
    public void mouseReleased(MouseEvent e)  {
{
 System.out.println("Mouse released , set the last point,x:" + e.getX()
        System.out.println("Mouse released , set the last point,x:" + e.getX()
 + " y:" + e.getY());
                + " y:" + e.getY());
 this.flag_prepare = true;
        this.flag_prepare = true;
 // save the picture
        // save the picture

 if (e.getButton() == MouseEvent.BUTTON1)
        if (e.getButton() == MouseEvent.BUTTON1)  {
{
 
            
 BufferedImage bimg = null;
            BufferedImage bimg = null;

 if (((w) < 0) && ((h) < 0))
            if (((w) < 0) && ((h) < 0))  {
{
 //g.drawRect(lastPoint.x, lastPoint.y, width, height);
                //g.drawRect(lastPoint.x, lastPoint.y, width, height);
 bimg = robot.createScreenCapture(new Rectangle(lastPoint.x+1, lastPoint.y+1, width-1, height-1));
                bimg = robot.createScreenCapture(new Rectangle(lastPoint.x+1, lastPoint.y+1, width-1, height-1));


 } else if (((w) > 0) && ((h) < 0))
            } else if (((w) > 0) && ((h) < 0))  {
{
 //g.drawRect(startPoint.x, lastPoint.y, width, height);
                //g.drawRect(startPoint.x, lastPoint.y, width, height);
 bimg = robot.createScreenCapture(new Rectangle(startPoint.x+1, lastPoint.y+1, width-1, height-1));
                bimg = robot.createScreenCapture(new Rectangle(startPoint.x+1, lastPoint.y+1, width-1, height-1));


 } else if (((w) < 0) && ((h) > 0))
            } else if (((w) < 0) && ((h) > 0))  {
{
 //g.drawRect(lastPoint.x, startPoint.y, width, height);
                //g.drawRect(lastPoint.x, startPoint.y, width, height);
 bimg = robot.createScreenCapture(new Rectangle(lastPoint.x+1, startPoint.y+1, width-1, height-1));
                bimg = robot.createScreenCapture(new Rectangle(lastPoint.x+1, startPoint.y+1, width-1, height-1));


 } else if (((w) > 0) && ((h) > 0))
            } else if (((w) > 0) && ((h) > 0))  {
{
 //g.drawRect(startPoint.x, startPoint.y, width, height);
                //g.drawRect(startPoint.x, startPoint.y, width, height);
 bimg = robot.createScreenCapture(new Rectangle(startPoint.x+1, startPoint.y+1, width-1, height-1));
                bimg = robot.createScreenCapture(new Rectangle(startPoint.x+1, startPoint.y+1, width-1, height-1));

 }
            }
 
            
 
            
 JFileChooser fcSave = new JFileChooser();
            JFileChooser fcSave = new JFileChooser();
 fcSave.setCurrentDirectory(new File(System.getProperty("user.dir")));
            fcSave.setCurrentDirectory(new File(System.getProperty("user.dir")));
 fcSave.setSelectedFile(null);
            fcSave.setSelectedFile(null);
 if (fcSave.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
            if (fcSave.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
 return;
                return;

 File file = fcSave.getSelectedFile();
            File file = fcSave.getSelectedFile();
 String path = file.getAbsolutePath().toLowerCase();
            String path = file.getAbsolutePath().toLowerCase();
 if (!path.endsWith(".png"))
            if (!path.endsWith(".png"))
 file = new File(path += ".png");
                file = new File(path += ".png");
 
            
 
            

 try
            try  {
{
 ImageIO.write(bimg, "png", file);
                ImageIO.write(bimg, "png", file);

 } catch (IOException e1)
            } catch (IOException e1)  {
{
 e1.printStackTrace();
                e1.printStackTrace();
 }
            }
 }
        }

 if (this.isShowing())
        if (this.isShowing())
 repaint();
            repaint();
 }
    }


 public void mouseClicked(MouseEvent e)
    public void mouseClicked(MouseEvent e)  {
{

 }
    }


 public void mouseEntered(MouseEvent e)
    public void mouseEntered(MouseEvent e)  {
{

 }
    }


 public void mouseExited(MouseEvent e)
    public void mouseExited(MouseEvent e)  {
{

 }
    }


 public void mouseDragged(MouseEvent e)
    public void mouseDragged(MouseEvent e)  {
{
 this.lastPoint.x = e.getX();
        this.lastPoint.x = e.getX();
 this.lastPoint.y = e.getY();
        this.lastPoint.y = e.getY();
 repaint();
        repaint();
 }
    }

 }
}

posted on 2007-03-29 19:19 
jht 阅读(1723) 
评论(5)  编辑  收藏  所属分类: 
J2SE 、
Swing Tips