sim.display
Class Display2D

java.lang.Object
  extended byjava.awt.Component
      extended byjava.awt.Container
          extended byjavax.swing.JComponent
              extended bysim.display.Display2D
All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, Steppable

public class Display2D
extends javax.swing.JComponent
implements Steppable

Display2D holds, displays, and manipulates 2D Portrayal objects, allowing the user to scale them, scroll them, change how often they're updated, take snapshots, and generate Quicktime movies. Display2D is Steppable, and each time it is stepped it redraws itself. Display2D also handles double-click events, routing them to the underlying portrayals as inspector requests.

In addition to various GUI widgets, Display2D holds a JScrollView which in turn holds a Display2D.InnerDisplay2D (a JComponent responsible for doing the actual drawing). Display2D can be placed in a JFrame; indeed it provides a convenience function to sprout its own JFrame with the method createFrame(). You can put Display2D in your own JFrame if you like, but you should try to call Display2D.quit() when the frame is disposed.

Display2D's constructor takes a height and a width; this will be the "expected" height and width of the underlying portrayal region when the Display2D is scaled to 1.0 (the default). The portrayals will also have an origin at (0,0) -- the top left corner. Display2D will automatically clip the portrayals to the area (0,0) to (width * scale, height * scale).

Display2D's step() method is typically called from the underlying schedule thread; this means that it has to be careful about painting as Swing widgets expect to be painted in the event loop thread. Display2D handles this in two ways. First, on MacOS X, the step() method calls repaint(), which will in turn call paintComponent() from the event loop thread at a time when the underlying schedule thread is doing nothing -- see Console. Second, on Windows and XWindows, the step() method immediately calls paintComponent(). Different OSes do it differently because MacOS X is far more efficient using standard repaint() calls, which get routed through Quartz. The step() method also updates various widgets using SwingUtilities.invokeLater().

See Also:
Serialized Form

Nested Class Summary
 class Display2D.InnerDisplay2D
          The object which actually does all the drawing.
 class Display2D.OptionPane
          Option pane
 
Nested classes inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
static javax.swing.ImageIcon CAMERA_ICON
           
 Display2D.InnerDisplay2D insideDisplay
          The 2D display inside the scroll view.
static boolean isMacOSX
          Set to true if we're running on a Mac
static boolean isWindows
          Set to true if we're running on Windows
static javax.swing.ImageIcon LAYERS_ICON
           
static javax.swing.ImageIcon MOVIE_OFF_ICON
           
static javax.swing.ImageIcon MOVIE_ON_ICON
           
 MovieMaker movieMaker
          Our movie maker, if one is running, else null.
 Display2D.OptionPane optionPane
          Our option pane
static javax.swing.ImageIcon OPTIONS_ICON
           
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
Display2D(double width, double height, GUIState simulation, long interval)
          Creates a Display2D with the provided width and height for its portrayal region, attached to the provided simulation, and displaying itself with the given interval (which must be > 0).
 
Method Summary
 void attach(FieldPortrayal2D portrayal, java.lang.String name)
          Attaches a portrayal to the Display2D, along with the provided human-readable name for the portrayal.
 void attach(FieldPortrayal2D portrayal, java.lang.String name, java.awt.geom.Rectangle2D.Double bounds)
          Attaches a portrayal to the Display2D, along with the provided human-readable name for the portrayal.
 javax.swing.JFrame createFrame()
          Creates a frame holding the Display2D.
 void createInspectors(java.awt.geom.Rectangle2D.Double rect, GUIState simulation)
          Determines the inspectors appropriate for the given selection region (rect), and sends them on to the Controller.
 java.util.ArrayList detatchAll()
          Detatches all portrayals from the Display2D.
static java.lang.String ensureFileEndsWith(java.lang.String filename, java.lang.String ending)
          Utility method.
 void ensureRepaintHeader()
          Force-repaints the header by running the repaint through an invokeLater(), which seems to be more stable than just calling header.repaint() directly.
protected  void finalize()
          Quits the Display2D.
 java.awt.Paint getBackdrop()
          Returns the backdrop color or paint.
 long getInterval()
          Gets how many ticks are skipped before the display updates itself.
 double getScale()
          Returns the scale (the zoom value) of the Display2D
 boolean isClipping()
          Returns true if the Display2D is clipping the drawing area to the user-specified height and width
 Bag[] objectsHitBy(java.awt.geom.Rectangle2D.Double rect)
          Returns LocationWrappers for all the objects which fall within the coordinate rectangle specified by rect.
 void quit()
          Quits the Display2D.
 void reset()
          Resets the Display2D so it reschedules itself.
 void setBackdrop(java.awt.Paint c)
          Specify the backdrop color or other paint.
 void setClipping(boolean val)
          Sets the Display2D to clip or to not clip to the user-specified height and width when drawing
 void setInterval(long i)
          Sets how many ticks are skipped before the display updates itself.
 void setScale(double val)
          Sets the scale (the zoom value) of the Display2D
 void startMovie()
          Starts a Quicktime movie on the given Display2D.
 void step(SimState state)
          Steps the Display2D in the GUIState schedule.
 void stopMovie()
          Stops a Quicktime movie and cleans up, flushing the remaining frames out to disk.
 void takeSnapshot()
          Takes a snapshot of the Display2D's currently displayed simulation.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, 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, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

isMacOSX

public static final boolean isMacOSX
Set to true if we're running on a Mac


isWindows

public static final boolean isWindows
Set to true if we're running on Windows


LAYERS_ICON

public static final javax.swing.ImageIcon LAYERS_ICON

MOVIE_ON_ICON

public static final javax.swing.ImageIcon MOVIE_ON_ICON

MOVIE_OFF_ICON

