Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package hu.kazocsaba.imageviewer;
  
  import java.awt.Dimension;
  import java.awt.Point;
 import java.io.File;
A general purpose image viewer component.

The Swing component that can be added to the GUI is obtained by calling getComponent().

ImageViewer supports status bars: arbitrary components that can be added to the viewer and are displayed below the image.

Overlays can also be added to the viewer; for details, see the the documentation of the Overlay class.

Author(s):
Kazó Csaba
See also:
StatusBar
Overlay
 
 public class ImageViewer {
 	private final LayeredImageView view;
 	private final JScrollPane scroller;
 	private JPanel panel;
 	private StatusBar statusBar;
 	private boolean statusBarVisible=false;
 	private JPopupMenu popup;
 	/*
 	 * This will only be accessed from the event dispatch thread so using a static instance to share
 	 * the current directory across components is fine.
 	 */
 	private static JFileChooser saveChooser;
 
 		private void showPopup(MouseEvent e) {
 			e.consume();
 			if (p == null) {
 				p = e.getPoint();
 			}
 			.show(e.getComponent(), p.xp.y);
 		}
 		public void mousePressed(MouseEvent e) {
 			if (e.isPopupTrigger()) {
 			}
 		}
 		public void mouseReleased(MouseEvent e) {
 			if (e.isPopupTrigger()) {
 			}
 		}
 	};
Creates a new image viewer.
 
 	public ImageViewer() {
 		this(null);
 	}
Creates a new image viewer displaying the specified image.

Parameters:
image the image to display; if null then no image is displayed
See also:
setImage(java.awt.image.BufferedImage)
 
 	public ImageViewer(BufferedImage image) {
			protected JViewport createViewport() {
				return new JViewport() {
					}
					}
				};
			}
			public boolean isValidateRoot() {
				return false;
			}
		};
	}
	private static JPopupMenu createPopup(final ImageViewer imageViewer) {
Status bar toggle
		final JCheckBoxMenuItem toggleStatusBarItem = new JCheckBoxMenuItem("Status bar");
		toggleStatusBarItem.setState(imageViewer.isStatusBarVisible());
		imageViewer.addPropertyChangeListener("statusBarVisible"new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				toggleStatusBarItem.setState(imageViewer.isStatusBarVisible());
			}
		});
		toggleStatusBarItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				imageViewer.setStatusBarVisible(!imageViewer.isStatusBarVisible());
			}
		});

Zoom menu
		JMenu zoomMenu = new JMenu("Zoom");
		final JRadioButtonMenuItem zoomOriginalSize = new JRadioButtonMenuItem("Original size"imageViewer.getResizeStrategy()==.);
		zoomOriginalSize.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		final JRadioButtonMenuItem zoomShrinkToFit = new JRadioButtonMenuItem("Shrink to fit"imageViewer.getResizeStrategy()==.);
		zoomShrinkToFit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		final JRadioButtonMenuItem zoomResizeToFit = new JRadioButtonMenuItem("Resize to fit"imageViewer.getResizeStrategy()==.);
		zoomResizeToFit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
			double value;
			private CustomZoomEntry(String labeldouble value) {
				this. = label;
				this. = value;
				=new JRadioButtonMenuItem(labelimageViewer.getResizeStrategy()==. && imageViewer.getZoomFactor()==value);
					public void actionPerformed(ActionEvent e) {
					}
				});
			}
		}
		final CustomZoomEntry[] customZoomEntries={
			new CustomZoomEntry("25%", .25),
			new CustomZoomEntry("50%", .50),
			new CustomZoomEntry("75%", .75),
			new CustomZoomEntry("100%", 1),
			new CustomZoomEntry("150%", 1.5),
			new CustomZoomEntry("200%", 2),
			new CustomZoomEntry("300%", 3),
			new CustomZoomEntry("500%", 5),
			new CustomZoomEntry("1000%", 10),
			new CustomZoomEntry("2000%", 20),
			new CustomZoomEntry("5000%", 50)
		};
		final ButtonGroup group = new ButtonGroup();
		group.add(zoomOriginalSize);
		group.add(zoomShrinkToFit);
		group.add(zoomResizeToFit);
		zoomMenu.add(zoomOriginalSize);
		zoomMenu.add(zoomShrinkToFit);
		zoomMenu.add(zoomResizeToFit);
		zoomMenu.add(new JSeparator());
		for (CustomZoomEntry czecustomZoomEntries) {
			zoomMenu.add(cze.menuItem);
			group.add(cze.menuItem);
		}
		imageViewer.addPropertyChangeListener("resizeStrategy"new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				switch ((ResizeStrategy)evt.getNewValue()) {
					case :
						zoomOriginalSize.setSelected(true);
						break;
						zoomResizeToFit.setSelected(true);
						break;
						zoomShrinkToFit.setSelected(true);
						break;
						for (CustomZoomEntry czecustomZoomEntries) {
							if (cze.value==imageViewer.getZoomFactor()) {
								cze.menuItem.setSelected(true);
								break;
							}
						}
						break;
					default:
						throw new AssertionError("Unknown resize strategy: "+evt.getNewValue());
				}
			}
		});
		imageViewer.addPropertyChangeListener("zoomFactor"new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
					for (CustomZoomEntry czecustomZoomEntries) {
						if (cze.value==imageViewer.getZoomFactor()) {
							cze.menuItem.setSelected(true);
							break;
						}
					}
				}
			}
		});

