⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 imageviewer.java

📁 基于jxta的局域网P2P文件共享,可以实现局域网中的文件p2p共享,实现文件快速传输及交流
💻 JAVA
字号:
package connex.plugins.slideshow;

import org.jdesktop.swingx.JXImageView;
import java.awt.event.InputEvent;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import javax.imageio.ImageIO;
import java.awt.datatransfer.Transferable;
import java.net.URL;
import java.io.File;
import java.util.List;
import java.awt.datatransfer.DataFlavor;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.io.IOException;
import java.util.ArrayList;
import org.jdesktop.swingx.util.PaintUtils;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyBoundsAdapter;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class ImageViewer
    extends JXImageView {
  private ImageListener listener;
  private Image image;

  public ImageViewer() {
  }

  public void setImageListener(ImageListener listener) {
    this.listener = listener;
    this.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
      public void ancestorResized(HierarchyEvent e) {
        this_ancestorResized(e);
      }
    });
    try {
      this.setTransferHandler(new DnDxHandler());
    } catch (ClassNotFoundException ex) {
    }

  }
  public void this_ancestorResized(HierarchyEvent e) {
    try {
      fitImageToScreen();
    } catch (Exception ex) {
    }
 }


  /**
   * Set the current image to an image pointed to by this File.
   * @param file a File pointing to an image
   * @throws java.io.IOException thrown if the image cannot be loaded
   */
  public void setImage(File file) throws IOException {
    System.out.println("reading: " + file.getAbsolutePath());
    setImage(ImageIO.read(file));
    if(getImage()!=null){
      listener.receiveImage(file);
    }
  }

  /**
   * Sets the current image. Can set null if there should be no image show.
   * @param image the new image to set, or null.
   */
  public void setImage(Image image) {
    super.setImage(image);
    try {
      fitImageToScreen();
    } catch (Exception ex) {
    }
    repaint();
  }

  public void fitImageToScreen() {
    if (getImage().getWidth(null) > getWidth() ||
        getImage().getHeight(null) > getHeight()) {

      double fit = (new Double("" + getWidth()) /
                    new Double(getImage().getWidth(null) + ""));

      setScale(fit);
      if ( (getImage().getHeight(null) * fit) > getHeight()) {
        fit = (new Double("" + getHeight()) /
               new Double(getImage().getHeight(null) + ""));

        setScale(fit);

      }
    }

  }

  public Action getZoomOutAction() {
    Action action = new AbstractAction() {
      public void actionPerformed(ActionEvent actionEvent) {
        setScale(getScale() * 0.9);
      }
    };
    action.putValue(Action.NAME, "Zoom Out");
    return action;
  }

  /**
   * Gets an action which will zoom the current image in by a factor of 2
   * @return an action
   */
  public Action getZoomInAction() {
    Action action = new AbstractAction() {
      public void actionPerformed(ActionEvent actionEvent) {
        setScale(getScale() * 1.1);
      }
    };
    action.putValue(Action.NAME, "Zoom In");
    return action;
  }

  public Action getOriginalSizeAction() {

    Action action = new AbstractAction() {
      public void actionPerformed(ActionEvent actionEvent) {
        setScale(1.0);
      }
    };
    action.putValue(Action.NAME, "OriginalSize");
    return action;
  }
  /**
     * Sets whether or not the user can drag images. When set to true the user can
     * drag the photo around with their mouse. Also the cursor will be set to the
     * 'hand' cursor. When set to false the user cannot drag photos around
     * and the cursor will be set to the default.
     * @param editable whether or not the user can drag images
     */




  private class DnDxHandler
      extends TransferHandler {
    DataFlavor urlFlavor;

    public DnDxHandler() throws ClassNotFoundException {
      urlFlavor = new DataFlavor("application/x-java-url;class=java.net.URL");
    }

    public void exportAsDrag(JComponent c, InputEvent evt, int action) {
      //System.out.println("exportting as drag");
      super.exportAsDrag(c, evt, action);
    }

    public int getSourceActions(JComponent c) {
      //System.out.println("get source actions: " + c);
      return COPY;
    }

    protected void exportDone(JComponent source, Transferable data, int action) {
      System.out.println("exportDone: " + source + " " + data + " " + action);
    }

    public boolean canImport(JComponent c, DataFlavor[] flavors) {
      //System.out.println("canImport:" + c);
      for (int i = 0; i < flavors.length; i++) {
        //System.out.println("testing: "+flavors[i]);
        if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
          return true;
        }
        if (DataFlavor.imageFlavor.equals(flavors[i])) {
          return true;
        }
        if (urlFlavor.match(flavors[i])) {
          return true;
        }

      }
      return false;
    }

    protected Transferable createTransferable(JComponent c) {
      System.out.println("creating a transferable");
      JXImageView view = (JXImageView) c;
      return new ImageTransferable(view.getImage(),
                                   view.getExportName(), view.getExportFormat());
    }

    public boolean importData(JComponent comp, Transferable t) {
      System.out.println("importData called");
      if (canImport(comp, t.getTransferDataFlavors())) {
        try {
          if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            List files = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
            System.out.println("doing file list flavor");
            if (files.size() > 0) {
              File file = (File) files.get(0);
              System.out.println("readingt the image: " + file.getCanonicalPath());
              /*Iterator it = ImageIO.getImageReaders(new FileInputStream(file));
                                           while(it.hasNext()) {
                  System.out.println("can read: " + it.next());
                                           }*/
              //BufferedImage img = ImageIO.read(file);
              setImage(file);
              return true;
            }
          }
          //System.out.println("doing a uri list");
          Object obj = t.getTransferData(urlFlavor);
          //System.out.println("obj = " + obj + " " + obj.getClass().getPackage() + " "
          //        + obj.getClass().getName());
          if (obj instanceof URL) {

            setImage(new File( ( (URL) obj).getFile()));
          }
          return true;
        } catch (Exception ex) {
          System.out.println(ex.getMessage());
          ex.printStackTrace();
          fireError(ex);
        }
      }
      return false;
    }

  }

  private class ImageTransferable
      implements Transferable {
    private Image img;
    private List files;
    private String exportName, exportFormat;
    public ImageTransferable(Image img, String exportName, String exportFormat) {
      this.img = img;
      this.exportName = exportName;
      this.exportFormat = exportFormat;
    }

    public DataFlavor[] getTransferDataFlavors() {
      DataFlavor[] flavors = {
          DataFlavor.imageFlavor,
          DataFlavor.javaFileListFlavor};
      return flavors;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
      if (flavor == DataFlavor.imageFlavor) {
        return true;
      }
      if (flavor == DataFlavor.javaFileListFlavor) {
        return true;
      }
      return false;
    }

    public Object getTransferData(DataFlavor flavor) throws
        UnsupportedFlavorException, IOException {
      //System.out.println("doing get trans data: " + flavor);
      if (flavor == DataFlavor.imageFlavor) {
        return img;
      }
      if (flavor == DataFlavor.javaFileListFlavor) {
        if (files == null) {
          files = new ArrayList();
          File file = File.createTempFile(exportName, "." + exportFormat);
          //System.out.println("writing to: " + file);
          ImageIO.write(PaintUtils.convertToBufferedImage(img), exportFormat,
                        file);
          files.add(file);
        }
        //System.out.println("returning: " + files);
        return files;
      }
      return null;
    }
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -