package xinyu.shangrao.demo.fucking;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.FilteredImageSource;
import java.awt.image.RGBImageFilter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.MenuEvent;
public class TestDemo extends JFrame implements ActionListener
, MouseListener{
/**
* @author Rick
* 这个文件的图片是获取自网络上,通过URL链接生成的图片,
* 当没有网络是,程序便会产生一个NullPointerException异常
* ,因为没有网络,url链接返回一个null,而不是产生一个
* MalformedURLException!
*/
private static final long serialVersionUID = 1L;
private BeiJingPane pane ;
private JPanel panButton= new JPanel(); //放置按钮
private JButton bt = new JButton("载入本地图片");
private JButton bt0= new JButton("载入网络图片");
private JButton bt1= new JButton("放大");
private JButton bt2= new JButton("缩小");
private JButton bt3 =new JButton("透明度");
private JButton bt4 =new JButton("调色板");
private String name= new String();
private JLabel label = new JLabel();
private JMenuBar menuBar = new JMenuBar();
private JMenu menuOpen= new JMenu("保存网络图片");
private JMenu menuNative=new JMenu("本地图片");
private JMenu menuNet =new JMenu("网络图片");
private JMenu menuQuit=new JMenu("退出");
//private ImageIcon iic1= new ImageIcon();
private Color color ;
private Container cot= new Container();
private Demo nativeDemo;
private Demo netDemo;
private String pathDir; //存放文件路径
private int currentWidth,currentHeight;
private final int step=50;
private FilteredImageSource fileImage;
private Image img;
private Image currentImg;
private short currentTmp=255;
private boolean isBigOn=false;
private boolean isClear=false;
private boolean isChange=false;
private ImageIcon iic1=new ImageIcon();
private int colorRgb=0;
private int counts=0;
private File nativeFileName;
private URL netUrlName;
private String nativeImage;
private String netImage;
public TestDemo(String name){
this.name=name;
this.setName(this.name);
cot=this.getContentPane();
setSize(700,500);
pane =new BeiJingPane(this.getWidth(),this.getHeight());
pane.setLayout(new BorderLayout());
cot.add(pane);
panButton.add(bt);
panButton.add(bt0);
panButton.add(bt1);
panButton.add(bt2);
panButton.add(bt3);
panButton.add(bt4);
menuBar.add(menuOpen);
menuBar.add(menuNative);
menuBar.add(menuNet);
menuBar.add(menuQuit);
pane.add(panButton,BorderLayout.SOUTH);
pane.add(menuBar,BorderLayout.NORTH);
//iic1=this.paintok(getGraphics());
pane.add(label,BorderLayout.CENTER);
pane.paintComponents(getGraphics());
label.setSize(100, 150);
bt0.addActionListener(this);
bt.addActionListener(this);
bt1.addActionListener(this);
bt2.addActionListener(this);
bt3.addActionListener(this);
bt4.addActionListener(this);
menuOpen.addMouseListener(this);
menuNative.addMouseListener(this);
menuNet.addMouseListener(this);
menuQuit.addMouseListener(this);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
public void menuSelected(MenuEvent arg0){
}
public void setTupian(){
FileDialog abc=
new FileDialog(new Frame(),"test",FileDialog.SAVE) ;
abc.setVisible(true);
if(abc.getFile() != null){
pathDir=abc.getDirectory();
pathDir=pathDir.replace('\\', '/');
try{
new TSUN(abc.getFile(),pathDir,netImage);//一定要先载入网络图片再保存图片
}catch(Exception e){
new ErrorFrame();
}
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bt ){
if(nativeDemo.getFilename() != null)nativeImage=nativeDemo.getFilename();
iic1=this.paintNative(getGraphics());
label.setIcon(iic1);counts=1;
}
else if(e.getSource() == bt0){
if(netDemo.getUrl() != null)netImage=netDemo.getUrl();
iic1=this.paintNet(getGraphics());
label.setIcon(iic1);counts=2;
}
else if(e.getSource()==bt1){//点击多次会无效果
currentWidth += step;
currentHeight += step;
isBigOn = true;
if(counts==1)label.setIcon(this.paintNative(getGraphics()));
else if(counts==2)label.setIcon(this.paintNet(getGraphics()));
else
label.setIcon(this.paintok(getGraphics()));
}
else if(e.getSource()==bt2){//点击多次会无效果
currentWidth -= step;
currentHeight -= step;
isBigOn = true;
if(counts==1)label.setIcon(this.paintNative(getGraphics()));
else if(counts==2)label.setIcon(this.paintNet(getGraphics()));
else
label.setIcon(this.paintok(getGraphics()));
}
else if(e.getSource()==bt3){
currentTmp -= step;
isClear= true;
if(counts==1)label.setIcon(this.paintNative(getGraphics()));
else if(counts==2)label.setIcon(this.paintNet(getGraphics()));
else
label.setIcon(this.paintok(getGraphics()));
}
else if(e.getSource()==bt4){
isChange=true;
color=JColorChooser.showDialog(getParent(), "调色板", getBackground());
if(color != null )
colorRgb=color.getRGB();
if(counts==1)label.setIcon(this.paintNative(getGraphics()));
else if(counts==2)label.setIcon(this.paintNet(getGraphics()));
else
label.setIcon(this.paintok(getGraphics()));
}
}
public ImageIcon paintok(Graphics g){
ImageIcon iic;
try {
img = ImageIO.read(new URL("http://a4.att.hudong." +
"com/74/38/013000000890051207" +
"15389520103.jpg"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(!isClear){
fileImage = new FilteredImageSource(img.getSource(),new FilterRGB());
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
}
if( isClear){
fileImage = new FilteredImageSource(img.getSource(),new ClearRGB(currentTmp));
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
// isClear=false;
}
if(isChange){
fileImage = new FilteredImageSource(img.getSource(),new ChangeRGB(colorRgb));
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
isChange=false;
}
if(!isBigOn){
currentHeight = currentImg.getHeight(null);
currentWidth = currentImg.getWidth(null);
}
if(isBigOn){
currentImg=currentImg.getScaledInstance
( currentWidth ,currentHeight ,Image.SCALE_DEFAULT);
}
iic =new ImageIcon(currentImg);
return iic;
}
public ImageIcon paintNative(Graphics g){
ImageIcon iic;
nativeFileName=new File(nativeImage);
try {
img = ImageIO.read(nativeFileName);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
new ErrorFrame();
}
if(!isClear){
fileImage = new FilteredImageSource(img.getSource(),new FilterRGB());
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
}
if( isClear){
fileImage = new FilteredImageSource(img.getSource(),new ClearRGB(currentTmp));
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
// isClear=false;
}
if(isChange){
fileImage = new FilteredImageSource(img.getSource(),new ChangeRGB(colorRgb));
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
isChange=false;
}
if(!isBigOn){
currentHeight = currentImg.getHeight(null);
currentWidth = currentImg.getWidth(null);
}
if(isBigOn){
currentImg=currentImg.getScaledInstance
( currentWidth ,currentHeight ,Image.SCALE_DEFAULT);
}
iic =new ImageIcon(currentImg);
return iic;
}
public ImageIcon paintNet(Graphics g){
ImageIcon iic;
try {
netUrlName = new URL(netImage);
} catch (MalformedURLException e1) {
new ErrorFrame();
e1.printStackTrace();
}
try {
img = ImageIO.read(netUrlName);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();new Frame("");
}
if(!isClear){
fileImage = new FilteredImageSource(img.getSource(),new FilterRGB());
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
}
if( isClear){
fileImage = new FilteredImageSource(img.getSource(),new ClearRGB(currentTmp));
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
// isClear=false;
}
if(isChange){
fileImage = new FilteredImageSource(img.getSource(),new ChangeRGB(colorRgb));
currentImg = Toolkit.getDefaultToolkit().createImage(fileImage);
isChange=false;
}
if(!isBigOn){
currentHeight = currentImg.getHeight(null);
currentWidth = currentImg.getWidth(null);
}
if(isBigOn){
currentImg=currentImg.getScaledInstance
( currentWidth ,currentHeight ,Image.SCALE_DEFAULT);
}
iic =new ImageIcon(currentImg);
return iic;
}
public static void main(String[] args) {
new TestDemo("demo");
}
@Override
public void mouseClicked(MouseEvent arg0) {
if(arg0.getSource()==menuOpen){
this.setTupian();
}
else if(arg0.getSource()==menuNet){
netDemo =new Demo("这里输入链接");
}
else if(arg0.getSource()==menuNative){
nativeDemo =new Demo("这里输入本地图片路径");
}
else if(arg0.getSource()==menuQuit){
switch(JOptionPane.showConfirmDialog(null, "quit?"))
{
case JOptionPane.YES_OPTION:
System.exit(0);break;
}
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
/*从网络获取图片并存储在本地*/
class TSUN {
/**
* @param args
* @throws Exception
*
*/
private String pathname;
private String filename;
private String netName;
private String urlName;
public TSUN(String filename,String pathname,String netName) throws Exception{
this.netName=netName;
this.filename=filename;
this.pathname=pathname;
if(filename!=null && pathname != null)
huizhi();
}
public void huizhi() throws Exception {
urlName="http://img.hexun.com/2011-06-21/130726386.jpg";//默认地址
// URL url = new URL("http://img.hexun.com/2011-06-21/130726386.jpg");
if(netName != null) urlName= netName;
URL url=new URL(urlName);
//打开链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
byte[] data = readInputStream(inStream);
//new一个文件对象用来保存图片,默认保存当前工程根目录
File imageFile = new File(pathname+filename);
//创建输出流
FileOutputStream outStream = new FileOutputStream(imageFile);
//写入数据
outStream.write(data);
//关闭输出流
outStream.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0; //初始化的值,所以值并不是很重要
//使用一个输入流从buffer里把数据读取出来 , 每次都检测是否读到流末尾并返回实际读取字节数
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
outStream.write(buffer);
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
}
}
/*交换红蓝两种像素*/
class FilterRGB extends RGBImageFilter{
public int filterRGB(int x,int y,int rgb){
return ((rgb & 0xFF00FF00)|((rgb & 0xff0000)>>16)|((rgb & 0xff)<<16));
}
}
/*使相片透明*/
class ClearRGB extends RGBImageFilter{
private short tmp;
public ClearRGB(short s){
tmp -= s;
}
@Override
public int filterRGB(int x, int y, int rgb) {
return (rgb&(0xffffff+(tmp<<24)));
}
}
/*使相片随着调色板而改变*/
class ChangeRGB extends RGBImageFilter{
private int tmp;
public ChangeRGB(int s){
tmp -= s;
}
@Override
public int filterRGB(int x, int y, int rgb) {
return (rgb|tmp);
}
}
class BeiJingPane extends JPanel{
private ImageIcon beiJing = new ImageIcon( );
private Image img;
private static final long serialVersionUID = 1L;
public BeiJingPane(int width,int height){
try {
img=ImageIO.read(
new File("D:\\My Documents\\My Pictures\\SB.gif" ));//不能显示动态,只是静态的
img=img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
beiJing= new ImageIcon(img );
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Image img =beiJing.getImage();
g.drawImage(img, 0, 0, getParent());
}
}
class JoinmePane extends JPanel{
private ImageIcon beiJing = new ImageIcon( );
private Image img;
private static final long serialVersionUID = 1L;
public JoinmePane(int width,int height){
try {
img=ImageIO.read(
new File("D:\\My Documents\\My Pictures\\SB.gif" ));//不能显示动态,只是静态的
img=img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
beiJing= new ImageIcon(img );
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Image img =beiJing.getImage();
g.drawImage(img, 0, 0, getParent());
}
}
class Demo extends JFrame implements ActionListener
,MouseListener{
private static final long serialVersionUID = -202867187739169266L;
private JPanel pane=new JPanel();
private String url;
private ZJTextField tf = new ZJTextField();
private JButton bt= new JButton("确认");
private String filename;
private String inf;
private boolean status=false; //反应按键是否按下的状态值
public Demo(String inf){
setSize(200,300);
this.inf=inf;
pane.add(tf);
tf.setText(this.inf);
pane.add(bt);
pane.setBackground(Color.blue);
bt.addActionListener(this);
tf.addMouseListener(this);
this.add(pane);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bt){
url=tf.getText();
filename=tf.getText();
status=true;
this.dispose(); //关闭窗口
}
}
public boolean getStatus(){
return status;
}
@Override
public void mouseClicked(MouseEvent e) {
if(e.getSource()==tf){
tf.setText("");
}
}
public String getUrl(){
return url;
}
public String getFilename(){
return filename;
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0){
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
}
class ErrorFrame extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel panel=new JPanel();
private JLabel label=new JLabel("你输入了错误的信息");
public ErrorFrame(){
panel.setLayout(new BorderLayout());
panel.add(label);
panel.setBackground(Color.blue);
this.setLocationRelativeTo(null);
add(panel);
this.setVisible(true);
}
}
/*share your idea with the people all round the world
* is happy for you and me*/
//实现JTextfield 的复制、剪切、粘贴功能。
class ZJTextField extends JTextField implements MouseListener {
private static final long serialVersionUID = -2308615404205560110L;
private JPopupMenu pop = null; // 弹出菜单
private JMenuItem copy = null, paste = null, cut = null; // 三个功能菜单
public ZJTextField() {
super();
init();
}
private void init() {
this.addMouseListener(this);
pop = new JPopupMenu();
pop.add(copy = new JMenuItem("复制"));
pop.add(paste = new JMenuItem("粘贴"));
pop.add(cut = new JMenuItem("剪切"));
copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action(e);
}
});
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action(e);
}
});
cut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action(e);
}
});
this.add(pop);
}
/**
* 菜单动作
*
* @param e
*/
public void action(ActionEvent e) {
String str = e.getActionCommand();
if (str.equals(copy.getText())) { // 复制
this.copy();
} else if (str.equals(paste.getText())) { // 粘贴
this.paste();
} else if (str.equals(cut.getText())) { // 剪切
this.cut();
}
}
public JPopupMenu getPop() {
return pop;
}
public void setPop(JPopupMenu pop) {
this.pop = pop;
}
/**
* 剪切板中是否有文本数据可供粘贴
*
* @return true为有文本数据
*/
public boolean isClipboardString() {
boolean b = false;
Clipboard clipboard = this.getToolkit().getSystemClipboard();
Transferable content = clipboard.getContents(this);
try {
if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
b = true;
}
} catch (Exception e) {
}
return b;
}
/**
* 文本组件中是否具备复制的条件
*
* @return true为具备
*/
public boolean isCanCopy() {
boolean b = false;
int start = this.getSelectionStart();
int end = this.getSelectionEnd();
if (start != end)
b = true;
return b;
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
copy.setEnabled(isCanCopy());
paste.setEnabled(isClipboardString());
cut.setEnabled(isCanCopy());
pop.show(this, e.getX(), e.getY());
}
}
public void mouseReleased(MouseEvent e) {
}
}