Save command
		JMenuItem saveImageMenuItem=new JMenuItem("Save image...");
		saveImageMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (==null) {
					.setDialogTitle("Save image...");
				}
					BufferedImage image=imageViewer.getImage();
					if (image==null) {
						JOptionPane.showMessageDialog(imageViewer.getComponent(), "No image""Error".);
else {
						try {
							if (name.endsWith(".jpg")) {
								ImageIO.write(image"jpg"f);
else if (name.endsWith(".png")) {
								ImageIO.write(image"png"f);
else {
								f=new File(f.getPath()+".png");
								ImageIO.write(image"png"f);
							}
catch (IOException ex) {
							JOptionPane.showMessageDialog(imageViewer.getComponent(), "Cannot write image to "+f.getAbsolutePath(), "Error".);
						}
					}
				}
			}
		});

Pixelated zoom toggle
		final JCheckBoxMenuItem togglePixelatedZoomItem = new JCheckBoxMenuItem("Pixelated zoom");
		togglePixelatedZoomItem.setState(imageViewer.isPixelatedZoom());
		imageViewer.addPropertyChangeListener("pixelatedZoom"new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				togglePixelatedZoomItem.setState(imageViewer.isPixelatedZoom());
			}
		});
		togglePixelatedZoomItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				imageViewer.setPixelatedZoom(!imageViewer.isPixelatedZoom());
			}
		});
		JPopupMenu popup = new JPopupMenu();
		popup.add(toggleStatusBarItem);
		popup.add(zoomMenu);
		popup.add(togglePixelatedZoomItem);
		popup.add(saveImageMenuItem);
		return popup;
	}
Sets the status bar component for this image viewer. The new status bar is made visible only if the statusBarVisible property is true. If statusBar is null this method removes any existing status bar.

Parameters:
statusBar the new status bar component to set
Throws:
java.lang.IllegalArgumentException if the status bar has already been added to a different image viewer
	public void setStatusBar(StatusBar statusBar) {
		if (statusBar==this.return;
		if (statusBar.getImageViewer()!=null)
			throw new IllegalArgumentException("Status bar already added to an image viewer");
		StatusBar oldStatusBar=this.;
		if (oldStatusBar!=null) {
			.remove(oldStatusBar.getComponent());
			oldStatusBar.setImageViewer(null);
		}
		this.=statusBar;
		if (this.!=null) {
		}
		.firePropertyChange("statusBar"oldStatusBarstatusBar);
	}
Sets whether the status bar is visible.

Parameters:
statusBarVisible true, if the status bar should be visible; false otherwise
	public void setStatusBarVisible(boolean statusBarVisible) {
		if (this. == statusBarVisiblereturn;
		if (!=null)
			.getComponent().setVisible(statusBarVisible);
		boolean prev = this.;
		this. = statusBarVisible;
		.firePropertyChange("statusBarVisible"prevstatusBarVisible);
	}
Returns whether the status bar is set to be visible.

Returns:
the statusBarVisible property
	public boolean isStatusBarVisible() {
	}
Returns the image viewer component that can be displayed.

Returns:
the image viewer component
		return ;
	}
Sets the image displayed by the viewer.

Parameters:
image the new image to display; if null then no image is displayed
	public void setImage(BufferedImage image) {
	}
Returns the currently displayed image.

Returns:
the current image, or null if no image is displayed
	public BufferedImage getImage() {
		return .getImage();
	}
Sets the resize strategy this viewer should use.

Parameters:
resizeStrategy the new resize strategy
	public void setResizeStrategy(ResizeStrategy resizeStrategy) {
		.setResizeStrategy(resizeStrategy);
	}
Returns the current resize strategy.

Returns:
the current resize strategy
	}

Sets whether the image should be resized with nearest neighbor interpolation when it is expanded.

Parameters:
pixelatedZoom the new value of the pixelatedZoom property
	public void setPixelatedZoom(boolean pixelatedZoom) {
		.setPixelatedZoom(pixelatedZoom);
	}
Returns the current pixelated zoom setting.

Returns:
the current pixelated zoom setting
	public boolean isPixelatedZoom() {
	}

Returns the zoom factor used when resize strategy is CUSTOM_ZOOM.

Returns:
the custom zoom factor
	public double getZoomFactor() {
	}

Sets the zoom factor to use when the resize strategy is CUSTOM_ZOOM.

Note that calling this function does not change the current resize strategy.

