日期:2014-05-20  浏览次数:20690 次

自己写的屏幕截图软件,大家一起学习
模仿QQ的截图软件,运行就可以截图,按Esc退出
在截图的时候线框部分不好处理,会闪烁,大家有什么好的建议可以提出来,谢谢,由于引用的组件比较多,我都用"*"号代替了,大家复制到Eclipse上可以先把这些import删掉,然后按ctrl+shift+o就可以看见所用的组件了

Java code
import java.awt.*; 

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;

import com.sun.image.codec.jpeg.*;

@SuppressWarnings("serial")
class ImagePanel extends JPanel
{
private BufferedImage image;

public ImagePanel(BufferedImage image)
{
this.image = image;
prefSize();
}

public void setImage(BufferedImage image)
{
this.image = image;
prefSize();
repaint();
}

/**
* 设置面板大小
*/
private void prefSize()
{
this.setSize(image.getWidth(), image.getHeight());
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}

/**
* 文件类型
*/
class ImageFilter extends FileFilter
{

public boolean accept(File f)
{
if (f.isDirectory())
{
return true;
}

String extension = getExtension(f);
if (extension != null)
{
if (extension.equals("jpeg") || extension.equals("jpg")
|| extension.equals("bmp"))
{
return true;
} else
{
return false;
}
}

return false;
}

public String getExtension(File f)
{
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');

if (i > 0 && i < s.length() - 1)
{
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}

public String getDescription()
{
return "图片类型";
}
}

@SuppressWarnings("serial")
public class CutScreen extends JFrame
{
private int x, y, w, h;
private BufferedImage bufImage;
private ImagePanel imagePanel;
private Graphics g;
private static Dimension screenDims;
private GraphicsDevice gd = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private JPopupMenu popup = new JPopupMenu();
private JMenuItem[] popupm =
{ new JMenuItem("Copy"), new JMenuItem("Save"), new JMenuItem("Reset"),
new JMenuItem("Exit") };
private JFileChooser fileChooser = new JFileChooser();

public CutScreen()
{

this.setLayout(new BorderLayout());
this.add(buildControls());

// 设置标题
this.setTitle("截图程序");
// 去掉窗口的装饰
this.setUndecorated(true);
// 采用指定的窗口装饰风格
this.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
// 设置全屏
gd.setFullScreenWindow(this);
// 窗体始终靠前
this.setAlwaysOnTop(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

private JComponent buildControls()
{
// 获取屏幕图像
bufImage = getScreenImage();
imagePanel = new ImagePanel(bufImage);

// 注册事件监听
imagePanel.addMouseListener(new MouseAdapter()
{

// 当鼠标按下时
public void mousePressed(MouseEvent e)
{
// 获取按下时的鼠标坐标
x = e.getX();
y = e.getY();
}

public void mouseReleased(MouseEvent e)
{