public static final javax.swing.ImageIcon MOVIE_OFF_ICON

CAMERA_ICON

public static final javax.swing.ImageIcon CAMERA_ICON

OPTIONS_ICON

public static final javax.swing.ImageIcon OPTIONS_ICON

movieMaker

public MovieMaker movieMaker
Our movie maker, if one is running, else null.


insideDisplay

public Display2D.InnerDisplay2D insideDisplay
The 2D display inside the scroll view. Does the actual drawing of the simulation.


optionPane

public Display2D.OptionPane optionPane
Our option pane

Constructor Detail

Display2D

public Display2D(double width,
                 double height,
                 GUIState simulation,
                 long interval)
Creates a Display2D with the provided width and height for its portrayal region, attached to the provided simulation, and displaying itself with the given interval (which must be > 0).

Method Detail

setScale

public void setScale(double val)
Sets the scale (the zoom value) of the Display2D


getScale

public double getScale()
Returns the scale (the zoom value) of the Display2D


setInterval

public void setInterval(long i)
Sets how many ticks are skipped before the display updates itself.


getInterval

public long getInterval()
Gets how many ticks are skipped before the display updates itself.


isClipping

public boolean isClipping()
Returns true if the Display2D is clipping the drawing area to the user-specified height and width


setClipping

public void setClipping(boolean val)
Sets the Display2D to clip or to not clip to the user-specified height and width when drawing


setBackdrop

public void setBackdrop(java.awt.Paint c)
Specify the backdrop color or other paint. The backdrop is the region behind where the simulation actually draws. If set to null, no color/paint is used.


getBackdrop

public java.awt.Paint getBackdrop()
Returns the backdrop color or paint. The backdrop is the region behind where the simulation actually draws. If set to null, no color/paint is used.


finalize

protected void finalize()
                 throws java.lang.Throwable
Quits the Display2D. Okay, so finalize is evil and we're not supposed to rely on it. We're not. But it's an additional cargo-cult programming measure just in case.

Throws:
java.lang.Throwable

quit

public void quit()
Quits the Display2D. Called by the Display2D's frame if the Display2D made the frame itself. Also called by finalize(). Otherwise you should call this method before destroying the Display2D.


reset

public void reset()
Resets the Display2D so it reschedules itself. This is useful when reusing the Display2D.


attach

public void attach(FieldPortrayal2D portrayal,
                   java.lang.String name)
Attaches a portrayal to the Display2D, along with the provided human-readable name for the portrayal. The portrayal will be attached with an origin at (0,0) and a width and height equal to the Display2D's default width and height. Portrayals are drawn on-screen in the order that they are attached; thus the "top-most" portrayal will be the last one attached.


attach

public void attach(FieldPortrayal2D portrayal,
                   java.lang.String name,
                   java.awt.geom.Rectangle2D.Double bounds)
Attaches a portrayal to the Display2D, along with the provided human-readable name for the portrayal. The portrayal's attached origin, width and height is given in the bounds rectangle.


detatchAll

public java.util.ArrayList detatchAll()
Detatches all portrayals from the Display2D.


objectsHitBy

public Bag[] objectsHitBy(java.awt.geom.Rectangle2D.Double rect)
Returns LocationWrappers for all the objects which fall within the coordinate rectangle specified by rect. This rectangle is in the coordinate system of the (InnerDisplay2D) component inside the scroll view of the Display2D class. The return value is an array of Bags. For each FieldPortrayal attached to the Display2D, one Bag is returned holding all the LocationWrappers for objects falling within the rectangle which are associated with that FieldPortrayal's portrayed field. The order of the Bags in the array is the same as the order of the FieldPortrayals in the Display2D's portrayals list.


createInspectors

public void createInspectors(java.awt.geom.Rectangle2D.Double rect,
                             GUIState simulation)
Determines the inspectors appropriate for the given selection region (rect), and sends them on to the Controller.


ensureRepaintHeader

public void ensureRepaintHeader()
Force-repaints the header by running the repaint through an invokeLater(), which seems to be more stable than just calling header.repaint() directly. This fixes a bug in MacOS X 1.3.1 which doesn't redraw the header when we resize the window.


createFrame

public javax.swing.JFrame createFrame()
Creates a frame holding the Display2D. This is the best method to create the frame, rather than making a frame and putting the Display2D in it. If you prefer the latter, then you need to handle two things. First, when the frame is disposed, you need to call quit() on the Display2D. Second, if you care about distribution to MacOS X Java 1.3.1, you need to call ensureRepaintHeader() whenever the window is resized.


ensureFileEndsWith

public static java.lang.String ensureFileEndsWith(java.lang.String filename,
                                                  java.lang.String ending)
Utility method. Returns a filename guaranteed to end with the given ending.


takeSnapshot

public void takeSnapshot()
Takes a snapshot of the Display2D's currently displayed simulation. Ought only be done from the main event loop.


startMovie

public void startMovie()
Starts a Quicktime movie on the given Display2D. The size of the movie frame will be the size of the display at the time this method is called. This method ought to be called from the main event loop. Most of the default movie formats provided will result in a giagantic movie, which you can re-encode using something smarter (like the Animation or Sorenson codecs) to put to a reasonable size. On the Mac, Quicktime Pro will do this quite elegantly.


stopMovie

public void stopMovie()
Stops a Quicktime movie and cleans up, flushing the remaining frames out to disk. This method ought to be called from the main event loop.


step

public void step(SimState state)
Steps the Display2D in the GUIState schedule. If we're in MacOS X, this results in a repaint() request generated. If we're in Windows or X Windows, this results in a direct call to paintComponent on the insideDisplay. It's OS-dependent because different operating systems draw faster in different ways.

Specified by:
step in interface Steppable