Parameters:
newZoomFactor the new zoom factor for the CUSTOM_ZOOM strategy
Throws:
java.lang.IllegalArgumentException if newZoomFactor is not a positive number
	public void setZoomFactor(double newZoomFactor) {
		.setZoomFactor(newZoomFactor);
	}
Returns the transformation that is applied to the image. Most commonly the transformation is the concatenation of a uniform scale and a translation.

The AffineTransform instance returned by this method should not be modified.

Returns:
the transformation applied to the image before painting
	}

Adds an overlay as the specified layer.

Parameters:
overlay the overlay to add
layer the layer to add the overlay to; higher layers are on top of lower layers; the image resides in layer 0
	public void addOverlay(Overlay overlayint layer) {
		.addOverlay(overlaylayer);
	}

Adds an overlay to layer 1.

Parameters:
overlay the overlay to add
	public void addOverlay(Overlay overlay) {
		addOverlay(overlay, 1);
	}
Removes an overlay from the image viewer.

Parameters:
overlay the overlay to remove
Throws:
java.lang.IllegalArgumentException if the overlay is not in the image viewer
	public void removeOverlay(Overlay overlay) {
	}
Adds the specified mouse listener to receive mouse events from the image component of this image viewer. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the mouse listener
	public void addMouseListener(MouseListener l) {
	}
Removes the specified mouse listener so that it no longer receives mouse motion events from the image component of this image viewer. This method performs no function, nor does it throw an exception, if the listener specified by the argument was not previously added to this component. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the mouse motion listener
	}
Adds the specified mouse motion listener to receive mouse events from the image component of this image viewer. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the mouse listener
	}
Removes the specified mouse motion listener so that it no longer receives mouse motion events from the image component of this image viewer. This method performs no function, nor does it throw an exception, if the listener specified by the argument was not previously added to this component. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the mouse motion listener
	}
Adds the specified image mouse motion listener to this viewer. The listener is notified as the mouse moves over pixels of the image. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the image mouse motion listener
	}

Removes the specified image mouse motion listener so that it no longer receives mouse motion events from the image component of this image viewer. This method performs no function, nor does it throw an exception, if the listener specified by the argument was not previously added to this component. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the mouse motion listener
	}

Adds the specified image mouse listener to this viewer. The listener is notified as mouse buttons are clicked over pixels of the image. If listener l is null, no exception is thrown and no action is performed.

Parameters:
l the image mouse motion listener
	}

Removes the specified image mouse listener so that it no longer receives mouse click events from the image component of this image viewer. This method performs no function, nor does it throw an exception, if the listener specified by the argument was not previously added to this component. If the listener l is null, no exception is thrown and no action is performed.

Parameters:
l the mouse motion listener
	}

Adds a PropertyChangeListener to the listener list. The same listener object may be added more than once, and will be called as many times as it is added. If the listener is null, no exception is thrown and no action is taken.

Parameters:
l the listener to be added
	}

Remove a PropertyChangeListener from the listener list. This removes a listener that was registered for all properties. If the listener was added more than once, it will be notified one less time after being removed. If the listener is null, or was never added, no exception is thrown and no action is taken.

Parameters:
l the listener to remove
	}

Adds a PropertyChangeListener for a specific property. The listener will be invoked only when a call on firePropertyChange names that specific property. The same listener object may be added more than once. For each property, the listener will be invoked the number of times it was added for that property. If the property name or the listener is null, no exception is thrown and no action is taken.

Parameters:
name the name of the property to listen on
l the listener to add
	}

Remove a PropertyChangeListener from the listener list. This removes a PropertyChangeListener that was registered for all properties. If the listener was added more than once, it will be notified one less time after being removed. If the listener is null, or was never added, no exception is thrown and no action is taken.

Parameters:
name the name of the property that was listened on
l the listener to remove
	}

Returns the scroll pane of the image viewer.

Returns:
the scroll pane
		return ;
	}
Adds a component to the trackSizeIfEmpty set. If this component has no image set but one of the tracked ones does, then the size of this component will be set to match the size of the image displayed in one of the tracked components. This method is useful if the scroll bars of image viewers are synchronized, because if a viewer has no image set, it can cause the scrolling of a viewer that has an image set not to work.

Tracking is symmetrical and transitive.

Parameters:
c the component to track
	}

Returns the image pixel corresponding to the given point. If the clipToImage parameter is false, then the function will return an appropriately positioned pixel on an infinite plane, even if the point is outside the image bounds. If clipToImage is true then the function will return null for such positions, and any non-null return value will be a valid image pixel.

Parameters:
p a point in component coordinate system
clipToImage whether the function should return null for positions outside the image bounds
Returns:
the corresponding image pixel
Throws:
java.lang.IllegalStateException if clipToImage is true but there is no image
	public Point pointToPixel(Point pboolean clipToImage) {
		return .pointToPixel(pclipToImage);
	}
New to GrepCode? Check out our FAQ X