Package ca.corbett.extras.image
Class ImagePanel
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
ca.corbett.extras.image.ImagePanel
- All Implemented Interfaces:
MouseListener,MouseMotionListener,MouseWheelListener,ImageObserver,MenuContainer,Serializable,EventListener,Accessible
public class ImagePanel
extends JPanel
implements MouseListener, MouseWheelListener, MouseMotionListener
A custom JPanel extension that can display an image in configurable ways, with optional
handling of mouse events to allow zooming and scrolling. Defaults are provided for
all configuration options. Alternatively, you can create an ImagePanelConfig
instance and override some or all of those defaults.
- Since:
- 2012-09-22 (originally for StegPng, later generified for ca.corbett.util.ui)
- Author:
- scorbo2
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanelNested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponentNested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected BufferedImageA handle on the image which will be displayed in this panel.An optional map of extra, caller-supplied attributesprotected ImageIconA handle on the ImageIcon which will be displayed in this panel.protected JLabelA wrapper label for the imageIcon, if set.protected intUsed internally for image placementprotected intUsed internally for image placementprotected intThe last rendered height of our image.If the image is scaled or if the panel is resized, the image may need to be re-rendered at a different size.protected intThe last rendered width of our image.protected PointUsed internally for mouse dragging operationsprotected PointUsed internally for mouse dragging operationsprotected ImagePanelConfigA handle on the original ImagePanelConfig (needed because we'll modify these)protected JPopupMenuAn optional popup menu for this ImagePanelprotected ImagePanelConfigA handle on our ImagePanelConfig configuration objectprotected PointA Point which represents the co-ordinates around which zoom operations will happenprotected doubleStores the current zoomFactor (1 for no zoom, higher numbers = more zoom)Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
ConstructorsModifierConstructorDescriptionCreates a new ImagePanel with a default ImagePanelConfig and no image.Creates an empty ImagePanel (no image) with the given ImagePanelConfig.ImagePanel(BufferedImage image) Creates an ImagePanel with the given image and with a default ImagePanelConfig.ImagePanel(BufferedImage image, ImagePanelConfig props) Creates an ImagePanel with the given image and the given ImagePanelConfig.protectedImagePanel(BufferedImage image, ImageIcon icon, ImagePanelConfig props) Invoked internally to set up a new ImagePanel with EITHER the given BufferedImage or the given ImageIcon - one of those two must be null, as both can't be displayed.ImagePanel(ImageIcon icon) Creates an ImagePanel with the given ImageIcon and a default ImagePanelConfig.ImagePanel(ImageIcon icon, ImagePanelConfig props) Creates an ImagePanel with the given ImageIcon and ImagePanelConfig. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddMouseListener(MouseListener listener) voidapplyProperties(ImagePanelConfig props) Applies the configuration options in the given ImagePanelConfig instance to this panel.voidClears the list of extra attributes.getExtraAttribute(String name) Returns the value of the named extra attribute, if it exists.getImage()Returns the current BufferedImage, if one is set.intReturns the height of the current BufferedImage or the current ImageIcon, depending on which one is set.Returns the current ImageIcon, if one is set.intReturns the width of the current BufferedImage or the current ImageIcon, depending on which one is set.Takes a co-ordinate inside this panel and translates it into a co-ordinate inside the image, taking current zoom factor and location into account.Returns the current zoom point, if set.doubleReturns the current zoom factor.voidInvoked automatically when the user clicks on the panel.voidInvoked automatically when the user drags the mouse on this panel.voidIgnored; does nothing.voidIgnored; does nothing.voidIgnored; does nothing.voidInvoked automatically when the user presses a mouse button over the panel.voidIgnored; does nothing.voidInvoked automatically when the user mouse wheels while over this panel.voidOverridden from JComponent, this method renders the image using current options.voidremoveMouseListener(MouseListener listener) voidResets the zoom center to be the center of the image.voidsetExtraAttribute(String name, Object value) Sets an optional "extra attribute", which can be anything caller-defined.voidsetImage(BufferedImage image) Replaces the current image with the given one.voidsetImageIcon(ImageIcon icon) voidsetPopupMenu(JPopupMenu menu) Associates the given JPopupMenu with this ImagePanel instance.protected voidsetRenderingQuality(Graphics2D graphics2D) Internal method to set rendering quality hints on a given Graphics2D instance based on the current ImagePanelConfig.getRenderingQuality() value.voidsetZoomCenter(Point point) Sets the point around which to base zoom operations.voidsetZoomFactor(double newFactor) Sets the factor for zooming - this is scaled around 1.0 being synonymous with "no zoom".voidEnabled (or re-enabled) STRETCH DisplayMode, and distorts the image to fit the panel.protected PointTakes a co-ordinate inside this panel and translates it into a co-ordinate inside the image, taking current zoom factor and location into account.voidEnables (or re-enables) autoBestFit, and renders the image to fit the panel.voidzoomIn()Zooms in towards the center of the image.voidZooms in around the given point.voidzoomOut()Zooms out from the center of the image.voidZooms out from the given point.Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUIMethods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeMethods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
extraAttributes
An optional map of extra, caller-supplied attributes. * -
dBuffer
A handle on the image which will be displayed in this panel. This is set to null and ignored if an ImageIcon is set instead. -
imageIcon
A handle on the ImageIcon which will be displayed in this panel. This is set to null and ignored if a BufferedImage is set instead. -
imageIconLabel
A wrapper label for the imageIcon, if set. If a BufferedImage is set instead of an ImageIcon, then this property is ignored. -
lastRenderedImageWidth
protected int lastRenderedImageWidthThe last rendered width of our image. If the image is scaled or if the panel is resized, the image may need to be re-rendered at a different size. -
lastRenderedImageHeight
protected int lastRenderedImageHeightThe last rendered height of our image.If the image is scaled or if the panel is resized, the image may need to be re-rendered at a different size. -
properties
A handle on our ImagePanelConfig configuration object. * -
originalProperties
A handle on the original ImagePanelConfig (needed because we'll modify these). * -
zoomFactor
protected double zoomFactorStores the current zoomFactor (1 for no zoom, higher numbers = more zoom). * -
zoomCenter
A Point which represents the co-ordinates around which zoom operations will happen. * -
mouseDragPoint
Used internally for mouse dragging operations. * -
mouseDragDelta
Used internally for mouse dragging operations. * -
imageX
protected int imageXUsed internally for image placement. * -
imageY
protected int imageYUsed internally for image placement. * -
popupMenu
An optional popup menu for this ImagePanel. *
-
-
Constructor Details
-
ImagePanel
public ImagePanel()Creates a new ImagePanel with a default ImagePanelConfig and no image. -
ImagePanel
Creates an ImagePanel with the given image and with a default ImagePanelConfig.- Parameters:
image- The image to display in this panel. Can be null.
-
ImagePanel
Creates an empty ImagePanel (no image) with the given ImagePanelConfig.- Parameters:
ipc- The ImagePanelConfig specifying our panel configuration.
-
ImagePanel
Creates an ImagePanel with the given ImageIcon and a default ImagePanelConfig.- Parameters:
icon- The ImageIcon to display in this panel. Can be null.
-
ImagePanel
Creates an ImagePanel with the given image and the given ImagePanelConfig.- Parameters:
image- The image to display in this panel. Can be null.props- The ImagePanelConfig specifying our panel configuration.
-
ImagePanel
Creates an ImagePanel with the given ImageIcon and ImagePanelConfig.- Parameters:
icon- The ImageIcon to display in this panel. Can be null.props- The ImagePanelConfig specifying our panel configuration.
-
ImagePanel
Invoked internally to set up a new ImagePanel with EITHER the given BufferedImage or the given ImageIcon - one of those two must be null, as both can't be displayed.- Parameters:
image- A BufferedImage to display. Must be null if icon is set.icon- An ImageIcon to display. Must be null if image is set.props- The ImagePanelConfig to use. Can be null for default configuration.
-
-
Method Details
-
applyProperties
Applies the configuration options in the given ImagePanelConfig instance to this panel. Changes take effect immediately and do not require a manual call to repaint(). If the supplied ImagePanelConfig is null, a default properties instance will be used instead.- Parameters:
props- The ImagePanelConfig instance containing our new configuration.
-
setExtraAttribute
Sets an optional "extra attribute", which can be anything caller-defined. Can be retrieved later by getExtraAttribute.- Parameters:
name- The name of this extra attribute. Case insensitive.value- The value of this extra attribute. Accepted as-is and not modified by this class.
-
getExtraAttribute
Returns the value of the named extra attribute, if it exists.- Parameters:
name- The name of the extra attribute. Case insensitive.- Returns:
- The named extra attribute, or null if no such attribute is set.
-
clearExtraAttributes
public void clearExtraAttributes()Clears the list of extra attributes. -
getImageWidth
public int getImageWidth()Returns the width of the current BufferedImage or the current ImageIcon, depending on which one is set. If neither is set, returns 0.- Returns:
- The width of the current image, or 0 if no image is shown.
-
getImageHeight
public int getImageHeight()Returns the height of the current BufferedImage or the current ImageIcon, depending on which one is set. If neither is set, returns 0.- Returns:
- The height of the current image, or 0 if no image is shown.
-
setZoomFactor
public void setZoomFactor(double newFactor) Sets the factor for zooming - this is scaled around 1.0 being synonymous with "no zoom". A value of 0.5 means half normal size, a value of 2.0 means double normal size, and so on. Setting any value here will automatically disable autoBestFit. To re-enable best bit, you can either re-apply the ImagePanelConfig or simply call zoomBestFit in this class.- Parameters:
newFactor- The new zoom factor.
-
getZoomFactor
public double getZoomFactor()Returns the current zoom factor.- Returns:
- The current zoom factor. See setZoomFactor for more information.
-
zoomIn
Zooms in around the given point. Invoking this will automatically disable autoBestFit. To re-enable it, try zoomBestFit() or re-apply your ImagePanelConfig.- Parameters:
point- The Point around which to zoom. To zoom to the center, use zoomIn() instead.
-
zoomIn
public void zoomIn()Zooms in towards the center of the image. Invoking this will automatically disable autoBestFit. To re-enable best fit, try zoomBestFit() or re-apply your ImagePanelConfig(). -
zoomOut
Zooms out from the given point. Invoking this will automatically disable autoBestFit. To re-enable best fit, try zoomBestFit() or re-apply your ImagePanelConfig().- Parameters:
point- The point around which to zoom out. To zoom out from center, try zoomOut instead.
-
zoomOut
public void zoomOut()Zooms out from the center of the image. Invoking this will automatically disable autoBestFit. To re-enable best fit, try zoomBestFit() or re-apply your ImagePanelConfig(). -
zoomBestFit
public void zoomBestFit()Enables (or re-enables) autoBestFit, and renders the image to fit the panel. -
stretchImage
public void stretchImage()Enabled (or re-enabled) STRETCH DisplayMode, and distorts the image to fit the panel. -
setZoomCenter
Sets the point around which to base zoom operations. Only used if displayMode is CUSTOM. By default, the zoom center is the center of the image.- Parameters:
point- The new point within the image around which to base zoom in/zoom out operations.
-
getZoomCenter
Returns the current zoom point, if set.- Returns:
- The current point around which to base zoom operations, or null if not set.
-
resetZoomCenter
public void resetZoomCenter()Resets the zoom center to be the center of the image. -
getTranslatedPoint
Takes a co-ordinate inside this panel and translates it into a co-ordinate inside the image, taking current zoom factor and location into account.- Parameters:
p- The point inside this panel- Returns:
- A point inside the image that corresponds to the input point.
-
setImage
Replaces the current image with the given one. If autoBestFit is enabled, the image will be scaled up or down as needed. Else it is simply shown at scale factor 1.- Parameters:
image- The new image to be displayed, or null.
-
setImageIcon
-
getImage
Returns the current BufferedImage, if one is set.- Returns:
- The BufferedImage currently being displayed in this panel, if there is one.
-
getImageIcon
Returns the current ImageIcon, if one is set.- Returns:
- The ImageIcon being displayed in this panel, if there is one.
-
paintComponent
Overridden from JComponent, this method renders the image using current options.- Overrides:
paintComponentin classJComponent- Parameters:
g- The Graphics object to use for rendering.
-
setRenderingQuality
Internal method to set rendering quality hints on a given Graphics2D instance based on the current ImagePanelConfig.getRenderingQuality() value.- Parameters:
graphics2D- The Graphics2D object to update.
-
translatePoint
Takes a co-ordinate inside this panel and translates it into a co-ordinate inside the image, taking current zoom factor and location into account.- Parameters:
p- The point inside this panel- Returns:
- A point inside the image that corresponds to the input point.
-
mouseClicked
Invoked automatically when the user clicks on the panel. If click to zoom is enabled in our properties, you can left click to zoom in and right click to zoom out. Otherwise this does nothing.- Specified by:
mouseClickedin interfaceMouseListener- Parameters:
e- The MouseEvent in question.
-
mousePressed
Invoked automatically when the user presses a mouse button over the panel. If mouse dragging is enabled, you can scroll the image by clicking and dragging it (only if the image is larger than the panel or is zoomed in to that extent). If mouse dragging is disabled, or if the image is smaller than the panel, this does nothing.- Specified by:
mousePressedin interfaceMouseListener- Parameters:
e- The MouseEvent in question.
-
mouseReleased
Ignored; does nothing.- Specified by:
mouseReleasedin interfaceMouseListener- Parameters:
e- Ignored.
-
mouseEntered
Ignored; does nothing.- Specified by:
mouseEnteredin interfaceMouseListener- Parameters:
e- Ignored.
-
mouseExited
Ignored; does nothing.- Specified by:
mouseExitedin interfaceMouseListener- Parameters:
e- Ignored.
-
mouseWheelMoved
Invoked automatically when the user mouse wheels while over this panel. If zoom on mouse wheel is enabled, you can zoom in by wheeling up and zoom out by wheeling down. If zoom on mouse wheel is disabled, this does nothing.- Specified by:
mouseWheelMovedin interfaceMouseWheelListener- Parameters:
e- The MouseEvent in question.
-
mouseDragged
Invoked automatically when the user drags the mouse on this panel. If mouse dragging is enabled, you can click and drag to scroll the image around in cases where the image is larger than the panel (or is zoomed in to that extent). If mouse dragging is disabled, or if the image is smaller than the panel, this does nothing.- Specified by:
mouseDraggedin interfaceMouseMotionListener- Parameters:
e- The MouseEvent in question.
-
mouseMoved
Ignored; does nothing.- Specified by:
mouseMovedin interfaceMouseMotionListener- Parameters:
e- Ignored.
-
setPopupMenu
Associates the given JPopupMenu with this ImagePanel instance. The popup menu will only pop if the current image is not null.- Parameters:
menu- The new JPopupMenu to use. Can be null to disable popup menu.
-
addMouseListener
- Overrides:
addMouseListenerin classComponent
-
removeMouseListener
- Overrides:
removeMouseListenerin classComponent
-