diff --git a/core/src/build/conf/eclipse-code-clean.xml b/core/src/build/conf/eclipse-code-clean.xml new file mode 100644 index 0000000..ae96c75 --- /dev/null +++ b/core/src/build/conf/eclipse-code-clean.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/src/main/java/edu/umd/cs/piccolo/PCamera.java b/core/src/main/java/edu/umd/cs/piccolo/PCamera.java index 462f308..8971f3a 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/PCamera.java +++ b/core/src/main/java/edu/umd/cs/piccolo/PCamera.java @@ -100,7 +100,7 @@ private transient PComponent component; private transient List layers; - private PAffineTransform viewTransform; + private final PAffineTransform viewTransform; private int viewConstraint; /** @@ -125,7 +125,7 @@ * Set the canvas associated with this camera. When the camera is repainted * it will request repaints on this canvas. */ - public void setComponent(PComponent aComponent) { + public void setComponent(final PComponent aComponent) { component = aComponent; invalidatePaint(); } @@ -134,7 +134,7 @@ * Repaint this camera, and forward the repaint request to the camera's * canvas if it is not null. */ - public void repaintFrom(PBounds localBounds, PNode descendentOrThis) { + public void repaintFrom(final PBounds localBounds, final PNode descendentOrThis) { if (getParent() != null) { if (descendentOrThis != this) { localToParent(localBounds); @@ -155,12 +155,12 @@ * transformed from view to local in this case. Unlike most repaint methods * in piccolo this one must not modify the viewBounds parameter. */ - public void repaintFromLayer(PBounds viewBounds, PLayer repaintedLayer) { + public void repaintFromLayer(final PBounds viewBounds, final PLayer repaintedLayer) { TEMP_REPAINT_RECT.setRect(viewBounds); viewToLocal(TEMP_REPAINT_RECT); if (getBoundsReference().intersects(TEMP_REPAINT_RECT)) { - PBounds.intersect(TEMP_REPAINT_RECT, getBoundsReference(), TEMP_REPAINT_RECT); + Rectangle2D.intersect(TEMP_REPAINT_RECT, getBoundsReference(), TEMP_REPAINT_RECT); repaintFrom(TEMP_REPAINT_RECT, repaintedLayer); } } @@ -173,7 +173,7 @@ * Unlike most repaint methods in piccolo this one must not * modify the viewBounds parameter. */ - public void repaintFromLayer(PBounds viewBounds, PNode repaintedLayer) { + public void repaintFromLayer(final PBounds viewBounds, final PNode repaintedLayer) { this.repaintFromLayer(viewBounds, (PLayer) repaintedLayer); } @@ -192,11 +192,11 @@ return layers.size(); } - public PLayer getLayer(int index) { + public PLayer getLayer(final int index) { return (PLayer) layers.get(index); } - public int indexOfLayer(PLayer layer) { + public int indexOfLayer(final PLayer layer) { return layers.indexOf(layer); } @@ -204,7 +204,7 @@ * Add the layer to the end of this camera's list of layers. Layers may be * viewed by multiple cameras at once. */ - public void addLayer(PLayer layer) { + public void addLayer(final PLayer layer) { addLayer(layers.size(), layer); } @@ -212,7 +212,7 @@ * Add the layer at the given index in this camera's list of layers. Layers * may be viewed by multiple cameras at once. */ - public void addLayer(int index, PLayer layer) { + public void addLayer(final int index, final PLayer layer) { layers.add(index, layer); layer.addCamera(this); invalidatePaint(); @@ -226,7 +226,7 @@ * * @param layer the layer to be removed */ - public PLayer removeLayer(PLayer layer) { + public PLayer removeLayer(final PLayer layer) { layer.removeCamera(this); if (layers.remove(layer)) { invalidatePaint(); @@ -239,8 +239,8 @@ * Remove the layer at the given index from the list of layers managed by * this camera. */ - public PLayer removeLayer(int index) { - PLayer layer = (PLayer) layers.remove(index); + public PLayer removeLayer(final int index) { + final PLayer layer = (PLayer) layers.remove(index); layer.removeCamera(this); invalidatePaint(); firePropertyChange(PROPERTY_CODE_LAYERS, PROPERTY_LAYERS, null, layers); @@ -251,11 +251,11 @@ * Return the total bounds of all the layers that this camera looks at. */ public PBounds getUnionOfLayerFullBounds() { - PBounds result = new PBounds(); + final PBounds result = new PBounds(); - int count = getLayerCount(); + final int count = getLayerCount(); for (int i = 0; i < count; i++) { - PLayer each = (PLayer) layers.get(i); + final PLayer each = (PLayer) layers.get(i); result.add(each.getFullBoundsReference()); } @@ -270,7 +270,7 @@ * Paint this camera (default background color is white) and then paint the * cameras view through the view transform. */ - protected void paint(PPaintContext paintContext) { + protected void paint(final PPaintContext paintContext) { super.paint(paintContext); paintContext.pushClip(getBoundsReference()); @@ -288,33 +288,33 @@ * after the cameras view transform and clip are applied to the * paintContext. */ - protected void paintCameraView(PPaintContext paintContext) { - int count = getLayerCount(); + protected void paintCameraView(final PPaintContext paintContext) { + final int count = getLayerCount(); for (int i = 0; i < count; i++) { - PLayer each = (PLayer) layers.get(i); + final PLayer each = (PLayer) layers.get(i); each.fullPaint(paintContext); } } - protected void paintDebugInfo(PPaintContext paintContext) { + protected void paintDebugInfo(final PPaintContext paintContext) { if (PDebug.debugBounds || PDebug.debugFullBounds) { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); paintContext.setRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); g2.setStroke(new BasicStroke(0)); - ArrayList nodes = new ArrayList(); - PBounds nodeBounds = new PBounds(); + final ArrayList nodes = new ArrayList(); + final PBounds nodeBounds = new PBounds(); - Color boundsColor = Color.red; - Color fullBoundsColor = new Color(1.0f, 0f, 0f, 0.2f); + final Color boundsColor = Color.red; + final Color fullBoundsColor = new Color(1.0f, 0f, 0f, 0.2f); for (int i = 0; i < getLayerCount(); i++) { getLayer(i).getAllNodes(null, nodes); } - Iterator i = getAllNodes(null, nodes).iterator(); + final Iterator i = getAllNodes(null, nodes).iterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); if (PDebug.debugBounds) { g2.setPaint(boundsColor); @@ -353,7 +353,7 @@ * Override fullPaint to push the camera onto the paintContext so that it * can be later be accessed by PPaintContext.getCamera(); */ - public void fullPaint(PPaintContext paintContext) { + public void fullPaint(final PPaintContext paintContext) { paintContext.pushCamera(this); super.fullPaint(paintContext); paintContext.popCamera(this); @@ -368,9 +368,9 @@ * coord system of this camera. Picking is done with a rectangle, halo * specifies how large that rectangle will be. */ - public PPickPath pick(double x, double y, double halo) { - PBounds b = new PBounds(new Point2D.Double(x, y), -halo, -halo); - PPickPath result = new PPickPath(this, b); + public PPickPath pick(final double x, final double y, final double halo) { + final PBounds b = new PBounds(new Point2D.Double(x, y), -halo, -halo); + final PPickPath result = new PPickPath(this, b); fullPick(result); @@ -387,7 +387,7 @@ * After the direct children of the camera have been given a chance to be * picked objects viewed by the camera are given a chance to be picked. */ - protected boolean pickAfterChildren(PPickPath pickPath) { + protected boolean pickAfterChildren(final PPickPath pickPath) { if (intersects(pickPath.getPickBounds())) { pickPath.pushTransform(viewTransform); @@ -405,10 +405,10 @@ * Pick all the layers that the camera is looking at, this method is called * after the cameras view transform and clip are applied to the pickPath. */ - protected boolean pickCameraView(PPickPath pickPath) { - int count = getLayerCount(); + protected boolean pickCameraView(final PPickPath pickPath) { + final int count = getLayerCount(); for (int i = count - 1; i >= 0; i--) { - PLayer each = (PLayer) layers.get(i); + final PLayer each = (PLayer) layers.get(i); if (each.fullPick(pickPath)) { return true; } @@ -438,7 +438,7 @@ * cameras view bounds. Use this method to point the camera at a given * location. */ - public void setViewBounds(Rectangle2D centerBounds) { + public void setViewBounds(final Rectangle2D centerBounds) { animateViewToCenterBounds(centerBounds, true, 0); } @@ -454,7 +454,7 @@ * Scale the view transform that is applied to the layers viewed by this * camera by the given amount. */ - public void scaleView(double scale) { + public void scaleView(final double scale) { scaleViewAboutPoint(scale, 0, 0); } @@ -462,7 +462,7 @@ * Scale the view transform that is applied to the layers viewed by this * camera by the given amount about the given point. */ - public void scaleViewAboutPoint(double scale, double x, double y) { + public void scaleViewAboutPoint(final double scale, final double x, final double y) { viewTransform.scaleAboutPoint(scale, x, y); applyViewConstraints(); invalidatePaint(); @@ -473,14 +473,14 @@ * Set the scale of the view transform that is applied to the layers viewed * by this camera. */ - public void setViewScale(double scale) { + public void setViewScale(final double scale) { scaleView(scale / getViewScale()); } /** * Translate the view transform that is applied to the camera's layers. */ - public void translateView(double dx, double dy) { + public void translateView(final double dx, final double dy) { viewTransform.translate(dx, dy); applyViewConstraints(); invalidatePaint(); @@ -491,7 +491,7 @@ * Sets the offset of the view transform that is applied to the camera's * layers. */ - public void setViewOffset(double x, double y) { + public void setViewOffset(final double x, final double y) { viewTransform.setOffset(x, y); applyViewConstraints(); invalidatePaint(); @@ -516,7 +516,7 @@ /** * Set the view transform that is applied to the views layers. */ - public void setViewTransform(AffineTransform aTransform) { + public void setViewTransform(final AffineTransform aTransform) { viewTransform.setTransform(aTransform); applyViewConstraints(); invalidatePaint(); @@ -534,15 +534,15 @@ * fit fully within the cameras view bounds, else the camera will maintain * its original scale. */ - public PTransformActivity animateViewToCenterBounds(Rectangle2D centerBounds, boolean shouldScaleToFit, - long duration) { - PBounds viewBounds = getViewBounds(); - PDimension delta = viewBounds.deltaRequiredToCenter(centerBounds); - PAffineTransform newTransform = getViewTransform(); + public PTransformActivity animateViewToCenterBounds(final Rectangle2D centerBounds, final boolean shouldScaleToFit, + final long duration) { + final PBounds viewBounds = getViewBounds(); + final PDimension delta = viewBounds.deltaRequiredToCenter(centerBounds); + final PAffineTransform newTransform = getViewTransform(); newTransform.translate(delta.width, delta.height); if (shouldScaleToFit) { - double s = Math.min(viewBounds.getWidth() / centerBounds.getWidth(), viewBounds.getHeight() + final double s = Math.min(viewBounds.getWidth() / centerBounds.getWidth(), viewBounds.getHeight() / centerBounds.getHeight()); if (s != Double.POSITIVE_INFINITY && s != 0) { newTransform.scaleAboutPoint(s, centerBounds.getCenterX(), centerBounds.getCenterY()); @@ -561,16 +561,16 @@ * will get returned that is set to animate the camera's view transform to * the new bounds. */ - public PTransformActivity animateViewToPanToBounds(Rectangle2D panToBounds, long duration) { - PBounds viewBounds = getViewBounds(); - PDimension delta = viewBounds.deltaRequiredToContain(panToBounds); + public PTransformActivity animateViewToPanToBounds(final Rectangle2D panToBounds, final long duration) { + final PBounds viewBounds = getViewBounds(); + final PDimension delta = viewBounds.deltaRequiredToContain(panToBounds); if (delta.width != 0 || delta.height != 0) { if (duration == 0) { translateView(-delta.width, -delta.height); } else { - AffineTransform at = getViewTransform(); + final AffineTransform at = getViewTransform(); at.translate(-delta.width, -delta.height); return animateViewToTransform(at, duration); } @@ -582,7 +582,7 @@ /** * @deprecated Renamed to animateViewToPanToBounds */ - public PTransformActivity animateViewToIncludeBounds(Rectangle2D includeBounds, long duration) { + public PTransformActivity animateViewToIncludeBounds(final Rectangle2D includeBounds, final long duration) { return animateViewToPanToBounds(includeBounds, duration); } @@ -590,25 +590,25 @@ * Animate the cameras view transform from its current value when the * activity starts to the new destination transform value. */ - public PTransformActivity animateViewToTransform(AffineTransform destination, long duration) { + public PTransformActivity animateViewToTransform(final AffineTransform destination, final long duration) { if (duration == 0) { setViewTransform(destination); return null; } - PTransformActivity.Target t = new PTransformActivity.Target() { - public void setTransform(AffineTransform aTransform) { + final PTransformActivity.Target t = new PTransformActivity.Target() { + public void setTransform(final AffineTransform aTransform) { PCamera.this.setViewTransform(aTransform); } - public void getSourceMatrix(double[] aSource) { - PCamera.this.viewTransform.getMatrix(aSource); + public void getSourceMatrix(final double[] aSource) { + viewTransform.getMatrix(aSource); } }; - PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destination); + final PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destination); - PRoot r = getRoot(); + final PRoot r = getRoot(); if (r != null) { r.getActivityScheduler().addActivity(ta); } @@ -625,17 +625,18 @@ return viewConstraint; } - public void setViewConstraint(int constraint) { + public void setViewConstraint(final int constraint) { viewConstraint = constraint; applyViewConstraints(); } protected void applyViewConstraints() { - if (viewConstraint == VIEW_CONSTRAINT_NONE) + if (viewConstraint == VIEW_CONSTRAINT_NONE) { return; + } - PBounds viewBounds = getViewBounds(); - PBounds layerBounds = (PBounds) globalToLocal(getUnionOfLayerFullBounds()); + final PBounds viewBounds = getViewBounds(); + final PBounds layerBounds = (PBounds) globalToLocal(getUnionOfLayerFullBounds()); PDimension constraintDelta = null; switch (viewConstraint) { @@ -668,7 +669,7 @@ * Convert the point from the camera's view coordinate system to the * camera's local coordinate system. The given point is modified by this. */ - public Point2D viewToLocal(Point2D viewPoint) { + public Point2D viewToLocal(final Point2D viewPoint) { return viewTransform.transform(viewPoint, viewPoint); } @@ -677,7 +678,7 @@ * camera's local coordinate system. The given dimension is modified by * this. */ - public Dimension2D viewToLocal(Dimension2D viewDimension) { + public Dimension2D viewToLocal(final Dimension2D viewDimension) { return viewTransform.transform(viewDimension, viewDimension); } @@ -686,7 +687,7 @@ * camera's local coordinate system. The given rectangle is modified by this * method. */ - public Rectangle2D viewToLocal(Rectangle2D viewRectangle) { + public Rectangle2D viewToLocal(final Rectangle2D viewRectangle) { return viewTransform.transform(viewRectangle, viewRectangle); } @@ -695,7 +696,7 @@ * camera's view coordinate system. The given point is modified by this * method. */ - public Point2D localToView(Point2D localPoint) { + public Point2D localToView(final Point2D localPoint) { return viewTransform.inverseTransform(localPoint, localPoint); } @@ -704,7 +705,7 @@ * camera's view coordinate system. The given dimension is modified by this * method. */ - public Dimension2D localToView(Dimension2D localDimension) { + public Dimension2D localToView(final Dimension2D localDimension) { return viewTransform.inverseTransform(localDimension, localDimension); } @@ -713,7 +714,7 @@ * camera's view coordinate system. The given rectangle is modified by this * method. */ - public Rectangle2D localToView(Rectangle2D localRectangle) { + public Rectangle2D localToView(final Rectangle2D localRectangle) { return viewTransform.inverseTransform(localRectangle, localRectangle); } @@ -729,10 +730,10 @@ * the cameras layers are written conditionally, so they will only get * written out if someone else writes them unconditionally. */ - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); - int count = getLayerCount(); + final int count = getLayerCount(); for (int i = 0; i < count; i++) { ((PObjectOutputStream) out).writeConditionalObject(layers.get(i)); } @@ -741,13 +742,13 @@ ((PObjectOutputStream) out).writeConditionalObject(component); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); layers = new ArrayList(); while (true) { - Object each = in.readObject(); + final Object each = in.readObject(); if (each != null) { if (each.equals(Boolean.FALSE)) { break; diff --git a/core/src/main/java/edu/umd/cs/piccolo/PCanvas.java b/core/src/main/java/edu/umd/cs/piccolo/PCanvas.java index 8a9778e..7617282 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/PCanvas.java +++ b/core/src/main/java/edu/umd/cs/piccolo/PCanvas.java @@ -34,6 +34,7 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.KeyEventPostProcessor; +import java.awt.KeyboardFocusManager; import java.awt.event.ActionListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; @@ -75,7 +76,7 @@ * formats. */ private static final long serialVersionUID = 1L; - + /** * @deprecated this is a typo and clients should change their code to * reflect the correct spelling @@ -86,7 +87,7 @@ public static PCanvas CURRENT_ZCANVAS = null; private PCamera camera; - private PStack cursorStack; + private final PStack cursorStack; private int interacting; private int defaultRenderQuality; private int animatingRenderQuality; @@ -117,7 +118,7 @@ setOpaque(true); addHierarchyListener(new HierarchyListener() { - public void hierarchyChanged(HierarchyEvent e) { + public void hierarchyChanged(final HierarchyEvent e) { if (e.getComponent() == PCanvas.this) { if (getParent() == null) { removeInputSources(); @@ -152,7 +153,7 @@ * * @param handler the new zoom event handler */ - public void setPanEventHandler(PPanEventHandler handler) { + public void setPanEventHandler(final PPanEventHandler handler) { if (panEventHandler != null) { removeInputEventListener(panEventHandler); } @@ -178,7 +179,7 @@ * * @param handler the new zoom event handler */ - public void setZoomEventHandler(PZoomEventHandler handler) { + public void setZoomEventHandler(final PZoomEventHandler handler) { if (zoomEventHandler != null) { removeInputEventListener(zoomEventHandler); } @@ -204,7 +205,7 @@ * canvas go through this camera. And this is the camera that paints this * canvas. */ - public void setCamera(PCamera newCamera) { + public void setCamera(final PCamera newCamera) { if (camera != null) { camera.setComponent(null); } @@ -234,14 +235,14 @@ /** * Add an input listener to the camera associated with this canvas. */ - public void addInputEventListener(PInputEventListener listener) { + public void addInputEventListener(final PInputEventListener listener) { getCamera().addInputEventListener(listener); } /** * Remove an input listener to the camera associated with this canvas. */ - public void removeInputEventListener(PInputEventListener listener) { + public void removeInputEventListener(final PInputEventListener listener) { getCamera().removeInputEventListener(listener); } @@ -273,7 +274,7 @@ * quality should change. */ public void setInteracting(boolean isInteracting) { - boolean wasInteracting = getInteracting(); + final boolean wasInteracting = getInteracting(); if (isInteracting) { interacting++; @@ -286,8 +287,9 @@ // it's greater then the old // interacting render quality. int nextRenderQuality = defaultRenderQuality; - if (getAnimating()) + if (getAnimating()) { nextRenderQuality = animatingRenderQuality; + } if (nextRenderQuality > interactingRenderQuality) { repaint(); } @@ -308,7 +310,7 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setDefaultRenderQuality(int requestedQuality) { + public void setDefaultRenderQuality(final int requestedQuality) { defaultRenderQuality = requestedQuality; repaint(); } @@ -321,10 +323,11 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setAnimatingRenderQuality(int requestedQuality) { + public void setAnimatingRenderQuality(final int requestedQuality) { animatingRenderQuality = requestedQuality; - if (getAnimating()) + if (getAnimating()) { repaint(); + } } /** @@ -335,17 +338,18 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setInteractingRenderQuality(int requestedQuality) { + public void setInteractingRenderQuality(final int requestedQuality) { interactingRenderQuality = requestedQuality; - if (getInteracting()) + if (getInteracting()) { repaint(); + } } /** * Set the canvas cursor, and remember the previous cursor on the cursor * stack. */ - public void pushCursor(Cursor cursor) { + public void pushCursor(final Cursor cursor) { cursorStack.push(getCursor()); setCursor(cursor); } @@ -373,7 +377,7 @@ /** * Override setEnabled to install/remove canvas input sources as needed. */ - public void setEnabled(boolean enabled) { + public void setEnabled(final boolean enabled) { super.setEnabled(enabled); if (isEnabled() && getParent() != null) { @@ -392,12 +396,12 @@ if (mouseListener == null) { mouseListener = new MouseListener() { /** {@inheritDoc} */ - public void mouseClicked(MouseEvent e) { + public void mouseClicked(final MouseEvent e) { sendInputEventToInputManager(e, MouseEvent.MOUSE_CLICKED); } /** {@inheritDoc} */ - public void mouseEntered(MouseEvent e) { + public void mouseEntered(final MouseEvent e) { MouseEvent simulated = null; if (isAnyButtonDown(e)) { @@ -412,7 +416,7 @@ } /** {@inheritDoc} */ - public void mouseExited(MouseEvent e) { + public void mouseExited(final MouseEvent e) { MouseEvent simulated = null; if (isAnyButtonDown(e)) { @@ -462,7 +466,7 @@ } sendInputEventToInputManager(e, MouseEvent.MOUSE_PRESSED); - } + } /** {@inheritDoc} */ public void mouseReleased(MouseEvent e) { @@ -500,45 +504,45 @@ sendInputEventToInputManager(e, MouseEvent.MOUSE_RELEASED); } - private boolean isAnyButtonDown(MouseEvent e) { + private boolean isAnyButtonDown(final MouseEvent e) { return (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK)) != 0; } - private MouseEvent copyButtonsFromModifiers(final MouseEvent rawEvent, int eventType) { + private MouseEvent copyButtonsFromModifiers(final MouseEvent rawEvent, final int eventType) { if (rawEvent.getButton() != MouseEvent.NOBUTTON) { return rawEvent; } int newButton = 0; - if (hasButtonModifier(rawEvent, MouseEvent.BUTTON1_MASK)) { + if (hasButtonModifier(rawEvent, InputEvent.BUTTON1_MASK)) { newButton = MouseEvent.BUTTON1; } - else if (hasButtonModifier(rawEvent, MouseEvent.BUTTON2_MASK)) { + else if (hasButtonModifier(rawEvent, InputEvent.BUTTON2_MASK)) { newButton = MouseEvent.BUTTON2; } - else if (hasButtonModifier(rawEvent, MouseEvent.BUTTON3_MASK)) { + else if (hasButtonModifier(rawEvent, InputEvent.BUTTON3_MASK)) { newButton = MouseEvent.BUTTON3; } - return buildModifiedMouseEvent(rawEvent, eventType, newButton); + return buildModifiedMouseEvent(rawEvent, eventType, newButton); } - private boolean hasButtonModifier(final MouseEvent event, int buttonMask) { + private boolean hasButtonModifier(final MouseEvent event, final int buttonMask) { return (event.getModifiers() & buttonMask) == buttonMask; } - public MouseEvent buildRetypedMouseEvent(MouseEvent e, int newType) { + public MouseEvent buildRetypedMouseEvent(final MouseEvent e, final int newType) { return buildModifiedMouseEvent(e, newType, e.getButton()); } - public MouseEvent buildModifiedMouseEvent(MouseEvent e, int newType, int newButton) { + public MouseEvent buildModifiedMouseEvent(final MouseEvent e, final int newType, final int newButton) { return new MouseEvent((Component) e.getSource(), newType, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), e.getClickCount(), e.isPopupTrigger(), newButton); } - - private void sendRetypedMouseEventToInputManager(MouseEvent e, int newType) { - MouseEvent retypedEvent = buildRetypedMouseEvent(e, newType); + + private void sendRetypedMouseEventToInputManager(final MouseEvent e, final int newType) { + final MouseEvent retypedEvent = buildRetypedMouseEvent(e, newType); sendInputEventToInputManager(retypedEvent, newType); } }; @@ -548,12 +552,12 @@ if (mouseMotionListener == null) { mouseMotionListener = new MouseMotionListener() { /** {@inheritDoc} */ - public void mouseDragged(MouseEvent e) { + public void mouseDragged(final MouseEvent e) { sendInputEventToInputManager(e, MouseEvent.MOUSE_DRAGGED); } /** {@inheritDoc} */ - public void mouseMoved(MouseEvent e) { + public void mouseMoved(final MouseEvent e) { sendInputEventToInputManager(e, MouseEvent.MOUSE_MOVED); } }; @@ -563,7 +567,7 @@ if (mouseWheelListener == null) { mouseWheelListener = new MouseWheelListener() { /** {@inheritDoc} */ - public void mouseWheelMoved(MouseWheelEvent e) { + public void mouseWheelMoved(final MouseWheelEvent e) { sendInputEventToInputManager(e, e.getScrollType()); if (!e.isConsumed() && getParent() != null) { getParent().dispatchEvent(e); @@ -588,7 +592,7 @@ return false; } }; - FocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(keyEventPostProcessor); + KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(keyEventPostProcessor); } } @@ -600,24 +604,24 @@ removeMouseListener(mouseListener); removeMouseMotionListener(mouseMotionListener); removeMouseWheelListener(mouseWheelListener); - FocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(keyEventPostProcessor); - + KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(keyEventPostProcessor); + mouseListener = null; mouseMotionListener = null; mouseWheelListener = null; keyEventPostProcessor = null; } - protected void sendInputEventToInputManager(InputEvent e, int type) { + protected void sendInputEventToInputManager(final InputEvent e, final int type) { getRoot().getDefaultInputManager().processEventFromCamera(e, type, getCamera()); } - public void setBounds(int x, int y, final int w, final int h) { + public void setBounds(final int x, final int y, final int w, final int h) { camera.setBounds(camera.getX(), camera.getY(), w, h); super.setBounds(x, y, w, h); } - public void repaint(PBounds bounds) { + public void repaint(final PBounds bounds) { PDebug.processRepaint(); bounds.expandNearestIntegerDimensions(); @@ -626,10 +630,10 @@ repaint((int) bounds.x, (int) bounds.y, (int) bounds.width, (int) bounds.height); } - public void paintComponent(Graphics g) { + public void paintComponent(final Graphics g) { PDebug.startProcessingOutput(); - Graphics2D g2 = (Graphics2D) g.create(); + final Graphics2D g2 = (Graphics2D) g.create(); // support for non-opaque canvases // see @@ -641,7 +645,7 @@ // create new paint context and set render quality to lowest common // denominator render quality. - PPaintContext paintContext = new PPaintContext(g2); + final PPaintContext paintContext = new PPaintContext(g2); if (getInteracting() || getAnimating()) { if (interactingRenderQuality < animatingRenderQuality) { paintContext.setRenderQuality(interactingRenderQuality); @@ -679,7 +683,7 @@ paintingImmediately = false; } - public Timer createTimer(int delay, ActionListener listener) { + public Timer createTimer(final int delay, final ActionListener listener) { return new Timer(delay, listener); } diff --git a/core/src/main/java/edu/umd/cs/piccolo/PInputManager.java b/core/src/main/java/edu/umd/cs/piccolo/PInputManager.java index 5f3f345..896f701 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/PInputManager.java +++ b/core/src/main/java/edu/umd/cs/piccolo/PInputManager.java @@ -52,8 +52,8 @@ */ public class PInputManager extends PBasicInputEventHandler implements PRoot.InputSource { - private Point2D lastCanvasPosition; - private Point2D currentCanvasPosition; + private final Point2D lastCanvasPosition; + private final Point2D currentCanvasPosition; private InputEvent nextInput; private int nextType; @@ -88,8 +88,8 @@ /** * Set the node that should receive key events. */ - public void setKeyboardFocus(PInputEventListener eventHandler) { - PInputEvent focusEvent = new PInputEvent(this, null); + public void setKeyboardFocus(final PInputEventListener eventHandler) { + final PInputEvent focusEvent = new PInputEvent(this, null); if (keyboardFocus != null) { dispatchEventToListener(focusEvent, FocusEvent.FOCUS_LOST, keyboardFocus); @@ -112,7 +112,7 @@ return mouseFocus; } - public void setMouseFocus(PPickPath path) { + public void setMouseFocus(final PPickPath path) { previousMouseFocus = mouseFocus; mouseFocus = path; } @@ -124,7 +124,7 @@ return mouseOver; } - public void setMouseOver(PPickPath path) { + public void setMouseOver(final PPickPath path) { mouseOver = path; } @@ -144,74 +144,76 @@ // focus nodes. // **************************************************************** - public void keyPressed(PInputEvent event) { + public void keyPressed(final PInputEvent event) { dispatchEventToListener(event, KeyEvent.KEY_PRESSED, keyboardFocus); } - public void keyReleased(PInputEvent event) { + public void keyReleased(final PInputEvent event) { dispatchEventToListener(event, KeyEvent.KEY_RELEASED, keyboardFocus); } - public void keyTyped(PInputEvent event) { + public void keyTyped(final PInputEvent event) { dispatchEventToListener(event, KeyEvent.KEY_TYPED, keyboardFocus); } - public void mouseClicked(PInputEvent event) { + public void mouseClicked(final PInputEvent event) { dispatchEventToListener(event, MouseEvent.MOUSE_CLICKED, previousMouseFocus); } - public void mouseWheelRotated(PInputEvent event) { + public void mouseWheelRotated(final PInputEvent event) { setMouseFocus(getMouseOver()); dispatchEventToListener(event, MouseWheelEvent.WHEEL_UNIT_SCROLL, mouseOver); } - public void mouseWheelRotatedByBlock(PInputEvent event) { + public void mouseWheelRotatedByBlock(final PInputEvent event) { setMouseFocus(getMouseOver()); dispatchEventToListener(event, MouseWheelEvent.WHEEL_BLOCK_SCROLL, mouseOver); } - public void mouseDragged(PInputEvent event) { + public void mouseDragged(final PInputEvent event) { checkForMouseEnteredAndExited(event); dispatchEventToListener(event, MouseEvent.MOUSE_DRAGGED, mouseFocus); } - public void mouseEntered(PInputEvent event) { + public void mouseEntered(final PInputEvent event) { dispatchEventToListener(event, MouseEvent.MOUSE_ENTERED, mouseOver); } - public void mouseExited(PInputEvent event) { + public void mouseExited(final PInputEvent event) { dispatchEventToListener(event, MouseEvent.MOUSE_EXITED, previousMouseOver); } - public void mouseMoved(PInputEvent event) { + public void mouseMoved(final PInputEvent event) { checkForMouseEnteredAndExited(event); dispatchEventToListener(event, MouseEvent.MOUSE_MOVED, mouseOver); } - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { if (pressedCount == 0) { setMouseFocus(getMouseOver()); } pressedCount++; dispatchEventToListener(event, MouseEvent.MOUSE_PRESSED, mouseFocus); - if (pressedCount < 1 || pressedCount > 3) + if (pressedCount < 1 || pressedCount > 3) { System.err.println("invalid pressedCount on mouse pressed: " + pressedCount); + } } - public void mouseReleased(PInputEvent event) { + public void mouseReleased(final PInputEvent event) { pressedCount--; checkForMouseEnteredAndExited(event); dispatchEventToListener(event, MouseEvent.MOUSE_RELEASED, mouseFocus); if (pressedCount == 0) { setMouseFocus(null); } - if (pressedCount < 0 || pressedCount > 2) + if (pressedCount < 0 || pressedCount > 2) { System.err.println("invalid pressedCount on mouse released: " + pressedCount); + } } - protected void checkForMouseEnteredAndExited(PInputEvent event) { - PNode c = (mouseOver != null) ? mouseOver.getPickedNode() : null; - PNode p = (previousMouseOver != null) ? previousMouseOver.getPickedNode() : null; + protected void checkForMouseEnteredAndExited(final PInputEvent event) { + final PNode c = mouseOver != null ? mouseOver.getPickedNode() : null; + final PNode p = previousMouseOver != null ? previousMouseOver.getPickedNode() : null; if (c != p) { dispatchEventToListener(event, MouseEvent.MOUSE_EXITED, previousMouseOver); @@ -225,18 +227,19 @@ // **************************************************************** public void processInput() { - if (nextInput == null) + if (nextInput == null) { return; + } - PInputEvent e = new PInputEvent(this, nextInput); + final PInputEvent e = new PInputEvent(this, nextInput); Point2D newCurrentCanvasPosition = null; Point2D newLastCanvasPosition = null; if (e.isMouseEvent()) { if (e.isMouseEnteredOrMouseExited()) { - PPickPath aPickPath = nextInputSource.pick(((MouseEvent) nextInput).getX(), ((MouseEvent) nextInput) - .getY(), 1); + final PPickPath aPickPath = nextInputSource.pick(((MouseEvent) nextInput).getX(), + ((MouseEvent) nextInput).getY(), 1); setMouseOver(aPickPath); previousMouseOver = aPickPath; newCurrentCanvasPosition = (Point2D) currentCanvasPosition.clone(); @@ -245,8 +248,8 @@ else { lastCanvasPosition.setLocation(currentCanvasPosition); currentCanvasPosition.setLocation(((MouseEvent) nextInput).getX(), ((MouseEvent) nextInput).getY()); - PPickPath aPickPath = nextInputSource.pick(currentCanvasPosition.getX(), currentCanvasPosition.getY(), - 1); + final PPickPath aPickPath = nextInputSource.pick(currentCanvasPosition.getX(), currentCanvasPosition + .getY(), 1); setMouseOver(aPickPath); } } @@ -254,7 +257,7 @@ nextInput = null; nextInputSource = null; - this.processEvent(e, nextType); + processEvent(e, nextType); if (newCurrentCanvasPosition != null && newLastCanvasPosition != null) { currentCanvasPosition.setLocation(newCurrentCanvasPosition); @@ -262,7 +265,7 @@ } } - public void processEventFromCamera(InputEvent event, int type, PCamera camera) { + public void processEventFromCamera(final InputEvent event, final int type, final PCamera camera) { // queue input nextInput = event; nextType = type; @@ -272,7 +275,7 @@ camera.getRoot().processInputs(); } - private void dispatchEventToListener(PInputEvent event, int type, PInputEventListener listener) { + private void dispatchEventToListener(final PInputEvent event, final int type, final PInputEventListener listener) { if (listener != null) { // clear the handled bit since the same event object is used to send // multiple events such as mouseEntered/mouseExited and mouseMove. diff --git a/core/src/main/java/edu/umd/cs/piccolo/PLayer.java b/core/src/main/java/edu/umd/cs/piccolo/PLayer.java index 42ab7b0..845346a 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/PLayer.java +++ b/core/src/main/java/edu/umd/cs/piccolo/PLayer.java @@ -59,7 +59,7 @@ * formats. */ private static final long serialVersionUID = 1L; - + /** * The property name that identifies a change in the set of this layer's * cameras (see {@link #getCamera getCamera}, {@link #getCameraCount @@ -102,7 +102,7 @@ /** * Get the camera in this layer's camera list at the specified index. */ - public PCamera getCamera(int index) { + public PCamera getCamera(final int index) { return (PCamera) cameras.get(index); } @@ -110,7 +110,7 @@ * Add a camera to this layer's camera list. This method it called * automatically when a layer is added to a camera. */ - public void addCamera(PCamera camera) { + public void addCamera(final PCamera camera) { addCamera(cameras.size(), camera); } @@ -118,7 +118,7 @@ * Add a camera to this layer's camera list at the specified index. This * method it called automatically when a layer is added to a camera. */ - public void addCamera(int index, PCamera camera) { + public void addCamera(final int index, final PCamera camera) { cameras.add(index, camera); invalidatePaint(); firePropertyChange(PROPERTY_CODE_CAMERAS, PROPERTY_CAMERAS, null, cameras); @@ -126,20 +126,20 @@ /** * Remove the camera from this layer's camera list. - */ - public PCamera removeCamera(PCamera camera) { + */ + public PCamera removeCamera(final PCamera camera) { if (cameras.remove(camera)) { invalidatePaint(); firePropertyChange(PROPERTY_CODE_CAMERAS, PROPERTY_CAMERAS, null, cameras); } - return camera; + return camera; } /** * Remove the camera at the given index from this layer's camera list. */ - public PCamera removeCamera(int index) { - PCamera result = (PCamera) cameras.remove(index); + public PCamera removeCamera(final int index) { + final PCamera result = (PCamera) cameras.remove(index); invalidatePaint(); firePropertyChange(PROPERTY_CODE_CAMERAS, PROPERTY_CAMERAS, null, cameras); return result; @@ -155,7 +155,7 @@ * Override repaints and forward them to the cameras that are viewing this * layer. */ - public void repaintFrom(PBounds localBounds, PNode childOrThis) { + public void repaintFrom(final PBounds localBounds, final PNode childOrThis) { if (childOrThis != this) { localToParent(localBounds); } @@ -167,10 +167,10 @@ } } - protected void notifyCameras(PBounds parentBounds) { - int count = getCameraCount(); + protected void notifyCameras(final PBounds parentBounds) { + final int count = getCameraCount(); for (int i = 0; i < count; i++) { - PCamera each = (PCamera) cameras.get(i); + final PCamera each = (PCamera) cameras.get(i); each.repaintFromLayer(parentBounds, this); } } @@ -188,10 +188,10 @@ * they will only get written out if someone else writes them * unconditionally. */ - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); - int count = getCameraCount(); + final int count = getCameraCount(); for (int i = 0; i < count; i++) { ((PObjectOutputStream) out).writeConditionalObject(cameras.get(i)); } @@ -199,13 +199,13 @@ out.writeObject(Boolean.FALSE); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); cameras = new ArrayList(); while (true) { - Object each = in.readObject(); + final Object each = in.readObject(); if (each != null) { if (each.equals(Boolean.FALSE)) { break; diff --git a/core/src/main/java/edu/umd/cs/piccolo/PNode.java b/core/src/main/java/edu/umd/cs/piccolo/PNode.java index 67ab489..ecba108 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/PNode.java +++ b/core/src/main/java/edu/umd/cs/piccolo/PNode.java @@ -219,7 +219,7 @@ private transient PNode parent; private List children; - private PBounds bounds; + private final PBounds bounds; private PAffineTransform transform; private Paint paint; private float transparency; @@ -285,7 +285,8 @@ * @param duration amount of time that the animation should take * @return the newly scheduled activity */ - public PInterpolatingActivity animateToBounds(double x, double y, double width, double height, long duration) { + public PInterpolatingActivity animateToBounds(final double x, final double y, final double width, + final double height, final long duration) { if (duration == 0) { setBounds(x, y, width, height); return null; @@ -293,7 +294,7 @@ else { final PBounds dst = new PBounds(x, y, width, height); - PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) { + final PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) { private PBounds src; protected void activityStarted() { @@ -302,10 +303,10 @@ super.activityStarted(); } - public void setRelativeTargetValue(float zeroToOne) { - PNode.this.setBounds(src.x + (zeroToOne * (dst.x - src.x)), src.y + (zeroToOne * (dst.y - src.y)), - src.width + (zeroToOne * (dst.width - src.width)), src.height - + (zeroToOne * (dst.height - src.height))); + public void setRelativeTargetValue(final float zeroToOne) { + PNode.this.setBounds(src.x + zeroToOne * (dst.x - src.x), src.y + zeroToOne * (dst.y - src.y), + src.width + zeroToOne * (dst.width - src.width), src.height + zeroToOne + * (dst.height - src.height)); } protected void activityFinished() { @@ -335,11 +336,12 @@ * @param duration amount of time that the animation should take * @return the newly scheduled activity */ - public PTransformActivity animateTransformToBounds(double x, double y, double width, double height, long duration) { - PAffineTransform t = new PAffineTransform(); + public PTransformActivity animateTransformToBounds(final double x, final double y, final double width, + final double height, final long duration) { + final PAffineTransform t = new PAffineTransform(); t.setToScale(width / getWidth(), height / getHeight()); - double scale = t.getScale(); - t.setOffset(x - (getX() * scale), y - (getY() * scale)); + final double scale = t.getScale(); + t.setOffset(x - getX() * scale, y - getY() * scale); return animateToTransform(t, duration); } @@ -357,9 +359,9 @@ * @param theta final theta value (in radians) for the animation * @return the newly scheduled activity */ - public PTransformActivity animateToPositionScaleRotation(double x, double y, double scale, double theta, - long duration) { - PAffineTransform t = getTransform(); + public PTransformActivity animateToPositionScaleRotation(final double x, final double y, final double scale, + final double theta, final long duration) { + final PAffineTransform t = getTransform(); t.setOffset(x, y); t.setScale(scale); t.setRotation(theta); @@ -380,23 +382,24 @@ * @param duration amount of time that the animation should take * @return the newly scheduled activity */ - public PTransformActivity animateToTransform(AffineTransform destTransform, long duration) { + public PTransformActivity animateToTransform(final AffineTransform destTransform, final long duration) { if (duration == 0) { setTransform(destTransform); return null; } else { - PTransformActivity.Target t = new PTransformActivity.Target() { - public void setTransform(AffineTransform aTransform) { + final PTransformActivity.Target t = new PTransformActivity.Target() { + public void setTransform(final AffineTransform aTransform) { PNode.this.setTransform(aTransform); } - public void getSourceMatrix(double[] aSource) { + public void getSourceMatrix(final double[] aSource) { PNode.this.getTransformReference(true).getMatrix(aSource); } }; - PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destTransform); + final PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, + destTransform); addActivity(ta); return ta; } @@ -416,23 +419,23 @@ * @param duration amount of time that the animation should take * @return the newly scheduled activity */ - public PInterpolatingActivity animateToColor(Color destColor, long duration) { + public PInterpolatingActivity animateToColor(final Color destColor, final long duration) { if (duration == 0) { setPaint(destColor); return null; } else { - PColorActivity.Target t = new PColorActivity.Target() { + final PColorActivity.Target t = new PColorActivity.Target() { public Color getColor() { return (Color) getPaint(); } - public void setColor(Color color) { + public void setColor(final Color color) { setPaint(color); } }; - PColorActivity ca = new PColorActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destColor); + final PColorActivity ca = new PColorActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destColor); addActivity(ca); return ca; } @@ -452,7 +455,7 @@ * @param duration amount of time that the animation should take * @return the newly scheduled activity */ - public PInterpolatingActivity animateToTransparency(float zeroToOne, long duration) { + public PInterpolatingActivity animateToTransparency(final float zeroToOne, final long duration) { if (duration == 0) { setTransparency(zeroToOne); return null; @@ -460,7 +463,7 @@ else { final float dest = zeroToOne; - PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) { + final PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) { private float source; protected void activityStarted() { @@ -468,8 +471,8 @@ super.activityStarted(); } - public void setRelativeTargetValue(float zeroToOne) { - PNode.this.setTransparency(source + (zeroToOne * (dest - source))); + public void setRelativeTargetValue(final float zeroToOne) { + PNode.this.setTransparency(source + zeroToOne * (dest - source)); } }; @@ -486,8 +489,8 @@ * @param activity new activity to schedule * @return true if the activity is successfully scheduled. */ - public boolean addActivity(PActivity activity) { - PRoot r = getRoot(); + public boolean addActivity(final PActivity activity) { + final PRoot r = getRoot(); if (r != null) { return r.addActivity(activity); } @@ -521,7 +524,7 @@ * * @return the value of this attribute or null */ - public Object getAttribute(Object key) { + public Object getAttribute(final Object key) { if (clientProperties == null || key == null) { return null; } @@ -539,11 +542,12 @@ *

* If value is null this method will remove the attribute. */ - public void addAttribute(Object key, Object value) { - if (value == null && clientProperties == null) + public void addAttribute(final Object key, final Object value) { + if (value == null && clientProperties == null) { return; + } - Object oldValue = getAttribute(key); + final Object oldValue = getAttribute(key); if (value != oldValue) { if (clientProperties == null) { @@ -582,37 +586,37 @@ // convenience methods for attributes - public Object getAttribute(Object key, Object def) { - Object o = getAttribute(key); - return (o == null ? def : o); + public Object getAttribute(final Object key, final Object def) { + final Object o = getAttribute(key); + return o == null ? def : o; } - public boolean getBooleanAttribute(Object key, boolean def) { - Boolean b = (Boolean) getAttribute(key); - return (b == null ? def : b.booleanValue()); + public boolean getBooleanAttribute(final Object key, final boolean def) { + final Boolean b = (Boolean) getAttribute(key); + return b == null ? def : b.booleanValue(); } - public int getIntegerAttribute(Object key, int def) { - Number n = (Number) getAttribute(key); - return (n == null ? def : n.intValue()); + public int getIntegerAttribute(final Object key, final int def) { + final Number n = (Number) getAttribute(key); + return n == null ? def : n.intValue(); } - public double getDoubleAttribute(Object key, double def) { - Number n = (Number) getAttribute(key); - return (n == null ? def : n.doubleValue()); + public double getDoubleAttribute(final Object key, final double def) { + final Number n = (Number) getAttribute(key); + return n == null ? def : n.doubleValue(); } /** * @deprecated use getAttribute(Object key)instead. */ - public Object getClientProperty(Object key) { + public Object getClientProperty(final Object key) { return getAttribute(key); } /** * @deprecated use addAttribute(Object key, Object value)instead. */ - public void addClientProperty(Object key, Object value) { + public void addClientProperty(final Object key, final Object value) { addAttribute(key, value); } @@ -650,13 +654,13 @@ */ public Object clone() { try { - byte[] ser = PObjectOutputStream.toByteArray(this); - return (PNode) new ObjectInputStream(new ByteArrayInputStream(ser)).readObject(); + final byte[] ser = PObjectOutputStream.toByteArray(this); + return new ObjectInputStream(new ByteArrayInputStream(ser)).readObject(); } - catch (IOException e) { + catch (final IOException e) { return null; } - catch (ClassNotFoundException e) { + catch (final ClassNotFoundException e) { return null; } } @@ -706,9 +710,10 @@ * @param localPoint point in local coordinate system to be transformed. * @return point in parent's local coordinate system */ - public Point2D localToParent(Point2D localPoint) { - if (transform == null) + public Point2D localToParent(final Point2D localPoint) { + if (transform == null) { return localPoint; + } return transform.transform(localPoint, localPoint); } @@ -721,9 +726,10 @@ * transformed. * @return dimension in parent's local coordinate system */ - public Dimension2D localToParent(Dimension2D localDimension) { - if (transform == null) + public Dimension2D localToParent(final Dimension2D localDimension) { + if (transform == null) { return localDimension; + } return transform.transform(localDimension, localDimension); } @@ -736,9 +742,10 @@ * transformed. * @return rectangle in parent's local coordinate system */ - public Rectangle2D localToParent(Rectangle2D localRectangle) { - if (transform == null) + public Rectangle2D localToParent(final Rectangle2D localRectangle) { + if (transform == null) { return localRectangle; + } return transform.transform(localRectangle, localRectangle); } @@ -750,9 +757,10 @@ * @param parentPoint point in parent's coordinate system to be transformed. * @return point in this node's local coordinate system */ - public Point2D parentToLocal(Point2D parentPoint) { - if (transform == null) + public Point2D parentToLocal(final Point2D parentPoint) { + if (transform == null) { return parentPoint; + } return transform.inverseTransform(parentPoint, parentPoint); } @@ -766,9 +774,10 @@ * transformed. * @return dimension in this node's local coordinate system */ - public Dimension2D parentToLocal(Dimension2D parentDimension) { - if (transform == null) + public Dimension2D parentToLocal(final Dimension2D parentDimension) { + if (transform == null) { return parentDimension; + } return transform.inverseTransform(parentDimension, parentDimension); } @@ -781,9 +790,10 @@ * transformed. * @return rectangle in this node's local coordinate system */ - public Rectangle2D parentToLocal(Rectangle2D parentRectangle) { - if (transform == null) + public Rectangle2D parentToLocal(final Rectangle2D parentRectangle) { + if (transform == null) { return parentRectangle; + } return transform.inverseTransform(parentRectangle, parentRectangle); } @@ -893,8 +903,9 @@ public PAffineTransform getLocalToGlobalTransform(PAffineTransform dest) { if (parent != null) { dest = parent.getLocalToGlobalTransform(dest); - if (transform != null) + if (transform != null) { dest.concatenate(transform); + } } else { if (dest == null) { @@ -924,7 +935,7 @@ try { dest.setTransform(dest.createInverse()); } - catch (NoninvertibleTransformException e) { + catch (final NoninvertibleTransformException e) { throw new PAffineTransformException(e, dest); } return dest; @@ -956,9 +967,10 @@ * * @param listener the new input listener */ - public void addInputEventListener(PInputEventListener listener) { - if (listenerList == null) + public void addInputEventListener(final PInputEventListener listener) { + if (listenerList == null) { listenerList = new EventListenerList(); + } getListenerList().add(PInputEventListener.class, listener); } @@ -968,9 +980,10 @@ * * @param listener the input listener to remove */ - public void removeInputEventListener(PInputEventListener listener) { - if (listenerList == null) + public void removeInputEventListener(final PInputEventListener listener) { + if (listenerList == null) { return; + } getListenerList().remove(PInputEventListener.class, listener); if (listenerList.getListenerCount() == 0) { listenerList = null; @@ -984,7 +997,7 @@ * * @param listener The PropertyChangeListener to be added */ - public void addPropertyChangeListener(PropertyChangeListener listener) { + public void addPropertyChangeListener(final PropertyChangeListener listener) { if (changeSupport == null) { changeSupport = new SwingPropertyChangeSupport(this); } @@ -1000,7 +1013,7 @@ * @param propertyName The name of the property to listen on. * @param listener The PropertyChangeListener to be added */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { if (listener == null) { return; } @@ -1016,7 +1029,7 @@ * * @param listener The PropertyChangeListener to be removed */ - public void removePropertyChangeListener(PropertyChangeListener listener) { + public void removePropertyChangeListener(final PropertyChangeListener listener) { if (changeSupport != null) { changeSupport.removePropertyChangeListener(listener); } @@ -1028,7 +1041,7 @@ * @param propertyName The name of the property that was listened on. * @param listener The PropertyChangeListener to be removed */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { + public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { if (listener == null) { return; } @@ -1052,7 +1065,7 @@ * events are forwared to this nodes parent so that its property change * listeners will also be notified. */ - public void setPropertyChangeParentMask(int propertyChangeParentMask) { + public void setPropertyChangeParentMask(final int propertyChangeParentMask) { this.propertyChangeParentMask = propertyChangeParentMask; } @@ -1068,7 +1081,8 @@ * @param oldValue The old value of the property. * @param newValue The new value of the property. */ - protected void firePropertyChange(int propertyCode, String propertyName, Object oldValue, Object newValue) { + protected void firePropertyChange(final int propertyCode, final String propertyName, final Object oldValue, + final Object newValue) { PropertyChangeEvent event = null; if (changeSupport != null) { @@ -1076,8 +1090,9 @@ changeSupport.firePropertyChange(event); } if (parent != null && (propertyCode & propertyChangeParentMask) != 0) { - if (event == null) + if (event == null) { event = new PropertyChangeEvent(this, propertyName, oldValue, newValue); + } parent.fireChildPropertyChange(event, propertyCode); } } @@ -1093,7 +1108,7 @@ * values. * @param propertyCode The code of the property changed. */ - protected void fireChildPropertyChange(PropertyChangeEvent event, int propertyCode) { + protected void fireChildPropertyChange(final PropertyChangeEvent event, final int propertyCode) { if (changeSupport != null) { changeSupport.firePropertyChange(event); } @@ -1156,19 +1171,19 @@ public void endResizeBounds() { } - public boolean setX(double x) { + public boolean setX(final double x) { return setBounds(x, getY(), getWidth(), getHeight()); } - public boolean setY(double y) { + public boolean setY(final double y) { return setBounds(getX(), y, getWidth(), getHeight()); } - public boolean setWidth(double width) { + public boolean setWidth(final double width) { return setBounds(getX(), getY(), width, getHeight()); } - public boolean setHeight(double height) { + public boolean setHeight(final double height) { return setBounds(getX(), getY(), getWidth(), height); } @@ -1178,7 +1193,7 @@ * * @return true if the bounds changed. */ - public boolean setBounds(Rectangle2D newBounds) { + public boolean setBounds(final Rectangle2D newBounds) { return setBounds(newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight()); } @@ -1193,7 +1208,7 @@ * * @return true if the bounds changed. */ - public boolean setBounds(double x, double y, double width, double height) { + public boolean setBounds(final double x, final double y, final double width, final double height) { if (bounds.x != x || bounds.y != y || bounds.width != width || bounds.height != height) { bounds.setRect(x, y, width, height); @@ -1221,7 +1236,7 @@ * * See PPath for an example that uses this method. */ - protected void internalUpdateBounds(double x, double y, double width, double height) { + protected void internalUpdateBounds(final double x, final double y, final double width, final double height) { } /** @@ -1276,9 +1291,9 @@ * * @return true if the bounds changed. */ - public boolean centerBoundsOnPoint(double localX, double localY) { - double dx = localX - bounds.getCenterX(); - double dy = localY - bounds.getCenterY(); + public boolean centerBoundsOnPoint(final double localX, final double localY) { + final double dx = localX - bounds.getCenterX(); + final double dy = localY - bounds.getCenterY(); return setBounds(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height); } @@ -1288,9 +1303,9 @@ * this meathod will modify the nodes transform, while centerBoundsOnPoint * will modify the nodes bounds. */ - public void centerFullBoundsOnPoint(double parentX, double parentY) { - double dx = parentX - getFullBoundsReference().getCenterX(); - double dy = parentY - getFullBoundsReference().getCenterY(); + public void centerFullBoundsOnPoint(final double parentX, final double parentY) { + final double dx = parentX - getFullBoundsReference().getCenterX(); + final double dy = parentY - getFullBoundsReference().getCenterY(); offset(dx, dy); } @@ -1304,9 +1319,10 @@ * @param localBounds the bounds to test for intersection against * @return true if the given rectangle intersects this nodes geometry. */ - public boolean intersects(Rectangle2D localBounds) { - if (localBounds == null) + public boolean intersects(final Rectangle2D localBounds) { + if (localBounds == null) { return true; + } return getBoundsReference().intersects(localBounds); } @@ -1358,8 +1374,8 @@ * @param dstBounds if not null the new bounds will be stored here * @return the full bounds in the parent coordinate system of this node */ - public PBounds computeFullBounds(PBounds dstBounds) { - PBounds result = getUnionOfChildrenBounds(dstBounds); + public PBounds computeFullBounds(final PBounds dstBounds) { + final PBounds result = getUnionOfChildrenBounds(dstBounds); result.add(getBoundsReference()); localToParent(result); return result; @@ -1380,9 +1396,9 @@ dstBounds.resetToZero(); } - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); dstBounds.add(each.getFullBoundsReference()); } @@ -1396,7 +1412,7 @@ * @return the full bounds in global coordinate system. */ public PBounds getGlobalFullBounds() { - PBounds b = getFullBounds(); + final PBounds b = getFullBounds(); if (parent != null) { parent.localToGlobal(b); } @@ -1411,9 +1427,10 @@ * (specified in parent's coordinate system) * @return true if this nodes full bounds intersect the given bounds. */ - public boolean fullIntersects(Rectangle2D parentBounds) { - if (parentBounds == null) + public boolean fullIntersects(final Rectangle2D parentBounds) { + if (parentBounds == null) { return true; + } return getFullBoundsReference().intersects(parentBounds); } @@ -1450,7 +1467,7 @@ * @param childBoundsVolatile true if this node has a descendent with * volatile bounds */ - protected void setChildBoundsVolatile(boolean childBoundsVolatile) { + protected void setChildBoundsVolatile(final boolean childBoundsVolatile) { this.childBoundsVolatile = childBoundsVolatile; } @@ -1470,7 +1487,7 @@ * * @param boundsChanged true if this nodes bounds have changed. */ - protected void setBoundsChanged(boolean boundsChanged) { + protected void setBoundsChanged(final boolean boundsChanged) { this.boundsChanged = boundsChanged; } @@ -1489,7 +1506,7 @@ * of this node need to be recomputed as is the case when this node is * transformed or when one of this node's children changes geometry. */ - protected void setFullBoundsInvalid(boolean fullBoundsInvalid) { + protected void setFullBoundsInvalid(final boolean fullBoundsInvalid) { this.fullBoundsInvalid = fullBoundsInvalid; } @@ -1504,7 +1521,7 @@ * Set the flag indicating that one of this node's descendents has invalid * bounds. */ - protected void setChildBoundsInvalid(boolean childBoundsInvalid) { + protected void setChildBoundsInvalid(final boolean childBoundsInvalid) { this.childBoundsInvalid = childBoundsInvalid; } @@ -1519,9 +1536,9 @@ setBoundsChanged(true); firePropertyChange(PROPERTY_CODE_BOUNDS, PROPERTY_BOUNDS, null, bounds); - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); each.parentBoundsChanged(); } } @@ -1553,8 +1570,9 @@ n = n.parent; } - if (SCENE_GRAPH_DELEGATE != null) + if (SCENE_GRAPH_DELEGATE != null) { SCENE_GRAPH_DELEGATE.nodeFullBoundsInvalidated(this); + } } /** @@ -1565,7 +1583,7 @@ * @return true if this node or any of its descendents have volatile bounds */ protected boolean validateFullBounds() { - boolean boundsVolatile = getBoundsVolatile(); + final boolean boundsVolatile = getBoundsVolatile(); // 1. Only compute new bounds if invalid flags are set. if (fullBoundsInvalid || childBoundsInvalid || boundsVolatile || childBoundsVolatile) { @@ -1588,9 +1606,9 @@ // validate the bounds of all of my children. if (childBoundsInvalid || childBoundsVolatile) { childBoundsVolatile = false; - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); childBoundsVolatile |= each.validateFullBounds(); } } @@ -1609,11 +1627,11 @@ // bounds cache here after our own bounds and the children's bounds // have been computed above. if (fullBoundsInvalid) { - double oldX = fullBoundsCache.x; - double oldY = fullBoundsCache.y; - double oldWidth = fullBoundsCache.width; - double oldHeight = fullBoundsCache.height; - boolean oldEmpty = fullBoundsCache.isEmpty(); + final double oldX = fullBoundsCache.x; + final double oldY = fullBoundsCache.y; + final double oldWidth = fullBoundsCache.width; + final double oldHeight = fullBoundsCache.height; + final boolean oldEmpty = fullBoundsCache.isEmpty(); // 6. This will call getFullBoundsReference on all of the // children. So if the above @@ -1622,7 +1640,7 @@ // validated again here. fullBoundsCache = computeFullBounds(fullBoundsCache); - boolean fullBoundsChanged = fullBoundsCache.x != oldX || fullBoundsCache.y != oldY + final boolean fullBoundsChanged = fullBoundsCache.x != oldX || fullBoundsCache.y != oldY || fullBoundsCache.width != oldWidth || fullBoundsCache.height != oldHeight || fullBoundsCache.isEmpty() != oldEmpty; @@ -1632,8 +1650,9 @@ // bounds changes // deep in the tree percolate up. if (fullBoundsChanged) { - if (parent != null) + if (parent != null) { parent.invalidateFullBounds(); + } firePropertyChange(PROPERTY_CODE_FULL_BOUNDS, PROPERTY_FULL_BOUNDS, null, fullBoundsCache); // 8. If our paint was invalid make sure to repaint our old @@ -1687,8 +1706,9 @@ * @return rotation in radians. */ public double getRotation() { - if (transform == null) + if (transform == null) { return 0; + } return transform.getRotation(); } @@ -1698,7 +1718,7 @@ * * @param theta rotation in radians */ - public void setRotation(double theta) { + public void setRotation(final double theta) { rotate(theta - getRotation()); } @@ -1708,7 +1728,7 @@ * * @param theta the amount to rotate by in radians */ - public void rotate(double theta) { + public void rotate(final double theta) { rotateAboutPoint(theta, 0, 0); } @@ -1718,10 +1738,10 @@ * * @param theta the amount to rotate by in radians */ - public void rotateInPlace(double theta) { + public void rotateInPlace(final double theta) { PBounds b = getFullBoundsReference(); - double px = b.x; - double py = b.y; + final double px = b.x; + final double py = b.y; rotateAboutPoint(theta, 0, 0); b = getFullBoundsReference(); offset(px - b.x, py - b.y); @@ -1733,7 +1753,7 @@ * * @param theta the amount to rotate by in radians */ - public void rotateAboutPoint(double theta, Point2D point) { + public void rotateAboutPoint(final double theta, final Point2D point) { rotateAboutPoint(theta, point.getX(), point.getY()); } @@ -1743,7 +1763,7 @@ * * @param theta the amount to rotate by in radians */ - public void rotateAboutPoint(double theta, double x, double y) { + public void rotateAboutPoint(final double theta, final double x, final double y) { getTransformReference(true).rotate(theta, x, y); invalidatePaint(); invalidateFullBounds(); @@ -1769,7 +1789,7 @@ * @param theta the amount to rotate by in radians relative to the global * coord system. */ - public void setGlobalRotation(double theta) { + public void setGlobalRotation(final double theta) { if (parent != null) { setRotation(theta - parent.getGlobalRotation()); } @@ -1785,8 +1805,9 @@ * @return scale applied by this nodes transform. */ public double getScale() { - if (transform == null) + if (transform == null) { return 1; + } return transform.getScale(); } @@ -1796,9 +1817,10 @@ * * @param scale the scale to set the transform to */ - public void setScale(double scale) { - if (scale == 0) + public void setScale(final double scale) { + if (scale == 0) { throw new RuntimeException("Can't set scale to 0"); + } scale(scale / getScale()); } @@ -1808,7 +1830,7 @@ * * @param scale the amount to scale by */ - public void scale(double scale) { + public void scale(final double scale) { scaleAboutPoint(scale, 0, 0); } @@ -1819,7 +1841,7 @@ * @param scale the amount to scale by * @param point the point to scale about */ - public void scaleAboutPoint(double scale, Point2D point) { + public void scaleAboutPoint(final double scale, final Point2D point) { scaleAboutPoint(scale, point.getX(), point.getY()); } @@ -1829,7 +1851,7 @@ * * @param scale the amount to scale by */ - public void scaleAboutPoint(double scale, double x, double y) { + public void scaleAboutPoint(final double scale, final double x, final double y) { getTransformReference(true).scaleAboutPoint(scale, x, y); invalidatePaint(); invalidateFullBounds(); @@ -1851,7 +1873,7 @@ * * @param scale the desired global scale */ - public void setGlobalScale(double scale) { + public void setGlobalScale(final double scale) { if (parent != null) { setScale(scale / parent.getGlobalScale()); } @@ -1861,14 +1883,16 @@ } public double getXOffset() { - if (transform == null) + if (transform == null) { return 0; + } return transform.getTranslateX(); } public double getYOffset() { - if (transform == null) + if (transform == null) { return 0; + } return transform.getTranslateY(); } @@ -1881,8 +1905,9 @@ * @return a point representing the x and y offset */ public Point2D getOffset() { - if (transform == null) + if (transform == null) { return new Point2D.Double(); + } return new Point2D.Double(transform.getTranslateX(), transform.getTranslateY()); } @@ -1895,7 +1920,7 @@ * * @param point a point representing the x and y offset */ - public void setOffset(Point2D point) { + public void setOffset(final Point2D point) { setOffset(point.getX(), point.getY()); } @@ -1909,7 +1934,7 @@ * @param x amount of x offset * @param y amount of y offset */ - public void setOffset(double x, double y) { + public void setOffset(final double x, final double y) { getTransformReference(true).setOffset(x, y); invalidatePaint(); invalidateFullBounds(); @@ -1922,7 +1947,7 @@ * directly adding dx to the m02 position and dy to the m12 position in the * affine transform. */ - public void offset(double dx, double dy) { + public void offset(final double dx, final double dy) { getTransformReference(true); setOffset(transform.getTranslateX() + dx, transform.getTranslateY() + dy); } @@ -1932,7 +1957,7 @@ * affine transform translate method. This translation effects this node and * all of its descendents. */ - public void translate(double dx, double dy) { + public void translate(final double dx, final double dy) { getTransformReference(true).translate(dx, dy); invalidatePaint(); invalidateFullBounds(); @@ -1944,7 +1969,7 @@ * transform together with the transforms of all its ancestors. */ public Point2D getGlobalTranslation() { - Point2D p = getOffset(); + final Point2D p = getOffset(); if (parent != null) { parent.localToGlobal(p); } @@ -1958,7 +1983,7 @@ * * @param globalPoint the desired global translation */ - public void setGlobalTranslation(Point2D globalPoint) { + public void setGlobalTranslation(final Point2D globalPoint) { if (parent != null) { parent.getGlobalToLocalTransform(null).transform(globalPoint, globalPoint); } @@ -1970,7 +1995,7 @@ * * @param aTransform the transform to apply. */ - public void transformBy(AffineTransform aTransform) { + public void transformBy(final AffineTransform aTransform) { getTransformReference(true).concatenate(aTransform); invalidatePaint(); invalidateFullBounds(); @@ -1986,8 +2011,8 @@ * @param b to Point * @param t variable 'time' parameter */ - static public double lerp(double t, double a, double b) { - return (a + t * (b - a)); + static public double lerp(final double t, final double a, final double b) { + return a + t * (b - a); } /** @@ -2022,7 +2047,8 @@ * this transform's node * @param millis Number of milliseconds over which to perform the animation */ - public PActivity animateToRelativePosition(Point2D srcPt, Point2D destPt, Rectangle2D destBounds, int millis) { + public PActivity animateToRelativePosition(final Point2D srcPt, final Point2D destPt, final Rectangle2D destBounds, + final int millis) { double srcx, srcy; double destx, desty; double dx, dy; @@ -2033,7 +2059,7 @@ } else { // First compute translation amount in global coordinates - Rectangle2D srcBounds = getGlobalFullBounds(); + final Rectangle2D srcBounds = getGlobalFullBounds(); srcx = lerp(srcPt.getX(), srcBounds.getX(), srcBounds.getX() + srcBounds.getWidth()); srcy = lerp(srcPt.getY(), srcBounds.getY(), srcBounds.getY() + srcBounds.getHeight()); destx = lerp(destPt.getX(), destBounds.getX(), destBounds.getX() + destBounds.getWidth()); @@ -2044,11 +2070,11 @@ globalToLocal(pt1); pt2 = new Point2D.Double(destx, desty); globalToLocal(pt2); - dx = (pt2.getX() - pt1.getX()); - dy = (pt2.getY() - pt1.getY()); + dx = pt2.getX() - pt1.getX(); + dy = pt2.getY() - pt1.getY(); // Finally, animate change - PAffineTransform at = new PAffineTransform(getTransformReference(true)); + final PAffineTransform at = new PAffineTransform(getTransformReference(true)); at.translate(dx, dy); return animateToTransform(at, millis); } @@ -2090,7 +2116,7 @@ * this transform's node * @param millis Number of milliseconds over which to perform the animation */ - public void position(Point2D srcPt, Point2D destPt, Rectangle2D destBounds, int millis) { + public void position(final Point2D srcPt, final Point2D destPt, final Rectangle2D destBounds, final int millis) { animateToRelativePosition(srcPt, destPt, destBounds, millis); }; @@ -2119,7 +2145,7 @@ * * @return reference to this node's transform */ - public PAffineTransform getTransformReference(boolean createNewTransformIfNull) { + public PAffineTransform getTransformReference(final boolean createNewTransformIfNull) { if (transform == null && createNewTransformIfNull) { transform = new PAffineTransform(); } @@ -2139,7 +2165,7 @@ try { return new PAffineTransform(transform.createInverse()); } - catch (NoninvertibleTransformException e) { + catch (final NoninvertibleTransformException e) { throw new PAffineTransformException(e, transform); } } @@ -2149,7 +2175,7 @@ * * @param newTransform the new transform value */ - public void setTransform(AffineTransform newTransform) { + public void setTransform(final AffineTransform newTransform) { if (newTransform == null) { transform = null; } @@ -2204,7 +2230,7 @@ * * @param paintInvalid true if this node should be repainted */ - public void setPaintInvalid(boolean paintInvalid) { + public void setPaintInvalid(final boolean paintInvalid) { this.paintInvalid = paintInvalid; } @@ -2222,7 +2248,7 @@ * * @param childPaintInvalid true if this node has a child with invalid paint */ - public void setChildPaintInvalid(boolean childPaintInvalid) { + public void setChildPaintInvalid(final boolean childPaintInvalid) { this.childPaintInvalid = childPaintInvalid; } @@ -2239,8 +2265,9 @@ n = n.parent; } - if (SCENE_GRAPH_DELEGATE != null) + if (SCENE_GRAPH_DELEGATE != null) { SCENE_GRAPH_DELEGATE.nodePaintInvalidated(this); + } } /** @@ -2253,9 +2280,9 @@ } if (getChildPaintInvalid()) { - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); each.validateFullPaint(); } setChildPaintInvalid(false); @@ -2279,7 +2306,7 @@ * @param childOrThis if childOrThis does not equal this then this nodes * transform will be applied to the localBounds param */ - public void repaintFrom(PBounds localBounds, PNode childOrThis) { + public void repaintFrom(final PBounds localBounds, final PNode childOrThis) { if (parent != null) { if (childOrThis != this) { localToParent(localBounds); @@ -2296,7 +2323,7 @@ // complete. // **************************************************************** - public boolean isOpaque(Rectangle2D boundary) { + public boolean isOpaque(final Rectangle2D boundary) { return false; } @@ -2304,7 +2331,7 @@ return occluded; } - public void setOccluded(boolean isOccluded) { + public void setOccluded(final boolean isOccluded) { occluded = isOccluded; } @@ -2345,10 +2372,11 @@ * * @param isVisible true if this node and its descendents are visible */ - public void setVisible(boolean isVisible) { + public void setVisible(final boolean isVisible) { if (getVisible() != isVisible) { - if (!isVisible) + if (!isVisible) { repaint(); + } visible = isVisible; firePropertyChange(PROPERTY_CODE_VISIBLE, PROPERTY_VISIBLE, null, null); invalidatePaint(); @@ -2365,11 +2393,12 @@ /** * Set the paint used to paint this node. This value may be set to null. */ - public void setPaint(Paint newPaint) { - if (paint == newPaint) + public void setPaint(final Paint newPaint) { + if (paint == newPaint) { return; + } - Paint old = paint; + final Paint old = paint; paint = newPaint; invalidatePaint(); firePropertyChange(PROPERTY_CODE_PAINT, PROPERTY_PAINT, old, paint); @@ -2387,9 +2416,10 @@ * Set the transparency used to paint this node. Note that this transparency * applies to this node and all of its descendents. */ - public void setTransparency(float zeroToOne) { - if (transparency == zeroToOne) + public void setTransparency(final float zeroToOne) { + if (transparency == zeroToOne) { return; + } transparency = zeroToOne; invalidatePaint(); @@ -2403,9 +2433,9 @@ * * @param paintContext the paint context to use for painting the node */ - protected void paint(PPaintContext paintContext) { + protected void paint(final PPaintContext paintContext) { if (paint != null) { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); g2.setPaint(paint); g2.fill(getBoundsReference()); } @@ -2419,17 +2449,18 @@ * @param paintContext the paint context to use for painting this node and * its children */ - public void fullPaint(PPaintContext paintContext) { + public void fullPaint(final PPaintContext paintContext) { if (getVisible() && fullIntersects(paintContext.getLocalClip())) { paintContext.pushTransform(transform); paintContext.pushTransparency(transparency); - if (!getOccluded()) + if (!getOccluded()) { paint(paintContext); + } - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); each.fullPaint(paintContext); } @@ -2447,7 +2478,7 @@ * @param paintContext the paint context to sue for painting after the * children are painted */ - protected void paintAfterChildren(PPaintContext paintContext) { + protected void paintAfterChildren(final PPaintContext paintContext) { } /** @@ -2457,7 +2488,7 @@ * @return a new image representing this node and its descendents */ public Image toImage() { - PBounds b = getFullBoundsReference(); + final PBounds b = getFullBoundsReference(); return toImage((int) Math.ceil(b.getWidth()), (int) Math.ceil(b.getHeight()), null); } @@ -2471,14 +2502,14 @@ * @param height pixel height of the resulting image * @return a new image representing this node and its descendents */ - public Image toImage(int width, int height, Paint backGroundPaint) { + public Image toImage(final int width, final int height, final Paint backGroundPaint) { BufferedImage result; if (GraphicsEnvironment.isHeadless()) { result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { - GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment() + final GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); result = graphicsConfiguration.createCompatibleImage(width, height, Transparency.TRANSLUCENT); } @@ -2494,10 +2525,10 @@ * @return a rendering of this image and its descendents into the specified * image */ - public Image toImage(BufferedImage image, Paint backGroundPaint) { - int width = image.getWidth(); - int height = image.getHeight(); - Graphics2D g2 = image.createGraphics(); + public Image toImage(final BufferedImage image, final Paint backGroundPaint) { + final int width = image.getWidth(); + final int height = image.getHeight(); + final Graphics2D g2 = image.createGraphics(); if (backGroundPaint != null) { g2.setPaint(backGroundPaint); @@ -2505,10 +2536,10 @@ } // reuse print method - Paper paper = new Paper(); + final Paper paper = new Paper(); paper.setSize(width, height); paper.setImageableArea(0, 0, width, height); - PageFormat pageFormat = new PageFormat(); + final PageFormat pageFormat = new PageFormat(); pageFormat.setPaper(paper); print(g2, pageFormat, 0); @@ -2520,9 +2551,9 @@ * print to, And then prints the node. */ public void print() { - PrinterJob printJob = PrinterJob.getPrinterJob(); - PageFormat pageFormat = printJob.defaultPage(); - Book book = new Book(); + final PrinterJob printJob = PrinterJob.getPrinterJob(); + final PageFormat pageFormat = printJob.defaultPage(); + final Book book = new Book(); book.append(this, pageFormat); printJob.setPageable(book); @@ -2530,7 +2561,7 @@ try { printJob.print(); } - catch (PrinterException e) { + catch (final PrinterException e) { System.out.println("Error Printing"); e.printStackTrace(); } @@ -2548,13 +2579,13 @@ * @param pageFormat the size and orientation of the page * @param pageIndex the zero based index of the page to be drawn */ - public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { + public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) { if (pageIndex != 0) { return NO_SUCH_PAGE; } - Graphics2D g2 = (Graphics2D) graphics; - PBounds imageBounds = getFullBounds(); + final Graphics2D g2 = (Graphics2D) graphics; + final PBounds imageBounds = getFullBounds(); imageBounds.expandNearestIntegerDimensions(); @@ -2570,7 +2601,7 @@ g2.scale(scale, scale); g2.translate(-imageBounds.x, -imageBounds.y); - PPaintContext pc = new PPaintContext(g2); + final PPaintContext pc = new PPaintContext(g2); pc.setRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING); fullPaint(pc); @@ -2622,7 +2653,7 @@ * * @param isPickable true if this node is pickable */ - public void setPickable(boolean isPickable) { + public void setPickable(final boolean isPickable) { if (getPickable() != isPickable) { pickable = isPickable; firePropertyChange(PROPERTY_CODE_PICKABLE, PROPERTY_PICKABLE, null, null); @@ -2646,7 +2677,7 @@ * * @param areChildrenPickable true if this node tries to pick its children */ - public void setChildrenPickable(boolean areChildrenPickable) { + public void setChildrenPickable(final boolean areChildrenPickable) { if (getChildrenPickable() != areChildrenPickable) { childrenPickable = areChildrenPickable; firePropertyChange(PROPERTY_CODE_CHILDREN_PICKABLE, PROPERTY_CHILDREN_PICKABLE, null, null); @@ -2661,7 +2692,7 @@ * @param pickPath the pick path used for the pick operation * @return true if this node was picked */ - protected boolean pick(PPickPath pickPath) { + protected boolean pick(final PPickPath pickPath) { return false; } @@ -2673,23 +2704,24 @@ * @param pickPath the pick path to add the node to if its picked * @return true if this node or one of its descendents was picked. */ - public boolean fullPick(PPickPath pickPath) { + public boolean fullPick(final PPickPath pickPath) { if ((getPickable() || getChildrenPickable()) && fullIntersects(pickPath.getPickBounds())) { pickPath.pushNode(this); pickPath.pushTransform(transform); - boolean thisPickable = getPickable() && pickPath.acceptsNode(this); + final boolean thisPickable = getPickable() && pickPath.acceptsNode(this); if (thisPickable && pick(pickPath)) { return true; } if (getChildrenPickable()) { - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = count - 1; i >= 0; i--) { - PNode each = (PNode) children.get(i); - if (each.fullPick(pickPath)) + final PNode each = (PNode) children.get(i); + if (each.fullPick(pickPath)) { return true; + } } } @@ -2704,17 +2736,17 @@ return false; } - public void findIntersectingNodes(Rectangle2D fullBounds, ArrayList results) { + public void findIntersectingNodes(final Rectangle2D fullBounds, final ArrayList results) { if (fullIntersects(fullBounds)) { - Rectangle2D localBounds = parentToLocal((Rectangle2D) fullBounds.clone()); + final Rectangle2D localBounds = parentToLocal((Rectangle2D) fullBounds.clone()); if (intersects(localBounds)) { results.add(this); } - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = count - 1; i >= 0; i--) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); each.findIntersectingNodes(localBounds, results); } } @@ -2728,7 +2760,7 @@ * @param pickPath the pick path used for the pick operation * @return true if this node was picked */ - protected boolean pickAfterChildren(PPickPath pickPath) { + protected boolean pickAfterChildren(final PPickPath pickPath) { if (intersects(pickPath.getPickBounds())) { return true; } @@ -2750,10 +2782,11 @@ * * @param child the new child to add to this node */ - public void addChild(PNode child) { + public void addChild(final PNode child) { int insertIndex = getChildrenCount(); - if (child.parent == this) + if (child.parent == this) { insertIndex--; + } addChild(insertIndex, child); } @@ -2764,8 +2797,8 @@ * * @param child the new child to add to this node */ - public void addChild(int index, PNode child) { - PNode oldParent = child.getParent(); + public void addChild(final int index, final PNode child) { + final PNode oldParent = child.getParent(); if (oldParent != null) { oldParent.removeChild(child); @@ -2785,10 +2818,10 @@ * * @param nodes a collection of nodes to be added to this node */ - public void addChildren(Collection nodes) { - Iterator i = nodes.iterator(); + public void addChildren(final Collection nodes) { + final Iterator i = nodes.iterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); addChild(each); } } @@ -2799,11 +2832,12 @@ * @param node a possible descendent node * @return true if this node is an ancestor of the given node */ - public boolean isAncestorOf(PNode node) { + public boolean isAncestorOf(final PNode node) { PNode p = node.parent; while (p != null) { - if (p == this) + if (p == this) { return true; + } p = p.parent; } return false; @@ -2815,11 +2849,12 @@ * @param node a possible ancestor node * @return true if this nodes descends from the given node */ - public boolean isDescendentOf(PNode node) { + public boolean isDescendentOf(final PNode node) { PNode p = parent; while (p != null) { - if (p == node) + if (p == node) { return true; + } p = p.parent; } return false; @@ -2837,7 +2872,7 @@ * will draw in back of all of its other sibling nodes. */ public void moveToBack() { - PNode p = parent; + final PNode p = parent; if (p != null) { p.removeChild(this); p.addChild(0, this); @@ -2848,11 +2883,11 @@ * Change the order of this node in its parent's children list so that it * will draw in front of all of its other sibling nodes. */ - public void moveInBackOf(PNode sibling) { - PNode p = parent; + public void moveInBackOf(final PNode sibling) { + final PNode p = parent; if (p != null && p == sibling.getParent()) { p.removeChild(this); - int index = p.indexOfChild(sibling); + final int index = p.indexOfChild(sibling); p.addChild(index, this); } } @@ -2862,7 +2897,7 @@ * will draw after the given sibling node. */ public void moveToFront() { - PNode p = parent; + final PNode p = parent; if (p != null) { p.removeChild(this); p.addChild(this); @@ -2873,11 +2908,11 @@ * Change the order of this node in its parent's children list so that it * will draw before the given sibling node. */ - public void moveInFrontOf(PNode sibling) { - PNode p = parent; + public void moveInFrontOf(final PNode sibling) { + final PNode p = parent; if (p != null && p == sibling.getParent()) { p.removeChild(this); - int index = p.indexOfChild(sibling); + final int index = p.indexOfChild(sibling); p.addChild(index + 1, this); } } @@ -2896,8 +2931,8 @@ * Set the parent of this node. Note this is set automatically when adding * and removing children. */ - public void setParent(PNode newParent) { - PNode old = parent; + public void setParent(final PNode newParent) { + final PNode old = parent; parent = newParent; firePropertyChange(PROPERTY_CODE_PARENT, PROPERTY_PARENT, old, parent); } @@ -2905,9 +2940,10 @@ /** * Return the index where the given child is stored. */ - public int indexOfChild(PNode child) { - if (children == null) + public int indexOfChild(final PNode child) { + if (children == null) { return -1; + } return children.indexOf(child); } @@ -2919,8 +2955,8 @@ * @param child the child to remove * @return the removed child */ - public PNode removeChild(PNode child) { - int index = indexOfChild(child); + public PNode removeChild(final PNode child) { + final int index = indexOfChild(child); if (index == -1) { return null; } @@ -2935,11 +2971,11 @@ * @param index the index of the child to remove * @return the removed child */ - public PNode removeChild(int index) { + public PNode removeChild(final int index) { if (children == null) { return null; } - PNode child = (PNode) children.remove(index); + final PNode child = (PNode) children.remove(index); if (children.size() == 0) { children = null; @@ -2960,10 +2996,10 @@ * * @param childrenNodes the collection of children to remove */ - public void removeChildren(Collection childrenNodes) { - Iterator i = childrenNodes.iterator(); + public void removeChildren(final Collection childrenNodes) { + final Iterator i = childrenNodes.iterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); removeChild(each); } } @@ -2974,9 +3010,9 @@ */ public void removeAllChildren() { if (children != null) { - int count = children.size(); + final int count = children.size(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); each.setParent(null); } children = null; @@ -3002,9 +3038,9 @@ * * @param newParent The new parent of this node. */ - public void reparent(PNode newParent) { - AffineTransform originalTransform = getLocalToGlobalTransform(null); - AffineTransform newTransform = newParent.getGlobalToLocalTransform(null); + public void reparent(final PNode newParent) { + final AffineTransform originalTransform = getLocalToGlobalTransform(null); + final AffineTransform newTransform = newParent.getGlobalToLocalTransform(null); newTransform.concatenate(originalTransform); removeFromParent(); @@ -3025,10 +3061,10 @@ * @param replacementNode the new node that replaces the current node in the * scene graph tree. */ - public void replaceWith(PNode replacementNode) { + public void replaceWith(final PNode replacementNode) { if (parent != null) { - PNode p = this.parent; - int index = p.getChildrenReference().indexOf(this); + final PNode p = parent; + final int index = p.getChildrenReference().indexOf(this); p.removeChild(this); p.addChild(index, replacementNode); } @@ -3052,7 +3088,7 @@ * @param index a child index * @return the child node at the specified index */ - public PNode getChild(int index) { + public PNode getChild(final int index) { return (PNode) children.get(index); } @@ -3111,16 +3147,18 @@ * @param filter the filter used to determine the subset * @return a collection containing this node and all descendents */ - public Collection getAllNodes(PNodeFilter filter, Collection results) { - if (results == null) + public Collection getAllNodes(final PNodeFilter filter, Collection results) { + if (results == null) { results = new ArrayList(); - if (filter == null || filter.accept(this)) + } + if (filter == null || filter.accept(this)) { results.add(this); + } if (filter == null || filter.acceptChildrenOf(this)) { - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = 0; i < count; i++) { - PNode each = (PNode) children.get(i); + final PNode each = (PNode) children.get(i); each.getAllNodes(filter, results); } } @@ -3144,7 +3182,7 @@ * @param out the output stream to write to, must be an instance of * PObjectOutputStream */ - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); ((PObjectOutputStream) out).writeConditionalObject(parent); } @@ -3154,7 +3192,7 @@ * * @param in the stream to read from */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); parent = (PNode) in.readObject(); } @@ -3167,7 +3205,7 @@ * Returns a string representation of this object for debugging purposes. */ public String toString() { - String result = super.toString().replaceAll(".*\\.", ""); + final String result = super.toString().replaceAll(".*\\.", ""); return result + "[" + paramString() + "]"; } @@ -3180,7 +3218,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("bounds=" + (bounds == null ? "null" : bounds.toString())); result.append(",fullBounds=" + (fullBoundsCache == null ? "null" : fullBoundsCache.toString())); @@ -3209,12 +3247,13 @@ } public PInputEventListener[] getInputEventListeners() { - if (listenerList == null || listenerList.getListenerCount() == 0) + if (listenerList == null || listenerList.getListenerCount() == 0) { return new PInputEventListener[] {}; + } - EventListener[] listeners = listenerList.getListeners(PInputEventListener.class); + final EventListener[] listeners = listenerList.getListeners(PInputEventListener.class); - PInputEventListener[] result = new PInputEventListener[listeners.length]; + final PInputEventListener[] result = new PInputEventListener[listeners.length]; for (int i = 0; i < listeners.length; i++) { result[i] = (PInputEventListener) listeners[i]; } diff --git a/core/src/main/java/edu/umd/cs/piccolo/PRoot.java b/core/src/main/java/edu/umd/cs/piccolo/PRoot.java index f804f84..28a20c7 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/PRoot.java +++ b/core/src/main/java/edu/umd/cs/piccolo/PRoot.java @@ -74,9 +74,9 @@ private transient int interacting; private PInputManager defaultInputManager; - private transient List inputSources; + private transient final List inputSources; private transient long globalTime; - private PActivityScheduler activityScheduler; + private final PActivityScheduler activityScheduler; /** * This interfaces is for advanced use only. If you want to implement a @@ -108,7 +108,7 @@ * processInputs method. When the activity has finished running * it will automatically get removed. */ - public boolean addActivity(PActivity activity) { + public boolean addActivity(final PActivity activity) { getActivityScheduler().addActivity(activity); return true; } @@ -127,21 +127,21 @@ * activities instead of using this method. */ public void waitForActivities() { - PNodeFilter cameraWithCanvas = new PNodeFilter() { - public boolean accept(PNode aNode) { - return (aNode instanceof PCamera) && (((PCamera) aNode).getComponent() != null); + final PNodeFilter cameraWithCanvas = new PNodeFilter() { + public boolean accept(final PNode aNode) { + return aNode instanceof PCamera && ((PCamera) aNode).getComponent() != null; } - public boolean acceptChildrenOf(PNode aNode) { + public boolean acceptChildrenOf(final PNode aNode) { return true; } }; while (activityScheduler.getActivitiesReference().size() > 0) { processInputs(); - Iterator i = getAllNodes(cameraWithCanvas, null).iterator(); + final Iterator i = getAllNodes(cameraWithCanvas, null).iterator(); while (i.hasNext()) { - PCamera each = (PCamera) i.next(); + final PCamera each = (PCamera) i.next(); each.getComponent().paintImmediately(); } } @@ -194,7 +194,7 @@ * @see PCanvas#setInteracting(boolean) */ public void setInteracting(boolean isInteracting) { - boolean wasInteracting = getInteracting(); + final boolean wasInteracting = getInteracting(); if (isInteracting) { interacting++; @@ -207,7 +207,7 @@ if (!isInteracting) { // force all the child cameras to repaint for (int i = 0; i < getChildrenCount(); i++) { - PNode child = getChild(i); + final PNode child = getChild(i); if (child instanceof PCamera) { child.repaint(); } @@ -225,7 +225,7 @@ * process you can do that here. You will seldom do this unless you are * making additions to the piccolo framework. */ - public void addInputSource(InputSource inputSource) { + public void addInputSource(final InputSource inputSource) { inputSources.add(inputSource); firePropertyChange(PROPERTY_CODE_INPUT_SOURCES, PROPERTY_INPUT_SOURCES, null, inputSources); } @@ -235,7 +235,7 @@ * UI process you can do that here. You will seldom do this unless you are * making additions to the piccolo framework. */ - public void removeInputSource(InputSource inputSource) { + public void removeInputSource(final InputSource inputSource) { inputSources.remove(inputSource); firePropertyChange(PROPERTY_CODE_INPUT_SOURCES, PROPERTY_INPUT_SOURCES, null, inputSources); } @@ -245,7 +245,7 @@ * create custom timers that will be used transparently by the Piccolo * framework. */ - public Timer createTimer(int delay, ActionListener listener) { + public Timer createTimer(final int delay, final ActionListener listener) { return new Timer(delay, listener); } @@ -273,9 +273,9 @@ processingInputs = true; globalTime = System.currentTimeMillis(); - int count = inputSources == null ? 0 : inputSources.size(); + final int count = inputSources == null ? 0 : inputSources.size(); for (int i = 0; i < count; i++) { - InputSource each = (InputSource) inputSources.get(i); + final InputSource each = (InputSource) inputSources.get(i); each.processInput(); } @@ -287,22 +287,22 @@ PDebug.endProcessingInput(); } - public void setFullBoundsInvalid(boolean fullLayoutInvalid) { + public void setFullBoundsInvalid(final boolean fullLayoutInvalid) { super.setFullBoundsInvalid(fullLayoutInvalid); scheduleProcessInputsIfNeeded(); } - public void setChildBoundsInvalid(boolean childLayoutInvalid) { + public void setChildBoundsInvalid(final boolean childLayoutInvalid) { super.setChildBoundsInvalid(childLayoutInvalid); scheduleProcessInputsIfNeeded(); } - public void setPaintInvalid(boolean paintInvalid) { + public void setPaintInvalid(final boolean paintInvalid) { super.setPaintInvalid(paintInvalid); scheduleProcessInputsIfNeeded(); } - public void setChildPaintInvalid(boolean childPaintInvalid) { + public void setChildPaintInvalid(final boolean childPaintInvalid) { super.setChildPaintInvalid(childPaintInvalid); scheduleProcessInputsIfNeeded(); } @@ -332,7 +332,7 @@ SwingUtilities.invokeLater(new Runnable() { public void run() { processInputs(); - PRoot.this.processInputsScheduled = false; + processInputsScheduled = false; } }); } diff --git a/core/src/main/java/edu/umd/cs/piccolo/activities/PActivity.java b/core/src/main/java/edu/umd/cs/piccolo/activities/PActivity.java index 052ad36..e0e82c2 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/activities/PActivity.java +++ b/core/src/main/java/edu/umd/cs/piccolo/activities/PActivity.java @@ -78,7 +78,7 @@ * @param aDuration the amount of time that this activity should take to * complete, -1 for infinite. */ - public PActivity(long aDuration) { + public PActivity(final long aDuration) { this(aDuration, PUtil.DEFAULT_ACTIVITY_STEP_RATE); } @@ -90,7 +90,7 @@ * @param aStepRate the maximum rate that this activity should receive step * events. */ - public PActivity(long aDuration, long aStepRate) { + public PActivity(final long aDuration, final long aStepRate) { this(aDuration, aStepRate, System.currentTimeMillis()); } @@ -104,7 +104,7 @@ * @param aStartTime the time (relative to System.currentTimeMillis()) that * this activity should start. */ - public PActivity(long aDuration, long aStepRate, long aStartTime) { + public PActivity(final long aDuration, final long aStepRate, final long aStartTime) { duration = aDuration; stepRate = aStepRate; startTime = aStartTime; @@ -130,7 +130,7 @@ * time. When this time is reached (or soon after) this activity will have * its startStepping() method called. */ - public void setStartTime(long aTriggerTime) { + public void setStartTime(final long aTriggerTime) { startTime = aTriggerTime; } @@ -144,7 +144,7 @@ /** * Set the amount of time that this activity should delay between steps. */ - public void setStepRate(long aStepRate) { + public void setStepRate(final long aStepRate) { stepRate = aStepRate; } @@ -164,7 +164,7 @@ * Set the amount of time that this activity should take to complete, after * the startStepping method is called. */ - public void setDuration(long aDuration) { + public void setDuration(final long aDuration) { duration = aDuration; } @@ -172,7 +172,7 @@ return scheduler; } - public void setActivityScheduler(PActivityScheduler aScheduler) { + public void setActivityScheduler(final PActivityScheduler aScheduler) { scheduler = aScheduler; } @@ -202,8 +202,9 @@ * activity finishes. */ protected void activityStarted() { - if (delegate != null) + if (delegate != null) { delegate.activityStarted(this); + } } /** @@ -213,9 +214,10 @@ * @param elapsedTime the amount of time that has passed relative to the * activities startTime. */ - protected void activityStep(long elapsedTime) { - if (delegate != null) + protected void activityStep(final long elapsedTime) { + if (delegate != null) { delegate.activityStepped(this); + } } /** @@ -223,8 +225,9 @@ * activity has been removed from the PActivityScheduler queue. */ protected void activityFinished() { - if (delegate != null) + if (delegate != null) { delegate.activityFinished(this); + } } /** @@ -239,7 +242,7 @@ * Set the delegate for this activity. The delegate is notified when the * activity starts and stops stepping. */ - public void setDelegate(PActivityDelegate delegate) { + public void setDelegate(final PActivityDelegate delegate) { this.delegate = delegate; } @@ -253,7 +256,7 @@ * or duration of the first activity is later changed this activities start * time will not be updated to reflect that change. */ - public void startAfter(PActivity first) { + public void startAfter(final PActivity first) { setStartTime(first.getStartTime() + first.getDuration()); } @@ -281,7 +284,7 @@ * called. TERMINATE_AND_FINISH_IF_STEPPING - The method activityFinished * will only be called if the activity has previously started. */ - public void terminate(int terminationBehavior) { + public void terminate(final int terminationBehavior) { if (scheduler != null) { scheduler.removeActivity(this); } @@ -316,7 +319,7 @@ * The activity scheduler calls this method and it is here that the activity * decides if it should do a step or not for the given time. */ - public long processStep(long currentTime) { + public long processStep(final long currentTime) { // if before start time if (currentTime < startTime) { return startTime - currentTime; @@ -370,7 +373,7 @@ * Returns a string representation of this object for debugging purposes. */ public String toString() { - String result = super.toString().replaceAll(".*\\.", ""); + final String result = super.toString().replaceAll(".*\\.", ""); return result + "[" + paramString() + "]"; } @@ -383,13 +386,14 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("startTime=" + startTime); result.append(",duration=" + duration); result.append(",stepRate=" + stepRate); - if (stepping) + if (stepping) { result.append(",stepping"); + } result.append(",nextStepTime=" + nextStepTime); return result.toString(); diff --git a/core/src/main/java/edu/umd/cs/piccolo/activities/PActivityScheduler.java b/core/src/main/java/edu/umd/cs/piccolo/activities/PActivityScheduler.java index 22cd084..13a01ab 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/activities/PActivityScheduler.java +++ b/core/src/main/java/edu/umd/cs/piccolo/activities/PActivityScheduler.java @@ -54,14 +54,14 @@ */ public class PActivityScheduler { - private PRoot root; - private List activities; + private final PRoot root; + private final List activities; private Timer activityTimer; private boolean activitiesChanged; private boolean animating; - private ArrayList processingActivities; + private final ArrayList processingActivities; - public PActivityScheduler(PRoot rootNode) { + public PActivityScheduler(final PRoot rootNode) { root = rootNode; activities = new ArrayList(); processingActivities = new ArrayList(); @@ -71,7 +71,7 @@ return root; } - public void addActivity(PActivity activity) { + public void addActivity(final PActivity activity) { addActivity(activity, false); } @@ -80,9 +80,10 @@ * that an activity is run after all other activities have been run. To do * this set processLast to true when adding the activity. */ - public void addActivity(PActivity activity, boolean processLast) { - if (activities.contains(activity)) + public void addActivity(final PActivity activity, final boolean processLast) { + if (activities.contains(activity)) { return; + } activitiesChanged = true; @@ -100,9 +101,10 @@ } } - public void removeActivity(PActivity activity) { - if (!activities.contains(activity)) + public void removeActivity(final PActivity activity) { + if (!activities.contains(activity)) { return; + } activitiesChanged = true; activities.remove(activity); @@ -126,13 +128,13 @@ * Process all scheduled activities for the given time. Each activity is * given one "step", equivalent to one frame of animation. */ - public void processActivities(long currentTime) { - int size = activities.size(); + public void processActivities(final long currentTime) { + final int size = activities.size(); if (size > 0) { processingActivities.clear(); processingActivities.addAll(activities); for (int i = size - 1; i >= 0; i--) { - PActivity each = (PActivity) processingActivities.get(i); + final PActivity each = (PActivity) processingActivities.get(i); each.processStep(currentTime); } } @@ -146,7 +148,7 @@ if (activitiesChanged) { animating = false; for (int i = 0; i < activities.size(); i++) { - PActivity each = (PActivity) activities.get(i); + final PActivity each = (PActivity) activities.get(i); animating |= each.isAnimation(); } activitiesChanged = false; @@ -165,7 +167,7 @@ protected Timer getActivityTimer() { if (activityTimer == null) { activityTimer = root.createTimer(PUtil.ACTIVITY_SCHEDULER_FRAME_DELAY, new ActionListener() { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(final ActionEvent e) { root.processInputs(); } }); diff --git a/core/src/main/java/edu/umd/cs/piccolo/activities/PColorActivity.java b/core/src/main/java/edu/umd/cs/piccolo/activities/PColorActivity.java index 873c9be..e8faf16 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/activities/PColorActivity.java +++ b/core/src/main/java/edu/umd/cs/piccolo/activities/PColorActivity.java @@ -43,7 +43,7 @@ private Color source; private Color destination; - private Target target; + private final Target target; /** * Target Objects that want their color to be set by the color @@ -65,11 +65,11 @@ public Color getColor(); } - public PColorActivity(long duration, long stepRate, Target aTarget) { + public PColorActivity(final long duration, final long stepRate, final Target aTarget) { this(duration, stepRate, aTarget, null); } - public PColorActivity(long duration, long stepRate, Target aTarget, Color aDestination) { + public PColorActivity(final long duration, final long stepRate, final Target aTarget, final Color aDestination) { this(duration, stepRate, 1, PInterpolatingActivity.SOURCE_TO_DESTINATION, aTarget, aDestination); } @@ -85,7 +85,8 @@ * the source state will be taken from. * @param aDestination the destination color state */ - public PColorActivity(long duration, long stepRate, int loopCount, int mode, Target aTarget, Color aDestination) { + public PColorActivity(final long duration, final long stepRate, final int loopCount, final int mode, + final Target aTarget, final Color aDestination) { super(duration, stepRate, loopCount, mode); target = aTarget; destination = aDestination; @@ -107,22 +108,23 @@ * Set the final color that will be set on the color activities target when * the activity stops stepping. */ - public void setDestinationColor(Color newDestination) { + public void setDestinationColor(final Color newDestination) { destination = newDestination; } protected void activityStarted() { - if (getFirstLoop()) + if (getFirstLoop()) { source = target.getColor(); + } super.activityStarted(); } - public void setRelativeTargetValue(float zeroToOne) { + public void setRelativeTargetValue(final float zeroToOne) { super.setRelativeTargetValue(zeroToOne); - float red = (float) (source.getRed() + (zeroToOne * (destination.getRed() - source.getRed()))); - float green = (float) (source.getGreen() + (zeroToOne * (destination.getGreen() - source.getGreen()))); - float blue = (float) (source.getBlue() + (zeroToOne * (destination.getBlue() - source.getBlue()))); - float alpha = (float) (source.getAlpha() + (zeroToOne * (destination.getAlpha() - source.getAlpha()))); + final float red = (source.getRed() + zeroToOne * (destination.getRed() - source.getRed())); + final float green = (source.getGreen() + zeroToOne * (destination.getGreen() - source.getGreen())); + final float blue = (source.getBlue() + zeroToOne * (destination.getBlue() - source.getBlue())); + final float alpha = (source.getAlpha() + zeroToOne * (destination.getAlpha() - source.getAlpha())); target.setColor(new Color(red / 255, green / 255, blue / 255, alpha / 255)); } @@ -139,7 +141,7 @@ * @return a string representation of this object's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("source=" + (source == null ? "null" : source.toString())); result.append(",destination=" + (destination == null ? "null" : destination.toString())); diff --git a/core/src/main/java/edu/umd/cs/piccolo/activities/PInterpolatingActivity.java b/core/src/main/java/edu/umd/cs/piccolo/activities/PInterpolatingActivity.java index c11e80f..02d3094 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/activities/PInterpolatingActivity.java +++ b/core/src/main/java/edu/umd/cs/piccolo/activities/PInterpolatingActivity.java @@ -55,11 +55,11 @@ private int loopCount; private boolean firstLoop; - public PInterpolatingActivity(long duration, long stepRate) { + public PInterpolatingActivity(final long duration, final long stepRate) { this(duration, stepRate, 1, PInterpolatingActivity.SOURCE_TO_DESTINATION); } - public PInterpolatingActivity(long duration, long stepRate, int loopCount, int mode) { + public PInterpolatingActivity(final long duration, final long stepRate, final int loopCount, final int mode) { this(duration, stepRate, System.currentTimeMillis(), loopCount, mode); } @@ -74,7 +74,8 @@ * @param loopCount number of times the activity should reschedule itself * @param mode defines how the activity interpolates between states */ - public PInterpolatingActivity(long duration, long stepRate, long startTime, int loopCount, int mode) { + public PInterpolatingActivity(final long duration, final long stepRate, final long startTime, final int loopCount, + final int mode) { super(duration, stepRate, startTime); this.loopCount = loopCount; this.mode = mode; @@ -87,9 +88,10 @@ * the startStepping method is called. The duration must be greater then * zero so that the interpolation value can be computed. */ - public void setDuration(long aDuration) { - if (aDuration <= 0) + public void setDuration(final long aDuration) { + if (aDuration <= 0) { throw new IllegalArgumentException("Duration for PInterpolatingActivity must be greater then 0"); + } super.setDuration(aDuration); } @@ -109,7 +111,7 @@ /** * Set the mode that defines how the activity interpolates between states. */ - public void setMode(int mode) { + public void setMode(final int mode) { this.mode = mode; } @@ -125,7 +127,7 @@ * Set the number of times the activity should automatically reschedule * itself after it has finished. */ - public void setLoopCount(int loopCount) { + public void setLoopCount(final int loopCount) { this.loopCount = loopCount; } @@ -142,7 +144,7 @@ * initialize their source state on the first loop. This method will rarely * need to be called, unless your are reusing activities. */ - public void setFirstLoop(boolean firstLoop) { + public void setFirstLoop(final boolean firstLoop) { this.firstLoop = firstLoop; } @@ -150,7 +152,7 @@ return slowInSlowOut; } - public void setSlowInSlowOut(boolean isSlowInSlowOut) { + public void setSlowInSlowOut(final boolean isSlowInSlowOut) { slowInSlowOut = isSlowInSlowOut; } @@ -167,7 +169,7 @@ setRelativeTargetValueAdjustingForMode(0); } - protected void activityStep(long elapsedTime) { + protected void activityStep(final long elapsedTime) { super.activityStep(elapsedTime); float t = elapsedTime / (float) getDuration(); @@ -186,10 +188,11 @@ setRelativeTargetValueAdjustingForMode(1); super.activityFinished(); - PActivityScheduler scheduler = getActivityScheduler(); + final PActivityScheduler scheduler = getActivityScheduler(); if (loopCount > 1) { - if (loopCount != Integer.MAX_VALUE) + if (loopCount != Integer.MAX_VALUE) { loopCount--; + } firstLoop = false; setStartTime(scheduler.getRoot().getGlobalTime()); scheduler.addActivity(this); @@ -210,16 +213,16 @@ * Subclasses should override this method and set the value on their target * (the object that they are modifying) accordingly. */ - public void setRelativeTargetValue(float zeroToOne) { + public void setRelativeTargetValue(final float zeroToOne) { } - public float computeSlowInSlowOut(float zeroToOne) { + public float computeSlowInSlowOut(final float zeroToOne) { if (zeroToOne < 0.5) { return 2.0f * zeroToOne * zeroToOne; } else { - float complement = 1.0f - zeroToOne; - return 1.0f - (2.0f * complement * complement); + final float complement = 1.0f - zeroToOne; + return 1.0f - 2.0f * complement * complement; } } @@ -237,7 +240,7 @@ zeroToOne *= 2; } else { - zeroToOne = 1 - ((zeroToOne - 0.5f) * 2); + zeroToOne = 1 - (zeroToOne - 0.5f) * 2; } break; } @@ -258,7 +261,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); if (slowInSlowOut) { result.append("slowinSlowOut,"); diff --git a/core/src/main/java/edu/umd/cs/piccolo/activities/PTransformActivity.java b/core/src/main/java/edu/umd/cs/piccolo/activities/PTransformActivity.java index aa39939..81cd4da 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/activities/PTransformActivity.java +++ b/core/src/main/java/edu/umd/cs/piccolo/activities/PTransformActivity.java @@ -46,9 +46,9 @@ private static PAffineTransform STATIC_TRANSFORM = new PAffineTransform(); - private double[] source; + private final double[] source; private double[] destination; - private Target target; + private final Target target; /** * Target Objects that want to get transformed by the transform @@ -70,11 +70,12 @@ public void getSourceMatrix(double[] aSource); } - public PTransformActivity(long duration, long stepRate, Target aTarget) { + public PTransformActivity(final long duration, final long stepRate, final Target aTarget) { this(duration, stepRate, aTarget, null); } - public PTransformActivity(long duration, long stepRate, Target aTarget, AffineTransform aDestination) { + public PTransformActivity(final long duration, final long stepRate, final Target aTarget, + final AffineTransform aDestination) { this(duration, stepRate, 1, PInterpolatingActivity.SOURCE_TO_DESTINATION, aTarget, aDestination); } @@ -90,14 +91,15 @@ * the source state will be taken from. * @param aDestination the destination color state */ - public PTransformActivity(long duration, long stepRate, int loopCount, int mode, Target aTarget, - AffineTransform aDestination) { + public PTransformActivity(final long duration, final long stepRate, final int loopCount, final int mode, + final Target aTarget, final AffineTransform aDestination) { super(duration, stepRate, loopCount, mode); source = new double[6]; destination = new double[6]; target = aTarget; - if (aDestination != null) + if (aDestination != null) { aDestination.getMatrix(destination); + } } protected boolean isAnimation() { @@ -116,24 +118,24 @@ * Set the final transform that will be set on the transform activities * target when the transform activity stops stepping. */ - public void setDestinationTransform(double[] newDestination) { + public void setDestinationTransform(final double[] newDestination) { destination = newDestination; } protected void activityStarted() { - if (getFirstLoop()) + if (getFirstLoop()) { target.getSourceMatrix(source); + } super.activityStarted(); } - public void setRelativeTargetValue(float zeroToOne) { + public void setRelativeTargetValue(final float zeroToOne) { super.setRelativeTargetValue(zeroToOne); - STATIC_TRANSFORM.setTransform(source[0] + (zeroToOne * (destination[0] - source[0])), source[1] - + (zeroToOne * (destination[1] - source[1])), source[2] + (zeroToOne * (destination[2] - source[2])), - source[3] + (zeroToOne * (destination[3] - source[3])), source[4] - + (zeroToOne * (destination[4] - source[4])), source[5] - + (zeroToOne * (destination[5] - source[5]))); + STATIC_TRANSFORM.setTransform(source[0] + zeroToOne * (destination[0] - source[0]), source[1] + zeroToOne + * (destination[1] - source[1]), source[2] + zeroToOne * (destination[2] - source[2]), source[3] + + zeroToOne * (destination[3] - source[3]), source[4] + zeroToOne * (destination[4] - source[4]), + source[5] + zeroToOne * (destination[5] - source[5])); target.setTransform(STATIC_TRANSFORM); } @@ -151,7 +153,7 @@ * @return a string representation of this activity's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("source=" + (source == null ? "null" : toString(source))); result.append(",destination=" + (destination == null ? "null" : toString(destination))); @@ -160,18 +162,18 @@ return result.toString(); } - + // here since 1.4 doesn't support Arrays.toString(double[] ...) // should be removed when we migrate to 1.5 - private String toString(double[] array) { - StringBuffer result = new StringBuffer('['); - for (int i=0; i= getMinDragStartDistance(); } @@ -144,18 +144,18 @@ return dragActivity; } - protected void startDragActivity(PInputEvent aEvent) { + protected void startDragActivity(final PInputEvent aEvent) { dragActivity = new PActivity(-1, PUtil.DEFAULT_ACTIVITY_STEP_RATE); dragActivity.setDelegate(new PActivity.PActivityDelegate() { - public void activityStarted(PActivity activity) { + public void activityStarted(final PActivity activity) { dragActivityFirstStep(dragEvent); } - public void activityStepped(PActivity activity) { + public void activityStepped(final PActivity activity) { dragActivityStep(dragEvent); } - public void activityFinished(PActivity activity) { + public void activityFinished(final PActivity activity) { dragActivityFinalStep(dragEvent); } }); @@ -163,7 +163,7 @@ aEvent.getCamera().getRoot().addActivity(dragActivity); } - protected void stopDragActivity(PInputEvent aEvent) { + protected void stopDragActivity(final PInputEvent aEvent) { dragActivity.terminate(); dragActivity = null; } @@ -172,7 +172,7 @@ * Override this method to get notified when the drag activity starts * stepping. */ - protected void dragActivityFirstStep(PInputEvent aEvent) { + protected void dragActivityFirstStep(final PInputEvent aEvent) { } /** @@ -182,14 +182,14 @@ * example PZoomEventHandler uses it for zooming and PPanEventHandler uses * it for auto panning. */ - protected void dragActivityStep(PInputEvent aEvent) { + protected void dragActivityStep(final PInputEvent aEvent) { } /** * Override this method to get notified when the drag activity stops * stepping. */ - protected void dragActivityFinalStep(PInputEvent aEvent) { + protected void dragActivityFinalStep(final PInputEvent aEvent) { } // **************************************************************** @@ -197,7 +197,7 @@ // override the appropriate drag method. // **************************************************************** - public void mousePressed(PInputEvent e) { + public void mousePressed(final PInputEvent e) { super.mousePressed(e); if (sequenceInitiatedButton == MouseEvent.NOBUTTON) { @@ -209,11 +209,11 @@ getMousePressedCanvasPoint().setLocation(e.getCanvasPosition()); if (!isDragging() && shouldStartDragInteraction(e)) { - startDrag(e); + startDrag(e); } } - public void mouseDragged(PInputEvent e) { + public void mouseDragged(final PInputEvent e) { super.mouseDragged(e); if (sequenceInitiatedButton != MouseEvent.NOBUTTON) { @@ -227,11 +227,12 @@ } } - public void mouseReleased(PInputEvent e) { + public void mouseReleased(final PInputEvent e) { super.mouseReleased(e); if (sequenceInitiatedButton == e.getButton()) { - if (isDragging()) + if (isDragging()) { endDrag(e); + } sequenceInitiatedButton = MouseEvent.NOBUTTON; } } @@ -249,14 +250,15 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("minDragStartDistance=" + minDragStartDistance); result.append(",mousePressedCanvasPoint=" + (mousePressedCanvasPoint == null ? "null" : mousePressedCanvasPoint.toString())); result.append(",sequenceInitiatedButton=" + sequenceInitiatedButton); - if (isDragging) + if (isDragging) { result.append(",dragging"); + } result.append(','); result.append(super.paramString()); diff --git a/core/src/main/java/edu/umd/cs/piccolo/event/PInputEvent.java b/core/src/main/java/edu/umd/cs/piccolo/event/PInputEvent.java index bc3b75b..6882285 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/event/PInputEvent.java +++ b/core/src/main/java/edu/umd/cs/piccolo/event/PInputEvent.java @@ -61,24 +61,24 @@ */ public class PInputEvent { - private InputEvent inputEvent; + private final InputEvent inputEvent; private PPickPath pickPath; - private PInputManager inputManager; + private final PInputManager inputManager; private boolean handled; - public PInputEvent(PInputManager inputManager, InputEvent event) { + public PInputEvent(final PInputManager inputManager, final InputEvent event) { super(); inputEvent = event; this.inputManager = inputManager; } - public void pushCursor(Cursor cursor) { - PComponent component = getTopCamera().getComponent(); + public void pushCursor(final Cursor cursor) { + final PComponent component = getTopCamera().getComponent(); component.pushCursor(cursor); } public void popCursor() { - PComponent component = getTopCamera().getComponent(); + final PComponent component = getTopCamera().getComponent(); component.popCursor(); } @@ -135,7 +135,7 @@ return pickPath; } - public void setPath(PPickPath path) { + public void setPath(final PPickPath path) { pickPath = path; } @@ -153,7 +153,7 @@ public int getKeyCode() { if (isKeyEvent()) { - KeyEvent e = (KeyEvent) inputEvent; + final KeyEvent e = (KeyEvent) inputEvent; return e.getKeyCode(); } throw new IllegalStateException("Can't get keycode from mouse event"); @@ -161,7 +161,7 @@ public char getKeyChar() { if (isKeyEvent()) { - KeyEvent e = (KeyEvent) inputEvent; + final KeyEvent e = (KeyEvent) inputEvent; return e.getKeyChar(); } throw new IllegalStateException("Can't get keychar from mouse event"); @@ -169,7 +169,7 @@ public int getKeyLocation() { if (isKeyEvent()) { - KeyEvent e = (KeyEvent) inputEvent; + final KeyEvent e = (KeyEvent) inputEvent; return e.getKeyLocation(); } throw new IllegalStateException("Can't get keylocation from mouse event"); @@ -177,7 +177,7 @@ public boolean isActionKey() { if (isKeyEvent()) { - KeyEvent e = (KeyEvent) inputEvent; + final KeyEvent e = (KeyEvent) inputEvent; return e.isActionKey(); } throw new IllegalStateException("Can't get isActionKey from mouse event"); @@ -276,7 +276,7 @@ * other event handlers that might conflict are expected to ignore events * that have already been handled. */ - public void setHandled(boolean handled) { + public void setHandled(final boolean handled) { this.handled = handled; } @@ -364,16 +364,16 @@ * coordinates. */ public PDimension getCanvasDelta() { - Point2D last = inputManager.getLastCanvasPosition(); - Point2D current = inputManager.getCurrentCanvasPosition(); + final Point2D last = inputManager.getLastCanvasPosition(); + final Point2D current = inputManager.getCurrentCanvasPosition(); return new PDimension(current.getX() - last.getX(), current.getY() - last.getY()); } /** * Return the mouse position relative to a given node on the pick path. */ - public Point2D getPositionRelativeTo(PNode nodeOnPath) { - Point2D r = getCanvasPosition(); + public Point2D getPositionRelativeTo(final PNode nodeOnPath) { + final Point2D r = getCanvasPosition(); return pickPath.canvasToLocal(r, nodeOnPath); } @@ -381,8 +381,8 @@ * Return the delta between the last and current mouse positions relative to * a given node on the pick path. */ - public PDimension getDeltaRelativeTo(PNode nodeOnPath) { - PDimension r = getCanvasDelta(); + public PDimension getDeltaRelativeTo(final PNode nodeOnPath) { + final PDimension r = getCanvasDelta(); return (PDimension) pickPath.canvasToLocal(r, nodeOnPath); } @@ -391,7 +391,7 @@ * bottom camera. */ public Point2D getPosition() { - Point2D r = getCanvasPosition(); + final Point2D r = getCanvasPosition(); pickPath.canvasToLocal(r, getCamera()); return getCamera().localToView(r); } @@ -401,16 +401,16 @@ * through the view transform of the bottom camera. */ public PDimension getDelta() { - PDimension r = getCanvasDelta(); + final PDimension r = getCanvasDelta(); pickPath.canvasToLocal(r, getCamera()); return (PDimension) getCamera().localToView(r); } - + /** * Returns a string representation of this object for debugging purposes. */ public String toString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append(super.toString().replaceAll(".*\\.", "")); result.append('['); diff --git a/core/src/main/java/edu/umd/cs/piccolo/event/PInputEventFilter.java b/core/src/main/java/edu/umd/cs/piccolo/event/PInputEventFilter.java index 3e2d96e..c86ead9 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/event/PInputEventFilter.java +++ b/core/src/main/java/edu/umd/cs/piccolo/event/PInputEventFilter.java @@ -53,9 +53,9 @@ */ public class PInputEventFilter { - public static final int ALL_MODIFIERS_MASK = InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK - | InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.ALT_GRAPH_MASK - | InputEvent.META_MASK; + public static final int ALL_MODIFIERS_MASK = InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK + | InputEvent.BUTTON3_MASK | InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.ALT_MASK + | InputEvent.ALT_GRAPH_MASK | InputEvent.META_MASK; private int andMask; private int orMask; @@ -83,17 +83,17 @@ acceptEverything(); } - public PInputEventFilter(int aAndMask) { + public PInputEventFilter(final int aAndMask) { this(); andMask = aAndMask; } - public PInputEventFilter(int aAndMask, int aNotMask) { + public PInputEventFilter(final int aAndMask, final int aNotMask) { this(aAndMask); notMask = aNotMask; } - public boolean acceptsEvent(PInputEvent aEvent, int type) { + public boolean acceptsEvent(final PInputEvent aEvent, final int type) { boolean aResult = false; int modifiers = 0; @@ -101,20 +101,24 @@ modifiers = aEvent.getModifiers(); } - if (aEvent.isHandled() && !acceptsAlreadyHandledEvents) + if (aEvent.isHandled() && !acceptsAlreadyHandledEvents) { return false; - - if (modifiers != 0) { - if ((modifiers & andMask) != andMask || (modifiers & notMask) != 0) - return false; - - if (orMask != ALL_MODIFIERS_MASK && (modifiers & orMask) == 0) - return false; } - - if (aEvent.isMouseEvent() && clickCount != -1 && clickCount != aEvent.getClickCount()) + + if (modifiers != 0) { + if ((modifiers & andMask) != andMask || (modifiers & notMask) != 0) { + return false; + } + + if (orMask != ALL_MODIFIERS_MASK && (modifiers & orMask) == 0) { + return false; + } + } + + if (aEvent.isMouseEvent() && clickCount != -1 && clickCount != aEvent.getClickCount()) { return false; - + } + switch (type) { case KeyEvent.KEY_PRESSED: aResult = getAcceptsKeyPressed(); @@ -168,7 +172,7 @@ default: throw new RuntimeException("PInputEvent with bad ID"); - } + } if (aResult && getMarksAcceptedEventsAsHandled()) { aEvent.setHandled(true); @@ -279,75 +283,75 @@ acceptsFocusEvents = false; } - public void setAcceptClickCount(short aClickCount) { + public void setAcceptClickCount(final short aClickCount) { clickCount = aClickCount; } - public void setAcceptsKeyPressed(boolean aBoolean) { + public void setAcceptsKeyPressed(final boolean aBoolean) { acceptsKeyPressed = aBoolean; } - public void setAcceptsKeyReleased(boolean aBoolean) { + public void setAcceptsKeyReleased(final boolean aBoolean) { acceptsKeyReleased = aBoolean; } - public void setAcceptsKeyTyped(boolean aBoolean) { + public void setAcceptsKeyTyped(final boolean aBoolean) { acceptsKeyTyped = aBoolean; } - public void setAcceptsMouseClicked(boolean aBoolean) { + public void setAcceptsMouseClicked(final boolean aBoolean) { acceptsMouseClicked = aBoolean; } - public void setAcceptsMouseDragged(boolean aBoolean) { + public void setAcceptsMouseDragged(final boolean aBoolean) { acceptsMouseDragged = aBoolean; } - public void setAcceptsMouseEntered(boolean aBoolean) { + public void setAcceptsMouseEntered(final boolean aBoolean) { acceptsMouseEntered = aBoolean; } - public void setAcceptsMouseExited(boolean aBoolean) { + public void setAcceptsMouseExited(final boolean aBoolean) { acceptsMouseExited = aBoolean; } - public void setAcceptsMouseMoved(boolean aBoolean) { + public void setAcceptsMouseMoved(final boolean aBoolean) { acceptsMouseMoved = aBoolean; } - public void setAcceptsMousePressed(boolean aBoolean) { + public void setAcceptsMousePressed(final boolean aBoolean) { acceptsMousePressed = aBoolean; } - public void setAcceptsMouseReleased(boolean aBoolean) { + public void setAcceptsMouseReleased(final boolean aBoolean) { acceptsMouseReleased = aBoolean; } - public void setAcceptsMouseWheelRotated(boolean aBoolean) { + public void setAcceptsMouseWheelRotated(final boolean aBoolean) { acceptsMouseWheelRotated = aBoolean; } - public void setAcceptsFocusEvents(boolean aBoolean) { + public void setAcceptsFocusEvents(final boolean aBoolean) { acceptsFocusEvents = aBoolean; } - public void setAndMask(int aAndMask) { + public void setAndMask(final int aAndMask) { andMask = aAndMask; } - public void setAcceptsAlreadyHandledEvents(boolean aBoolean) { + public void setAcceptsAlreadyHandledEvents(final boolean aBoolean) { acceptsAlreadyHandledEvents = aBoolean; } - public void setMarksAcceptedEventsAsHandled(boolean aBoolean) { + public void setMarksAcceptedEventsAsHandled(final boolean aBoolean) { marksAcceptedEventsAsHandled = aBoolean; } - public void setNotMask(int aNotMask) { + public void setNotMask(final int aNotMask) { notMask = aNotMask; } - public void setOrMask(int aOrMask) { + public void setOrMask(final int aOrMask) { orMask = aOrMask; } } diff --git a/core/src/main/java/edu/umd/cs/piccolo/event/PPanEventHandler.java b/core/src/main/java/edu/umd/cs/piccolo/event/PPanEventHandler.java index f83412f..3157f7d 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/event/PPanEventHandler.java +++ b/core/src/main/java/edu/umd/cs/piccolo/event/PPanEventHandler.java @@ -28,9 +28,9 @@ */ package edu.umd.cs.piccolo.event; -import java.awt.Rectangle; import java.awt.event.InputEvent; import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolo.util.PBounds; @@ -58,17 +58,17 @@ setAutopan(true); } - protected void drag(PInputEvent e) { + protected void drag(final PInputEvent e) { super.drag(e); pan(e); } - protected void pan(PInputEvent e) { - PCamera c = e.getCamera(); - Point2D l = e.getPosition(); + protected void pan(final PInputEvent e) { + final PCamera c = e.getCamera(); + final Point2D l = e.getPosition(); if (c.getViewBounds().contains(l)) { - PDimension d = e.getDelta(); + final PDimension d = e.getDelta(); c.translateView(d.getWidth(), d.getHeight()); } } @@ -77,7 +77,7 @@ // Auto Pan // **************************************************************** - public void setAutopan(boolean autopan) { + public void setAutopan(final boolean autopan) { this.autopan = autopan; } @@ -90,7 +90,7 @@ * * @param minAutopanSpeed */ - public void setMinAutopanSpeed(double minAutopanSpeed) { + public void setMinAutopanSpeed(final double minAutopanSpeed) { this.minAutopanSpeed = minAutopanSpeed; } @@ -99,10 +99,10 @@ * * @param maxAutopanSpeed */ - public void setMaxAutopanSpeed(double maxAutopanSpeed) { + public void setMaxAutopanSpeed(final double maxAutopanSpeed) { this.maxAutopanSpeed = maxAutopanSpeed; } - + /** * Returns the minAutoPan speed in pixels per second. * @@ -124,28 +124,29 @@ /** * Do auto panning even when the mouse is not moving. */ - protected void dragActivityStep(PInputEvent aEvent) { - if (!autopan) + protected void dragActivityStep(final PInputEvent aEvent) { + if (!autopan) { return; - - PCamera c = aEvent.getCamera(); - PBounds b = c.getBoundsReference(); - Point2D l = aEvent.getPositionRelativeTo(c); - int outcode = b.outcode(l); - PDimension delta = new PDimension(); - - if ((outcode & Rectangle.OUT_TOP) != 0) { - delta.height = validatePanningSpeed(-1.0 - (0.5 * Math.abs(l.getY() - b.getY()))); - } - else if ((outcode & Rectangle.OUT_BOTTOM) != 0) { - delta.height = validatePanningSpeed(1.0 + (0.5 * Math.abs(l.getY() - (b.getY() + b.getHeight())))); } - if ((outcode & Rectangle.OUT_RIGHT) != 0) { - delta.width = validatePanningSpeed(1.0 + (0.5 * Math.abs(l.getX() - (b.getX() + b.getWidth())))); + final PCamera c = aEvent.getCamera(); + final PBounds b = c.getBoundsReference(); + final Point2D l = aEvent.getPositionRelativeTo(c); + final int outcode = b.outcode(l); + final PDimension delta = new PDimension(); + + if ((outcode & Rectangle2D.OUT_TOP) != 0) { + delta.height = validatePanningSpeed(-1.0 - 0.5 * Math.abs(l.getY() - b.getY())); } - else if ((outcode & Rectangle.OUT_LEFT) != 0) { - delta.width = validatePanningSpeed(-1.0 - (0.5 * Math.abs(l.getX() - b.getX()))); + else if ((outcode & Rectangle2D.OUT_BOTTOM) != 0) { + delta.height = validatePanningSpeed(1.0 + 0.5 * Math.abs(l.getY() - (b.getY() + b.getHeight()))); + } + + if ((outcode & Rectangle2D.OUT_RIGHT) != 0) { + delta.width = validatePanningSpeed(1.0 + 0.5 * Math.abs(l.getX() - (b.getX() + b.getWidth()))); + } + else if ((outcode & Rectangle2D.OUT_LEFT) != 0) { + delta.width = validatePanningSpeed(-1.0 - 0.5 * Math.abs(l.getX() - b.getX())); } c.localToView(delta); @@ -156,17 +157,20 @@ } protected double validatePanningSpeed(double delta) { - double minDelta = minAutopanSpeed / (1000d / getDragActivity().getStepRate()); - double maxDelta = maxAutopanSpeed / (1000d / getDragActivity().getStepRate()); + final double minDelta = minAutopanSpeed / (1000d / getDragActivity().getStepRate()); + final double maxDelta = maxAutopanSpeed / (1000d / getDragActivity().getStepRate()); - boolean deltaNegative = delta < 0; + final boolean deltaNegative = delta < 0; delta = Math.abs(delta); - if (delta < minDelta) + if (delta < minDelta) { delta = minDelta; - if (delta > maxDelta) + } + if (delta > maxDelta) { delta = maxDelta; - if (deltaNegative) + } + if (deltaNegative) { delta = -delta; + } return delta; } @@ -183,12 +187,13 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("minAutopanSpeed=" + minAutopanSpeed); result.append(",maxAutopanSpeed=" + maxAutopanSpeed); - if (autopan) + if (autopan) { result.append(",autopan"); + } result.append(','); result.append(super.paramString()); diff --git a/core/src/main/java/edu/umd/cs/piccolo/event/PZoomEventHandler.java b/core/src/main/java/edu/umd/cs/piccolo/event/PZoomEventHandler.java index 41ffad7..967563e 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/event/PZoomEventHandler.java +++ b/core/src/main/java/edu/umd/cs/piccolo/event/PZoomEventHandler.java @@ -92,7 +92,7 @@ * * @param minScale the minimum scale, must not be negative. */ - public void setMinScale(double minScale) { + public void setMinScale(final double minScale) { this.minScale = minScale; } @@ -114,27 +114,27 @@ * * @param maxScale the maximum scale, must not be negative. */ - public void setMaxScale(double maxScale) { + public void setMaxScale(final double maxScale) { this.maxScale = maxScale; } - protected void dragActivityFirstStep(PInputEvent aEvent) { + protected void dragActivityFirstStep(final PInputEvent aEvent) { viewZoomPoint = aEvent.getPosition(); super.dragActivityFirstStep(aEvent); } - protected void dragActivityStep(PInputEvent aEvent) { - PCamera camera = aEvent.getCamera(); - double dx = aEvent.getCanvasPosition().getX() - getMousePressedCanvasPoint().getX(); - double scaleDelta = (1.0 + (0.001 * dx)); + protected void dragActivityStep(final PInputEvent aEvent) { + final PCamera camera = aEvent.getCamera(); + final double dx = aEvent.getCanvasPosition().getX() - getMousePressedCanvasPoint().getX(); + double scaleDelta = 1.0 + 0.001 * dx; - double currentScale = camera.getViewScale(); - double newScale = currentScale * scaleDelta; + final double currentScale = camera.getViewScale(); + final double newScale = currentScale * scaleDelta; if (newScale < minScale) { scaleDelta = minScale / currentScale; } - if ((maxScale > 0) && (newScale > maxScale)) { + if (maxScale > 0 && newScale > maxScale) { scaleDelta = maxScale / currentScale; } @@ -154,7 +154,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("minScale=" + minScale); result.append(",maxScale=" + maxScale); diff --git a/core/src/main/java/edu/umd/cs/piccolo/nodes/PImage.java b/core/src/main/java/edu/umd/cs/piccolo/nodes/PImage.java index 8b74d70..f740a5d 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/nodes/PImage.java +++ b/core/src/main/java/edu/umd/cs/piccolo/nodes/PImage.java @@ -62,7 +62,7 @@ * formats. */ private static final long serialVersionUID = 1L; - + /** * The property name that identifies a change of this node's image (see * {@link #getImage getImage}). Both old and new value will be set correctly @@ -80,7 +80,7 @@ /** * Construct a new PImage wrapping the given java.awt.Image. */ - public PImage(Image newImage) { + public PImage(final Image newImage) { this(); setImage(newImage); } @@ -89,7 +89,7 @@ * Construct a new PImage by loading the given fileName and wrapping the * resulting java.awt.Image. */ - public PImage(String fileName) { + public PImage(final String fileName) { this(Toolkit.getDefaultToolkit().getImage(fileName)); } @@ -99,10 +99,11 @@ * empty PImage; this behaviour is useful when fetching resources that may * be missing. */ - public PImage(java.net.URL url) { + public PImage(final java.net.URL url) { this(); - if (url != null) + if (url != null) { setImage(Toolkit.getDefaultToolkit().getImage(url)); + } } /** @@ -118,7 +119,7 @@ * Set the image that is wrapped by this PImage node. This method will also * load the image using a MediaTracker before returning. */ - public void setImage(String fileName) { + public void setImage(final String fileName) { setImage(Toolkit.getDefaultToolkit().getImage(fileName)); } @@ -126,14 +127,14 @@ * Set the image that is wrapped by this PImage node. This method will also * load the image using a MediaTracker before returning. */ - public void setImage(Image newImage) { - Image old = image; + public void setImage(final Image newImage) { + final Image old = image; if (newImage == null || newImage instanceof BufferedImage) { image = newImage; } else { // else make sure the image is loaded - ImageIcon imageLoader = new ImageIcon(newImage); + final ImageIcon imageLoader = new ImageIcon(newImage); switch (imageLoader.getImageLoadStatus()) { case MediaTracker.LOADING: System.err.println("media tracker still loading image after requested to wait until finished"); @@ -157,21 +158,21 @@ if (image != null) { setBounds(0, 0, getImage().getWidth(null), getImage().getHeight(null)); invalidatePaint(); - } + } firePropertyChange(PROPERTY_CODE_IMAGE, PROPERTY_IMAGE, old, image); } - protected void paint(PPaintContext paintContext) { + protected void paint(final PPaintContext paintContext) { if (getImage() == null) { return; } - - double iw = image.getWidth(null); - double ih = image.getHeight(null); - - PBounds b = getBoundsReference(); - Graphics2D g2 = paintContext.getGraphics(); + + final double iw = image.getWidth(null); + final double ih = image.getHeight(null); + + final PBounds b = getBoundsReference(); + final Graphics2D g2 = paintContext.getGraphics(); if (b.x != 0 || b.y != 0 || b.width != iw || b.height != ih) { g2.translate(b.x, b.y); @@ -194,14 +195,15 @@ * The java.awt.Image wrapped by this PImage is converted into a * BufferedImage when serialized. */ - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); - BufferedImage bufferedImage = toBufferedImage(image, false); - if (bufferedImage != null) + final BufferedImage bufferedImage = toBufferedImage(image, false); + if (bufferedImage != null) { ImageIO.write(bufferedImage, "png", out); + } } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); image = ImageIO.read(in); } @@ -215,7 +217,7 @@ * image it will not be copied and instead the original image will just be * returned. */ - public static BufferedImage toBufferedImage(Image image, boolean alwaysCreateCopy) { + public static BufferedImage toBufferedImage(final Image image, final boolean alwaysCreateCopy) { if (image == null) { return null; } @@ -225,17 +227,17 @@ } BufferedImage result; - + if (GraphicsEnvironment.isHeadless()) { result = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); - } - else { - GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment() - .getDefaultScreenDevice().getDefaultConfiguration(); - result = graphicsConfiguration.createCompatibleImage(image.getWidth(null), image.getHeight(null)); } - - Graphics2D g2 = result.createGraphics(); + else { + final GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice().getDefaultConfiguration(); + result = graphicsConfiguration.createCompatibleImage(image.getWidth(null), image.getHeight(null)); + } + + final Graphics2D g2 = result.createGraphics(); g2.drawImage(image, 0, 0, null); g2.dispose(); return result; @@ -250,7 +252,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("image=" + (image == null ? "null" : image.toString())); result.append(','); diff --git a/core/src/main/java/edu/umd/cs/piccolo/nodes/PPath.java b/core/src/main/java/edu/umd/cs/piccolo/nodes/PPath.java index e53a841..9a95afc 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/nodes/PPath.java +++ b/core/src/main/java/edu/umd/cs/piccolo/nodes/PPath.java @@ -75,7 +75,7 @@ * formats. */ private static final long serialVersionUID = 1L; - + /** * The property name that identifies a change of this node's stroke paint * (see {@link #getStrokePaint getStrokePaint}). Both old and new value will @@ -114,58 +114,57 @@ private transient boolean updatingBoundsFromPath; private Paint strokePaint; - public static PPath createRectangle(float x, float y, float width, float height) { + public static PPath createRectangle(final float x, final float y, final float width, final float height) { TEMP_RECTANGLE.setFrame(x, y, width, height); - PPath result = new PPath(TEMP_RECTANGLE); + final PPath result = new PPath(TEMP_RECTANGLE); result.setPaint(Color.white); return result; } - public static PPath createRoundRectangle(float x, float y, float width, float height, float arcWidth, - float arcHeight) { + public static PPath createRoundRectangle(final float x, final float y, final float width, final float height, + final float arcWidth, final float arcHeight) { TEMP_ROUNDRECTANGLE.setRoundRect(x, y, width, height, arcWidth, arcHeight); - PPath result = new PPath(TEMP_ROUNDRECTANGLE); + final PPath result = new PPath(TEMP_ROUNDRECTANGLE); result.setPaint(Color.white); return result; } - public static PPath createEllipse(float x, float y, float width, float height) { + public static PPath createEllipse(final float x, final float y, final float width, final float height) { TEMP_ELLIPSE.setFrame(x, y, width, height); - PPath result = new PPath(TEMP_ELLIPSE); + final PPath result = new PPath(TEMP_ELLIPSE); result.setPaint(Color.white); return result; } - public static PPath createLine(float x1, float y1, float x2, float y2) { - PPath result = new PPath(); + public static PPath createLine(final float x1, final float y1, final float x2, final float y2) { + final PPath result = new PPath(); result.moveTo(x1, y1); result.lineTo(x2, y2); result.setPaint(Color.white); return result; } - public static PPath createPolyline(Point2D[] points) { - PPath result = new PPath(); + public static PPath createPolyline(final Point2D[] points) { + final PPath result = new PPath(); result.setPathToPolyline(points); result.setPaint(Color.white); return result; } - public static PPath createPolyline(float[] xp, float[] yp) { - PPath result = new PPath(); + public static PPath createPolyline(final float[] xp, final float[] yp) { + final PPath result = new PPath(); result.setPathToPolyline(xp, yp); result.setPaint(Color.white); return result; } - public PPath() { strokePaint = DEFAULT_STROKE_PAINT; stroke = DEFAULT_STROKE; path = new GeneralPath(); } - public PPath(Shape aShape) { + public PPath(final Shape aShape) { this(aShape, DEFAULT_STROKE); } @@ -178,11 +177,12 @@ * calculated, so if you pass in a null stroke here you won't ever have to * pay that bounds calculation price if you don't need to. */ - public PPath(Shape aShape, Stroke aStroke) { + public PPath(final Shape aShape, final Stroke aStroke) { this(); stroke = aStroke; - if (aShape != null) + if (aShape != null) { append(aShape, false); + } } // **************************************************************** @@ -193,8 +193,8 @@ return strokePaint; } - public void setStrokePaint(Paint aPaint) { - Paint old = strokePaint; + public void setStrokePaint(final Paint aPaint) { + final Paint old = strokePaint; strokePaint = aPaint; invalidatePaint(); firePropertyChange(PROPERTY_CODE_STROKE_PAINT, PROPERTY_STROKE_PAINT, old, strokePaint); @@ -204,8 +204,8 @@ return stroke; } - public void setStroke(Stroke aStroke) { - Stroke old = stroke; + public void setStroke(final Stroke aStroke) { + final Stroke old = stroke; stroke = aStroke; updateBoundsFromPath(); invalidatePaint(); @@ -241,9 +241,9 @@ path.append(resizePath, false); } - Rectangle2D pathBounds = path.getBounds2D(); - Rectangle2D pathStrokeBounds = getPathBoundsWithStroke(); - double strokeOutset = Math.max(pathStrokeBounds.getWidth() - pathBounds.getWidth(), pathStrokeBounds + final Rectangle2D pathBounds = path.getBounds2D(); + final Rectangle2D pathStrokeBounds = getPathBoundsWithStroke(); + final double strokeOutset = Math.max(pathStrokeBounds.getWidth() - pathBounds.getWidth(), pathStrokeBounds .getHeight() - pathBounds.getHeight()); @@ -252,8 +252,8 @@ width -= strokeOutset; height -= strokeOutset; - double scaleX = (width == 0 || pathBounds.getWidth() == 0) ? 1 : width / pathBounds.getWidth(); - double scaleY = (height == 0 || pathBounds.getHeight() == 0) ? 1 : height / pathBounds.getHeight(); + final double scaleX = width == 0 || pathBounds.getWidth() == 0 ? 1 : width / pathBounds.getWidth(); + final double scaleY = height == 0 || pathBounds.getHeight() == 0 ? 1 : height / pathBounds.getHeight(); TEMP_TRANSFORM.setToIdentity(); TEMP_TRANSFORM.translate(x, y); @@ -263,7 +263,7 @@ path.transform(TEMP_TRANSFORM); } - public boolean intersects(Rectangle2D aBounds) { + public boolean intersects(final Rectangle2D aBounds) { if (super.intersects(aBounds)) { if (getPaint() != null && path.intersects(aBounds)) { return true; @@ -290,7 +290,7 @@ resetBounds(); } else { - Rectangle2D b = getPathBoundsWithStroke(); + final Rectangle2D b = getPathBoundsWithStroke(); setBounds(b.getX(), b.getY(), b.getWidth(), b.getHeight()); } updatingBoundsFromPath = false; @@ -300,9 +300,9 @@ // Painting // **************************************************************** - protected void paint(PPaintContext paintContext) { - Paint p = getPaint(); - Graphics2D g2 = paintContext.getGraphics(); + protected void paint(final PPaintContext paintContext) { + final Paint p = getPaint(); + final Graphics2D g2 = paintContext.getGraphics(); if (p != null) { g2.setPaint(p); @@ -325,57 +325,57 @@ return path; } - public void moveTo(float x, float y) { + public void moveTo(final float x, final float y) { path.moveTo(x, y); firePropertyChange(PROPERTY_CODE_PATH, PROPERTY_PATH, null, path); updateBoundsFromPath(); invalidatePaint(); } - public void lineTo(float x, float y) { + public void lineTo(final float x, final float y) { path.lineTo(x, y); firePropertyChange(PROPERTY_CODE_PATH, PROPERTY_PATH, null, path); updateBoundsFromPath(); invalidatePaint(); } - public void quadTo(float x1, float y1, float x2, float y2) { + public void quadTo(final float x1, final float y1, final float x2, final float y2) { path.quadTo(x1, y1, x2, y2); firePropertyChange(PROPERTY_CODE_PATH, PROPERTY_PATH, null, path); updateBoundsFromPath(); invalidatePaint(); } - public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) { + public void curveTo(final float x1, final float y1, final float x2, final float y2, final float x3, final float y3) { path.curveTo(x1, y1, x2, y2, x3, y3); firePropertyChange(PROPERTY_CODE_PATH, PROPERTY_PATH, null, path); updateBoundsFromPath(); invalidatePaint(); } - public void append(Shape aShape, boolean connect) { + public void append(final Shape aShape, final boolean connect) { path.append(aShape, connect); firePropertyChange(PROPERTY_CODE_PATH, PROPERTY_PATH, null, path); updateBoundsFromPath(); invalidatePaint(); } - public void setPathTo(Shape aShape) { + public void setPathTo(final Shape aShape) { path.reset(); append(aShape, false); } - public void setPathToRectangle(float x, float y, float width, float height) { + public void setPathToRectangle(final float x, final float y, final float width, final float height) { TEMP_RECTANGLE.setFrame(x, y, width, height); setPathTo(TEMP_RECTANGLE); } - public void setPathToEllipse(float x, float y, float width, float height) { + public void setPathToEllipse(final float x, final float y, final float width, final float height) { TEMP_ELLIPSE.setFrame(x, y, width, height); setPathTo(TEMP_ELLIPSE); } - public void setPathToPolyline(Point2D[] points) { + public void setPathToPolyline(final Point2D[] points) { path.reset(); path.moveTo((float) points[0].getX(), (float) points[0].getY()); for (int i = 1; i < points.length; i++) { @@ -386,7 +386,7 @@ invalidatePaint(); } - public void setPathToPolyline(float[] xp, float[] yp) { + public void setPathToPolyline(final float[] xp, final float[] yp) { path.reset(); path.moveTo(xp[0], yp[0]); for (int i = 1; i < xp.length; i++) { @@ -415,13 +415,13 @@ // Serialization // **************************************************************** - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); PUtil.writeStroke(stroke, out); PUtil.writePath(path, out); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); stroke = PUtil.readStroke(in); path = PUtil.readPath(in); @@ -440,7 +440,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("path=" + (path == null ? "null" : path.toString())); result.append(",stroke=" + (stroke == null ? "null" : stroke.toString())); diff --git a/core/src/main/java/edu/umd/cs/piccolo/nodes/PText.java b/core/src/main/java/edu/umd/cs/piccolo/nodes/PText.java index abcfcd9..7277e5c 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/nodes/PText.java +++ b/core/src/main/java/edu/umd/cs/piccolo/nodes/PText.java @@ -29,6 +29,7 @@ package edu.umd.cs.piccolo.nodes; import java.awt.Color; +import java.awt.Component; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; @@ -57,314 +58,307 @@ * formats. */ private static final long serialVersionUID = 1L; - - /** - * The property name that identifies a change of this node's text (see - * {@link #getText getText}). Both old and new value will be set in any - * property change event. - */ - public static final String PROPERTY_TEXT = "text"; - public static final int PROPERTY_CODE_TEXT = 1 << 19; - /** - * The property name that identifies a change of this node's font (see - * {@link #getFont getFont}). Both old and new value will be set in any - * property change event. - */ - public static final String PROPERTY_FONT = "font"; - public static final int PROPERTY_CODE_FONT = 1 << 20; + /** + * The property name that identifies a change of this node's text (see + * {@link #getText getText}). Both old and new value will be set in any + * property change event. + */ + public static final String PROPERTY_TEXT = "text"; + public static final int PROPERTY_CODE_TEXT = 1 << 19; - public static Font DEFAULT_FONT = new Font("Helvetica", Font.PLAIN, 12); - public static double DEFAULT_GREEK_THRESHOLD = 5.5; + /** + * The property name that identifies a change of this node's font (see + * {@link #getFont getFont}). Both old and new value will be set in any + * property change event. + */ + public static final String PROPERTY_FONT = "font"; + public static final int PROPERTY_CODE_FONT = 1 << 20; - private String text; - private Paint textPaint; - private Font font; - protected double greekThreshold = DEFAULT_GREEK_THRESHOLD; - private float justification = javax.swing.JLabel.LEFT_ALIGNMENT; - private boolean constrainHeightToTextHeight = true; - private boolean constrainWidthToTextWidth = true; - private transient TextLayout[] lines; + public static Font DEFAULT_FONT = new Font("Helvetica", Font.PLAIN, 12); + public static double DEFAULT_GREEK_THRESHOLD = 5.5; - public PText() { - super(); - setTextPaint(Color.BLACK); - text = ""; - } + private String text; + private Paint textPaint; + private Font font; + protected double greekThreshold = DEFAULT_GREEK_THRESHOLD; + private float justification = Component.LEFT_ALIGNMENT; + private boolean constrainHeightToTextHeight = true; + private boolean constrainWidthToTextWidth = true; + private transient TextLayout[] lines; - public PText(String aText) { - this(); - setText(aText); - } + public PText() { + super(); + setTextPaint(Color.BLACK); + text = ""; + } - /** - * Return the justificaiton of the text in the bounds. - * - * @return float - */ - public float getJustification() { - return justification; - } + public PText(final String aText) { + this(); + setText(aText); + } - /** - * Sets the justificaiton of the text in the bounds. - * - * @param just - */ - public void setJustification(float just) { - justification = just; - recomputeLayout(); - } + /** + * Return the justificaiton of the text in the bounds. + * + * @return float + */ + public float getJustification() { + return justification; + } - /** - * Get the paint used to paint this nodes text. - * - * @return Paint - */ - public Paint getTextPaint() { - return textPaint; - } + /** + * Sets the justificaiton of the text in the bounds. + * + * @param just + */ + public void setJustification(final float just) { + justification = just; + recomputeLayout(); + } - /** - * Set the paint used to paint this node's text background. - * - * @param textPaint - */ - public void setTextPaint(Paint textPaint) { - this.textPaint = textPaint; - invalidatePaint(); - } + /** + * Get the paint used to paint this nodes text. + * + * @return Paint + */ + public Paint getTextPaint() { + return textPaint; + } - public boolean isConstrainWidthToTextWidth() { - return constrainWidthToTextWidth; - } + /** + * Set the paint used to paint this node's text background. + * + * @param textPaint + */ + public void setTextPaint(final Paint textPaint) { + this.textPaint = textPaint; + invalidatePaint(); + } - /** - * Controls whether this node changes its width to fit the width of its - * text. If flag is true it does; if flag is false it doesn't - */ - public void setConstrainWidthToTextWidth(boolean constrainWidthToTextWidth) { - this.constrainWidthToTextWidth = constrainWidthToTextWidth; - recomputeLayout(); - } + public boolean isConstrainWidthToTextWidth() { + return constrainWidthToTextWidth; + } - public boolean isConstrainHeightToTextHeight() { - return constrainHeightToTextHeight; - } + /** + * Controls whether this node changes its width to fit the width of its + * text. If flag is true it does; if flag is false it doesn't + */ + public void setConstrainWidthToTextWidth(final boolean constrainWidthToTextWidth) { + this.constrainWidthToTextWidth = constrainWidthToTextWidth; + recomputeLayout(); + } - /** - * Controls whether this node changes its height to fit the height of its - * text. If flag is true it does; if flag is false it doesn't - */ - public void setConstrainHeightToTextHeight( - boolean constrainHeightToTextHeight) { - this.constrainHeightToTextHeight = constrainHeightToTextHeight; - recomputeLayout(); - } + public boolean isConstrainHeightToTextHeight() { + return constrainHeightToTextHeight; + } - /** - * Returns the current greek threshold. When the screen font size will be - * below this threshold the text is rendered as 'greek' instead of drawing - * the text glyphs. - */ - public double getGreekThreshold() { - return greekThreshold; - } + /** + * Controls whether this node changes its height to fit the height of its + * text. If flag is true it does; if flag is false it doesn't + */ + public void setConstrainHeightToTextHeight(final boolean constrainHeightToTextHeight) { + this.constrainHeightToTextHeight = constrainHeightToTextHeight; + recomputeLayout(); + } - /** - * Sets the current greek threshold. When the screen font size will be below - * this threshold the text is rendered as 'greek' instead of drawing the - * text glyphs. - * - * @param threshold - * minimum screen font size. - */ - public void setGreekThreshold(double threshold) { - greekThreshold = threshold; - invalidatePaint(); - } + /** + * Returns the current greek threshold. When the screen font size will be + * below this threshold the text is rendered as 'greek' instead of drawing + * the text glyphs. + */ + public double getGreekThreshold() { + return greekThreshold; + } - public String getText() { - return text; - } + /** + * Sets the current greek threshold. When the screen font size will be below + * this threshold the text is rendered as 'greek' instead of drawing the + * text glyphs. + * + * @param threshold minimum screen font size. + */ + public void setGreekThreshold(final double threshold) { + greekThreshold = threshold; + invalidatePaint(); + } - /** - * Set the text for this node. The text will be broken up into multiple - * lines based on the size of the text and the bounds width of this node. - */ - public void setText(String aText) { - String old = text; - text = (aText == null) ? "" : aText; - lines = null; - recomputeLayout(); - invalidatePaint(); - firePropertyChange(PROPERTY_CODE_TEXT, PROPERTY_TEXT, old, text); - } + public String getText() { + return text; + } - /** - * Returns the font of this PText. - * - * @return the font of this PText. - */ - public Font getFont() { - if (font == null) { - font = DEFAULT_FONT; - } - return font; - } + /** + * Set the text for this node. The text will be broken up into multiple + * lines based on the size of the text and the bounds width of this node. + */ + public void setText(final String aText) { + final String old = text; + text = aText == null ? "" : aText; + lines = null; + recomputeLayout(); + invalidatePaint(); + firePropertyChange(PROPERTY_CODE_TEXT, PROPERTY_TEXT, old, text); + } - /** - * Set the font of this PText. Note that in Piccolo if you want to change - * the size of a text object it's often a better idea to scale the PText - * node instead of changing the font size to get that same effect. Using - * very large font sizes can slow performance. - */ - public void setFont(Font aFont) { - Font old = font; - font = aFont; - lines = null; - recomputeLayout(); - invalidatePaint(); - firePropertyChange(PROPERTY_CODE_FONT, PROPERTY_FONT, old, font); - } + /** + * Returns the font of this PText. + * + * @return the font of this PText. + */ + public Font getFont() { + if (font == null) { + font = DEFAULT_FONT; + } + return font; + } - private static final TextLayout[] EMPTY_TEXT_LAYOUT_ARRAY = new TextLayout[0]; + /** + * Set the font of this PText. Note that in Piccolo if you want to change + * the size of a text object it's often a better idea to scale the PText + * node instead of changing the font size to get that same effect. Using + * very large font sizes can slow performance. + */ + public void setFont(final Font aFont) { + final Font old = font; + font = aFont; + lines = null; + recomputeLayout(); + invalidatePaint(); + firePropertyChange(PROPERTY_CODE_FONT, PROPERTY_FONT, old, font); + } - /** - * Compute the bounds of the text wrapped by this node. The text layout is - * wrapped based on the bounds of this node. - */ - public void recomputeLayout() { - ArrayList linesList = new ArrayList(); - double textWidth = 0; - double textHeight = 0; + private static final TextLayout[] EMPTY_TEXT_LAYOUT_ARRAY = new TextLayout[0]; - if (text != null && text.length() > 0) { - AttributedString atString = new AttributedString(text); - atString.addAttribute(TextAttribute.FONT, getFont()); - AttributedCharacterIterator itr = atString.getIterator(); - LineBreakMeasurer measurer = new LineBreakMeasurer(itr, - PPaintContext.RENDER_QUALITY_HIGH_FRC); - float availableWidth = constrainWidthToTextWidth ? Float.MAX_VALUE - : (float) getWidth(); + /** + * Compute the bounds of the text wrapped by this node. The text layout is + * wrapped based on the bounds of this node. + */ + public void recomputeLayout() { + final ArrayList linesList = new ArrayList(); + double textWidth = 0; + double textHeight = 0; - int nextLineBreakOffset = text.indexOf('\n'); - if (nextLineBreakOffset == -1) { - nextLineBreakOffset = Integer.MAX_VALUE; - } else { - nextLineBreakOffset++; - } + if (text != null && text.length() > 0) { + final AttributedString atString = new AttributedString(text); + atString.addAttribute(TextAttribute.FONT, getFont()); + final AttributedCharacterIterator itr = atString.getIterator(); + final LineBreakMeasurer measurer = new LineBreakMeasurer(itr, PPaintContext.RENDER_QUALITY_HIGH_FRC); + final float availableWidth = constrainWidthToTextWidth ? Float.MAX_VALUE : (float) getWidth(); - while (measurer.getPosition() < itr.getEndIndex()) { - TextLayout aTextLayout = computeNextLayout(measurer, - availableWidth, nextLineBreakOffset); + int nextLineBreakOffset = text.indexOf('\n'); + if (nextLineBreakOffset == -1) { + nextLineBreakOffset = Integer.MAX_VALUE; + } + else { + nextLineBreakOffset++; + } - if (nextLineBreakOffset == measurer.getPosition()) { - nextLineBreakOffset = text.indexOf('\n', measurer - .getPosition()); - if (nextLineBreakOffset == -1) { - nextLineBreakOffset = Integer.MAX_VALUE; - } else { - nextLineBreakOffset++; - } - } + while (measurer.getPosition() < itr.getEndIndex()) { + final TextLayout aTextLayout = computeNextLayout(measurer, availableWidth, nextLineBreakOffset); - linesList.add(aTextLayout); - textHeight += aTextLayout.getAscent(); - textHeight += aTextLayout.getDescent() - + aTextLayout.getLeading(); - textWidth = Math.max(textWidth, aTextLayout.getAdvance()); - } - } + if (nextLineBreakOffset == measurer.getPosition()) { + nextLineBreakOffset = text.indexOf('\n', measurer.getPosition()); + if (nextLineBreakOffset == -1) { + nextLineBreakOffset = Integer.MAX_VALUE; + } + else { + nextLineBreakOffset++; + } + } - lines = (TextLayout[]) linesList.toArray(EMPTY_TEXT_LAYOUT_ARRAY); + linesList.add(aTextLayout); + textHeight += aTextLayout.getAscent(); + textHeight += aTextLayout.getDescent() + aTextLayout.getLeading(); + textWidth = Math.max(textWidth, aTextLayout.getAdvance()); + } + } - if (constrainWidthToTextWidth || constrainHeightToTextHeight) { - double newWidth = getWidth(); - double newHeight = getHeight(); + lines = (TextLayout[]) linesList.toArray(EMPTY_TEXT_LAYOUT_ARRAY); - if (constrainWidthToTextWidth) { - newWidth = textWidth; - } + if (constrainWidthToTextWidth || constrainHeightToTextHeight) { + double newWidth = getWidth(); + double newHeight = getHeight(); - if (constrainHeightToTextHeight) { - newHeight = textHeight; - } + if (constrainWidthToTextWidth) { + newWidth = textWidth; + } - super.setBounds(getX(), getY(), newWidth, newHeight); - } - } + if (constrainHeightToTextHeight) { + newHeight = textHeight; + } - // provided in case someone needs to override the way that lines are - // wrapped. - protected TextLayout computeNextLayout(LineBreakMeasurer measurer, - float availibleWidth, int nextLineBreakOffset) { - return measurer.nextLayout(availibleWidth, nextLineBreakOffset, false); - } + super.setBounds(getX(), getY(), newWidth, newHeight); + } + } - protected void paint(PPaintContext paintContext) { - super.paint(paintContext); + // provided in case someone needs to override the way that lines are + // wrapped. + protected TextLayout computeNextLayout(final LineBreakMeasurer measurer, final float availibleWidth, + final int nextLineBreakOffset) { + return measurer.nextLayout(availibleWidth, nextLineBreakOffset, false); + } - float screenFontSize = getFont().getSize() - * (float) paintContext.getScale(); - if (textPaint == null || screenFontSize <= greekThreshold) - return; + protected void paint(final PPaintContext paintContext) { + super.paint(paintContext); - float x = (float) getX(); - float y = (float) getY(); - float bottomY = (float) getHeight() + y; + final float screenFontSize = getFont().getSize() * (float) paintContext.getScale(); + if (textPaint == null || screenFontSize <= greekThreshold) { + return; + } - Graphics2D g2 = paintContext.getGraphics(); + final float x = (float) getX(); + float y = (float) getY(); + final float bottomY = (float) getHeight() + y; - if (lines == null) { - recomputeLayout(); - repaint(); - return; - } + final Graphics2D g2 = paintContext.getGraphics(); - g2.setPaint(textPaint); + if (lines == null) { + recomputeLayout(); + repaint(); + return; + } - for (int i = 0; i < lines.length; i++) { - TextLayout tl = lines[i]; - y += tl.getAscent(); + g2.setPaint(textPaint); - if (bottomY < y) { - return; - } + for (int i = 0; i < lines.length; i++) { + final TextLayout tl = lines[i]; + y += tl.getAscent(); - float offset = (float) (getWidth() - tl.getAdvance()) - * justification; - tl.draw(g2, x + offset, y); + if (bottomY < y) { + return; + } - y += tl.getDescent() + tl.getLeading(); - } - } + final float offset = (float) (getWidth() - tl.getAdvance()) * justification; + tl.draw(g2, x + offset, y); - protected void internalUpdateBounds(double x, double y, double width, - double height) { - recomputeLayout(); - } + y += tl.getDescent() + tl.getLeading(); + } + } - // **************************************************************** - // Debugging - methods for debugging - // **************************************************************** + protected void internalUpdateBounds(final double x, final double y, final double width, final double height) { + recomputeLayout(); + } - /** - * Returns a string representing the state of this node. This method is - * intended to be used only for debugging purposes, and the content and - * format of the returned string may vary between implementations. The - * returned string may be empty but may not be null. - * - * @return a string representation of this node's state - */ - protected String paramString() { - StringBuffer result = new StringBuffer(); + // **************************************************************** + // Debugging - methods for debugging + // **************************************************************** - result.append("text=" + (text == null ? "null" : text)); - result.append(",font=" + (font == null ? "null" : font.toString())); - result.append(','); - result.append(super.paramString()); + /** + * Returns a string representing the state of this node. This method is + * intended to be used only for debugging purposes, and the content and + * format of the returned string may vary between implementations. The + * returned string may be empty but may not be null. + * + * @return a string representation of this node's state + */ + protected String paramString() { + final StringBuffer result = new StringBuffer(); - return result.toString(); - } + result.append("text=" + (text == null ? "null" : text)); + result.append(",font=" + (font == null ? "null" : font.toString())); + result.append(','); + result.append(super.paramString()); + + return result.toString(); + } } diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransform.java b/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransform.java index b8ab86d..e61291b 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransform.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransform.java @@ -48,7 +48,7 @@ * formats. */ private static final long serialVersionUID = 1L; - + private static double[] PTS1 = new double[8]; private static double[] PTS2 = new double[8]; @@ -56,27 +56,29 @@ super(); } - public PAffineTransform(double[] flatmatrix) { + public PAffineTransform(final double[] flatmatrix) { super(flatmatrix); } - public PAffineTransform(float[] flatmatrix) { + public PAffineTransform(final float[] flatmatrix) { super(flatmatrix); } - public PAffineTransform(double m00, double m10, double m01, double m11, double m02, double m12) { + public PAffineTransform(final double m00, final double m10, final double m01, final double m11, final double m02, + final double m12) { super(m00, m10, m01, m11, m02, m12); } - public PAffineTransform(float m00, float m10, float m01, float m11, float m02, float m12) { + public PAffineTransform(final float m00, final float m10, final float m01, final float m11, final float m02, + final float m12) { super(m00, m10, m01, m11, m02, m12); } - public PAffineTransform(AffineTransform tx) { + public PAffineTransform(final AffineTransform tx) { super(tx); } - public void scaleAboutPoint(double scale, double x, double y) { + public void scaleAboutPoint(final double scale, final double x, final double y) { translate(x, y); scale(scale, scale); translate(-x, -y); @@ -91,7 +93,7 @@ return Point2D.distance(PTS2[0], PTS2[1], PTS2[2], PTS2[3]); } - public void setScale(double scale) { + public void setScale(final double scale) { if (scale == 0) { throw new PAffineTransformException("Can't set scale to 0", this); } @@ -99,7 +101,7 @@ scaleAboutPoint(scale / getScale(), 0, 0); } - public void setOffset(double tx, double ty) { + public void setOffset(final double tx, final double ty) { setTransform(getScaleX(), getShearY(), getShearX(), getScaleY(), tx, ty); } @@ -117,8 +119,8 @@ transform(PTS1, 0, PTS2, 0, 2); - double dy = Math.abs(PTS2[3] - PTS2[1]); - double l = Point2D.distance(PTS2[0], PTS2[1], PTS2[2], PTS2[3]); + final double dy = Math.abs(PTS2[3] - PTS2[1]); + final double l = Point2D.distance(PTS2[0], PTS2[1], PTS2[2], PTS2[3]); double rotation = Math.asin(dy / l); // correct for quadrant @@ -142,11 +144,11 @@ /** * Set rotation in radians. */ - public void setRotation(double theta) { + public void setRotation(final double theta) { rotate(theta - getRotation()); } - public Dimension2D transform(Dimension2D dimSrc, Dimension2D dimDst) { + public Dimension2D transform(final Dimension2D dimSrc, Dimension2D dimDst) { if (dimDst == null) { dimDst = (Dimension2D) dimSrc.clone(); } @@ -158,27 +160,27 @@ return dimDst; } - public Point2D inverseTransform(Point2D ptSrc, Point2D ptDst) { + public Point2D inverseTransform(final Point2D ptSrc, final Point2D ptDst) { try { return super.inverseTransform(ptSrc, ptDst); } - catch (NoninvertibleTransformException e) { + catch (final NoninvertibleTransformException e) { throw new PAffineTransformException("Could not invert Transform", e, this); } } - public Dimension2D inverseTransform(Dimension2D dimSrc, Dimension2D dimDst) { + public Dimension2D inverseTransform(final Dimension2D dimSrc, Dimension2D dimDst) { if (dimDst == null) { dimDst = (Dimension2D) dimSrc.clone(); } - double width = dimSrc.getWidth(); - double height = dimSrc.getHeight(); - double m00 = getScaleX(); - double m11 = getScaleY(); - double m01 = getShearX(); - double m10 = getShearY(); - double det = m00 * m11 - m01 * m10; + final double width = dimSrc.getWidth(); + final double height = dimSrc.getHeight(); + final double m00 = getScaleX(); + final double m11 = getScaleY(); + final double m01 = getShearX(); + final double m10 = getShearY(); + final double det = m00 * m11 - m01 * m10; if (Math.abs(det) > Double.MIN_VALUE) { dimDst.setSize((width * m11 - height * m01) / det, (height * m00 - width * m10) / det); @@ -190,7 +192,7 @@ return dimDst; } - public Rectangle2D transform(Rectangle2D rectSrc, Rectangle2D rectDst) { + public Rectangle2D transform(final Rectangle2D rectSrc, Rectangle2D rectDst) { if (rectDst == null) { rectDst = (Rectangle2D) rectSrc.clone(); } @@ -207,8 +209,9 @@ switch (getType()) { case AffineTransform.TYPE_IDENTITY: - if (rectSrc != rectDst) + if (rectSrc != rectDst) { rectDst.setRect(rectSrc); + } break; case AffineTransform.TYPE_TRANSLATION: @@ -225,12 +228,12 @@ case AffineTransform.TYPE_TRANSLATION | AffineTransform.TYPE_UNIFORM_SCALE: scale = getScaleX(); - rectDst.setRect((rectSrc.getX() * scale) + getTranslateX(), (rectSrc.getY() * scale) + getTranslateY(), + rectDst.setRect(rectSrc.getX() * scale + getTranslateX(), rectSrc.getY() * scale + getTranslateY(), rectSrc.getWidth() * scale, rectSrc.getHeight() * scale); break; default: - double[] pts = rectToArray(rectSrc); + final double[] pts = rectToArray(rectSrc); transform(pts, 0, pts, 0, 4); rectFromArray(rectDst, pts); break; @@ -239,7 +242,7 @@ return rectDst; } - public Rectangle2D inverseTransform(Rectangle2D rectSrc, Rectangle2D rectDst) { + public Rectangle2D inverseTransform(final Rectangle2D rectSrc, Rectangle2D rectDst) { if (rectDst == null) { rectDst = (Rectangle2D) rectSrc.clone(); } @@ -256,8 +259,9 @@ switch (getType()) { case AffineTransform.TYPE_IDENTITY: - if (rectSrc != rectDst) + if (rectSrc != rectDst) { rectDst.setRect(rectSrc); + } break; case AffineTransform.TYPE_TRANSLATION: @@ -270,9 +274,10 @@ if (scale == 0) { throw new PAffineTransformException("Could not invertTransform rectangle", this); } - + rectDst.setRect(rectSrc.getX() / scale, rectSrc.getY() / scale, rectSrc.getWidth() / scale, rectSrc - .getHeight() / scale); + .getHeight() + / scale); break; case AffineTransform.TYPE_TRANSLATION | AffineTransform.TYPE_UNIFORM_SCALE: @@ -285,11 +290,11 @@ break; default: - double[] pts = rectToArray(rectSrc); + final double[] pts = rectToArray(rectSrc); try { inverseTransform(pts, 0, pts, 0, 4); } - catch (NoninvertibleTransformException e) { + catch (final NoninvertibleTransformException e) { throw new PAffineTransformException("Could not invert transform", e, this); } rectFromArray(rectDst, pts); @@ -299,7 +304,7 @@ return rectDst; } - private static double[] rectToArray(Rectangle2D aRectangle) { + private static double[] rectToArray(final Rectangle2D aRectangle) { PTS1[0] = aRectangle.getX(); PTS1[1] = aRectangle.getY(); PTS1[2] = PTS1[0] + aRectangle.getWidth(); @@ -311,7 +316,7 @@ return PTS1; } - private static void rectFromArray(Rectangle2D aRectangle, double[] pts) { + private static void rectFromArray(final Rectangle2D aRectangle, final double[] pts) { double minX = pts[0]; double minY = pts[1]; double maxX = pts[0]; @@ -322,7 +327,7 @@ for (int i = 1; i < 4; i++) { x = pts[2 * i]; - y = pts[(2 * i) + 1]; + y = pts[2 * i + 1]; if (x < minX) { minX = x; @@ -338,5 +343,5 @@ } } aRectangle.setRect(minX, minY, maxX - minX, maxY - minY); - } + } } diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransformException.java b/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransformException.java index 5f9e02d..4b489c5 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransformException.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PAffineTransformException.java @@ -6,28 +6,29 @@ * formats. */ private static final long serialVersionUID = 1L; - + private final PAffineTransform errantTransform; - public PAffineTransformException(PAffineTransform errantTransform) { + public PAffineTransformException(final PAffineTransform errantTransform) { this.errantTransform = errantTransform; } - public PAffineTransformException(String message, PAffineTransform errantTransform) { + public PAffineTransformException(final String message, final PAffineTransform errantTransform) { super(message); this.errantTransform = errantTransform; } - public PAffineTransformException(Throwable throwable, PAffineTransform errantTransform) { + public PAffineTransformException(final Throwable throwable, final PAffineTransform errantTransform) { super(throwable); this.errantTransform = errantTransform; } - public PAffineTransformException(String message, Throwable throwable, PAffineTransform errantTransform) { + public PAffineTransformException(final String message, final Throwable throwable, + final PAffineTransform errantTransform) { super(message, throwable); this.errantTransform = errantTransform; } - + public PAffineTransform getErrantTransform() { return errantTransform; } diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PBounds.java b/core/src/main/java/edu/umd/cs/piccolo/util/PBounds.java index b14634e..1e411c1 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PBounds.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PBounds.java @@ -56,29 +56,29 @@ * formats. */ private static final long serialVersionUID = 1L; - + private boolean isEmpty = true; public PBounds() { super(); } - public PBounds(PBounds aBounds) { + public PBounds(final PBounds aBounds) { this(aBounds.x, aBounds.y, aBounds.width, aBounds.height); isEmpty = aBounds.isEmpty(); } - public PBounds(Rectangle2D aBounds) { + public PBounds(final Rectangle2D aBounds) { this(aBounds.getX(), aBounds.getY(), aBounds.getWidth(), aBounds.getHeight()); isEmpty = aBounds.isEmpty(); } - public PBounds(Point2D aCenterPoint, double insetX, double insetY) { + public PBounds(final Point2D aCenterPoint, final double insetX, final double insetY) { this(aCenterPoint.getX(), aCenterPoint.getY(), 0, 0); inset(insetX, insetY); } - public PBounds(double x, double y, double width, double height) { + public PBounds(final double x, final double y, final double width, final double height) { super(x, y, width, height); isEmpty = false; } @@ -105,12 +105,12 @@ return this; } - public void setRect(Rectangle2D r) { + public void setRect(final Rectangle2D r) { super.setRect(r); isEmpty = false; } - public void setRect(PBounds b) { + public void setRect(final PBounds b) { isEmpty = b.isEmpty; x = b.x; y = b.y; @@ -118,15 +118,15 @@ height = b.height; } - public void setRect(double x, double y, double w, double h) { + public void setRect(final double x, final double y, final double w, final double h) { this.x = x; this.y = y; - this.width = w; - this.height = h; + width = w; + height = h; isEmpty = false; } - public void add(double newx, double newy) { + public void add(final double newx, final double newy) { if (isEmpty) { setRect(newx, newy, 0, 0); isEmpty = false; @@ -136,7 +136,7 @@ } } - public void add(Rectangle2D r) { + public void add(final Rectangle2D r) { if (isEmpty) { setRect(r); } @@ -146,7 +146,7 @@ } // optimized add when adding two PBounds together. - public void add(PBounds r) { + public void add(final PBounds r) { if (r.isEmpty) { return; } @@ -158,10 +158,10 @@ isEmpty = false; } else { - double x1 = (x <= r.x) ? x : r.x; - double y1 = (y <= r.y) ? y : r.y; - double x2 = ((x + width) >= (r.x + r.width)) ? (x + width) : (r.x + r.width); - double y2 = ((y + height) >= (r.y + r.height)) ? (y + height) : (r.y + r.height); + final double x1 = x <= r.x ? x : r.x; + final double y1 = y <= r.y ? y : r.y; + final double x2 = x + width >= r.x + r.width ? x + width : r.x + r.width; + final double y2 = y + height >= r.y + r.height ? y + height : r.y + r.height; x = x1; y = y1; @@ -175,7 +175,7 @@ return new Point2D.Double(x, y); } - public PBounds setOrigin(double x, double y) { + public PBounds setOrigin(final double x, final double y) { this.x = x; this.y = y; isEmpty = false; @@ -186,7 +186,7 @@ return new PDimension(width, height); } - public void setSize(double width, double height) { + public void setSize(final double width, final double height) { setRect(x, y, width, height); } @@ -194,7 +194,7 @@ return new Point2D.Double(getCenterX(), getCenterY()); } - public PBounds moveBy(double dx, double dy) { + public PBounds moveBy(final double dx, final double dy) { setOrigin(x + dx, y + dy); return this; } @@ -206,35 +206,35 @@ height = Math.ceil(height); } - public PBounds inset(double dx, double dy) { - setRect(x + dx, y + dy, width - (dx * 2), height - (dy * 2)); + public PBounds inset(final double dx, final double dy) { + setRect(x + dx, y + dy, width - dx * 2, height - dy * 2); return this; } - public PDimension deltaRequiredToCenter(Rectangle2D b) { - PDimension result = new PDimension(); - double xDelta = getCenterX() - b.getCenterX(); - double yDelta = getCenterY() - b.getCenterY(); + public PDimension deltaRequiredToCenter(final Rectangle2D b) { + final PDimension result = new PDimension(); + final double xDelta = getCenterX() - b.getCenterX(); + final double yDelta = getCenterY() - b.getCenterY(); result.setSize(xDelta, yDelta); return result; } - public PDimension deltaRequiredToContain(Rectangle2D b) { - PDimension result = new PDimension(); + public PDimension deltaRequiredToContain(final Rectangle2D b) { + final PDimension result = new PDimension(); if (!contains(b)) { - double bMaxX = b.getMaxX(); - double bMinX = b.getMinX(); - double bMaxY = b.getMaxY(); - double bMinY = b.getMinY(); - double maxX = getMaxX(); - double minX = getMinX(); - double maxY = getMaxY(); - double minY = getMinY(); + final double bMaxX = b.getMaxX(); + final double bMinX = b.getMinX(); + final double bMaxY = b.getMaxY(); + final double bMinY = b.getMinY(); + final double maxX = getMaxX(); + final double minX = getMinX(); + final double maxY = getMaxY(); + final double minY = getMinY(); - if ((bMaxX > maxX) ^ (bMinX < minX)) { - double difMaxX = bMaxX - maxX; - double difMinX = bMinX - minX; + if (bMaxX > maxX ^ bMinX < minX) { + final double difMaxX = bMaxX - maxX; + final double difMinX = bMinX - minX; if (Math.abs(difMaxX) < Math.abs(difMinX)) { result.width = difMaxX; } @@ -243,9 +243,9 @@ } } - if ((bMaxY > maxY) ^ (bMinY < minY)) { - double difMaxY = bMaxY - maxY; - double difMinY = bMinY - minY; + if (bMaxY > maxY ^ bMinY < minY) { + final double difMaxY = bMaxY - maxY; + final double difMinY = bMinY - minY; if (Math.abs(difMaxY) < Math.abs(difMinY)) { result.height = difMaxY; } @@ -258,7 +258,7 @@ return result; } - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeDouble(x); out.writeDouble(y); @@ -266,7 +266,7 @@ out.writeDouble(height); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); x = in.readDouble(); y = in.readDouble(); @@ -275,7 +275,7 @@ } public String toString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append(getClass().getName().replaceAll(".*\\.", "")); result.append('['); diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PDebug.java b/core/src/main/java/edu/umd/cs/piccolo/util/PDebug.java index 3cce923..1e56554 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PDebug.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PDebug.java @@ -66,7 +66,7 @@ } public static Color getDebugPaintColor() { - int color = 100 + (debugPaintColor++ % 10) * 10; + final int color = 100 + debugPaintColor++ % 10 * 10; return new Color(color, color, color, 150); } @@ -97,26 +97,26 @@ startProcessingOutputTime = System.currentTimeMillis(); } - public static void endProcessingOutput(Graphics g) { - processOutputTime += (System.currentTimeMillis() - startProcessingOutputTime); + public static void endProcessingOutput(final Graphics g) { + processOutputTime += System.currentTimeMillis() - startProcessingOutputTime; framesProcessed++; if (framesProcessed % printResultsFrameRate == 0) { - if (PDebug.debugPrintFrameRate ) { + if (PDebug.debugPrintFrameRate) { System.out.println("Process output frame rate: " + getOutputFPS() + " fps"); System.out.println("Process input frame rate: " + getInputFPS() + " fps"); System.out.println("Total frame rate: " + getTotalFPS() + " fps"); System.out.println(); resetFPSTiming(); } - - if (PDebug.debugPrintUsedMemory) { - System.out.println("Approximate used memory: " + getApproximateUsedMemory() / 1024 + " k"); + + if (PDebug.debugPrintUsedMemory) { + System.out.println("Approximate used memory: " + getApproximateUsedMemory() / 1024 + " k"); } } if (PDebug.debugRegionManagement) { - Graphics2D g2 = (Graphics2D) g; + final Graphics2D g2 = (Graphics2D) g; g.setColor(PDebug.getDebugPaintColor()); g2.fill(g.getClipBounds().getBounds2D()); } @@ -129,7 +129,7 @@ } public static void endProcessingInput() { - processInputTime += (System.currentTimeMillis() - startProcessingInputTime); + processInputTime += System.currentTimeMillis() - startProcessingInputTime; } /** @@ -138,7 +138,7 @@ * you are interacting with the system or have activities scheduled. */ public static double getTotalFPS() { - if ((framesProcessed > 0)) { + if (framesProcessed > 0) { return 1000.0 / ((processInputTime + processOutputTime) / (double) framesProcessed); } else { @@ -150,7 +150,7 @@ * Return the frames per second used to process input events and activities. */ public static double getInputFPS() { - if ((processInputTime > 0) && (framesProcessed > 0)) { + if (processInputTime > 0 && framesProcessed > 0) { return 1000.0 / (processInputTime / (double) framesProcessed); } else { @@ -162,7 +162,7 @@ * Return the frames per seconds used to paint graphics to the screen. */ public static double getOutputFPS() { - if ((processOutputTime > 0) && (framesProcessed > 0)) { + if (processOutputTime > 0 && framesProcessed > 0) { return 1000.0 / (processOutputTime / (double) framesProcessed); } else { @@ -192,8 +192,8 @@ public static long getApproximateUsedMemory() { System.gc(); System.runFinalization(); - long totalMemory = Runtime.getRuntime().totalMemory(); - long free = Runtime.getRuntime().freeMemory(); + final long totalMemory = Runtime.getRuntime().totalMemory(); + final long free = Runtime.getRuntime().freeMemory(); return totalMemory - free; } } diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PDimension.java b/core/src/main/java/edu/umd/cs/piccolo/util/PDimension.java index f70b1bb..94ec009 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PDimension.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PDimension.java @@ -46,7 +46,7 @@ * formats. */ private static final long serialVersionUID = 1L; - + public double width; public double height; @@ -54,17 +54,17 @@ super(); } - public PDimension(Dimension2D aDimension) { + public PDimension(final Dimension2D aDimension) { this(aDimension.getWidth(), aDimension.getHeight()); } - public PDimension(double aWidth, double aHeight) { + public PDimension(final double aWidth, final double aHeight) { super(); width = aWidth; height = aHeight; } - public PDimension(Point2D p1, Point2D p2) { + public PDimension(final Point2D p1, final Point2D p2) { width = p2.getX() - p1.getX(); height = p2.getY() - p1.getY(); } @@ -73,17 +73,17 @@ return height; } - public double getWidth() { + public double getWidth() { return width; } - public void setSize(double aWidth, double aHeight) { + public void setSize(final double aWidth, final double aHeight) { width = aWidth; height = aHeight; } public String toString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append(super.toString().replaceAll(".*\\.", "")); result.append('['); diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PObjectOutputStream.java b/core/src/main/java/edu/umd/cs/piccolo/util/PObjectOutputStream.java index d970b7a..775a09f 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PObjectOutputStream.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PObjectOutputStream.java @@ -68,28 +68,28 @@ public class PObjectOutputStream extends ObjectOutputStream { private boolean writingRoot; - private HashMap unconditionallyWritten; + private final HashMap unconditionallyWritten; - public static byte[] toByteArray(Object aRoot) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PObjectOutputStream zout = new PObjectOutputStream(out); + public static byte[] toByteArray(final Object aRoot) throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final PObjectOutputStream zout = new PObjectOutputStream(out); zout.writeObjectTree(aRoot); return out.toByteArray(); } - public PObjectOutputStream(OutputStream out) throws IOException { + public PObjectOutputStream(final OutputStream out) throws IOException { super(out); unconditionallyWritten = new HashMap(); } - public void writeObjectTree(Object aRoot) throws IOException { + public void writeObjectTree(final Object aRoot) throws IOException { writingRoot = true; recordUnconditionallyWritten(aRoot); // record pass writeObject(aRoot); // write pass writingRoot = false; } - public void writeConditionalObject(Object object) throws IOException { + public void writeConditionalObject(final Object object) throws IOException { if (!writingRoot) { throw new RuntimeException( "writeConditionalObject() may only be called when a root object has been written."); @@ -108,19 +108,19 @@ unconditionallyWritten.clear(); } - protected void recordUnconditionallyWritten(Object aRoot) throws IOException { + protected void recordUnconditionallyWritten(final Object aRoot) throws IOException { class ZMarkObjectOutputStream extends PObjectOutputStream { public ZMarkObjectOutputStream() throws IOException { super(PUtil.NULL_OUTPUT_STREAM); enableReplaceObject(true); } - public Object replaceObject(Object object) { - PObjectOutputStream.this.unconditionallyWritten.put(object, Boolean.TRUE); + public Object replaceObject(final Object object) { + unconditionallyWritten.put(object, Boolean.TRUE); return object; } - public void writeConditionalObject(Object object) throws IOException { + public void writeConditionalObject(final Object object) throws IOException { } } new ZMarkObjectOutputStream().writeObject(aRoot); diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PPaintContext.java b/core/src/main/java/edu/umd/cs/piccolo/util/PPaintContext.java index f15a677..a248143 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PPaintContext.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PPaintContext.java @@ -59,7 +59,7 @@ private static double[] PTS = new double[4]; - private Graphics2D graphics; + private final Graphics2D graphics; protected PStack compositeStack; protected PStack clipStack; protected PStack localClipStack; @@ -67,7 +67,7 @@ protected PStack transformStack; protected int renderQuality; - public PPaintContext(Graphics2D aGraphics) { + public PPaintContext(final Graphics2D aGraphics) { super(); graphics = aGraphics; compositeStack = new PStack(); @@ -114,11 +114,11 @@ // popped. // **************************************************************** - public void pushCamera(PCamera aCamera) { + public void pushCamera(final PCamera aCamera) { cameraStack.push(aCamera); } - public void popCamera(PCamera aCamera) { + public void popCamera(final PCamera aCamera) { cameraStack.pop(); } @@ -126,57 +126,60 @@ return (PCamera) cameraStack.peek(); } - public void pushClip(Shape aClip) { - Shape currentClip = graphics.getClip(); + public void pushClip(final Shape aClip) { + final Shape currentClip = graphics.getClip(); clipStack.push(currentClip); graphics.clip(aClip); - Rectangle2D newLocalClip = aClip.getBounds2D(); + final Rectangle2D newLocalClip = aClip.getBounds2D(); Rectangle2D.intersect(getLocalClip(), newLocalClip, newLocalClip); localClipStack.push(newLocalClip); } - public void popClip(Shape aClip) { - Shape newClip = (Shape) clipStack.pop(); + public void popClip(final Shape aClip) { + final Shape newClip = (Shape) clipStack.pop(); graphics.setClip(newClip); localClipStack.pop(); } - public void pushTransparency(float transparency) { + public void pushTransparency(final float transparency) { if (transparency == 1) { return; } - Composite current = graphics.getComposite(); + final Composite current = graphics.getComposite(); float currentAlaph = 1.0f; compositeStack.push(current); if (current instanceof AlphaComposite) { currentAlaph = ((AlphaComposite) current).getAlpha(); } - AlphaComposite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, currentAlaph * transparency); + final AlphaComposite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, currentAlaph + * transparency); graphics.setComposite(newComposite); } - public void popTransparency(float transparency) { + public void popTransparency(final float transparency) { if (transparency == 1) { return; } - Composite c = (Composite) compositeStack.pop(); + final Composite c = (Composite) compositeStack.pop(); graphics.setComposite(c); } - public void pushTransform(PAffineTransform aTransform) { - if (aTransform == null) + public void pushTransform(final PAffineTransform aTransform) { + if (aTransform == null) { return; - Rectangle2D newLocalClip = (Rectangle2D) getLocalClip().clone(); + } + final Rectangle2D newLocalClip = (Rectangle2D) getLocalClip().clone(); aTransform.inverseTransform(newLocalClip, newLocalClip); transformStack.push(graphics.getTransform()); localClipStack.push(newLocalClip); graphics.transform(aTransform); } - public void popTransform(PAffineTransform aTransform) { - if (aTransform == null) + public void popTransform(final PAffineTransform aTransform) { + if (aTransform == null) { return; + } graphics.setTransform((AffineTransform) transformStack.pop()); localClipStack.pop(); } @@ -200,7 +203,7 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setRenderQuality(int requestedQuality) { + public void setRenderQuality(final int requestedQuality) { renderQuality = requestedQuality; switch (renderQuality) { diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PPickPath.java b/core/src/main/java/edu/umd/cs/piccolo/util/PPickPath.java index b9dc6e2..587430b 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PPickPath.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PPickPath.java @@ -71,11 +71,11 @@ private PStack nodeStack; private PStack transformStack; private PStack pickBoundsStack; - private PCamera topCamera; + private final PCamera topCamera; private PCamera bottomCamera; private HashMap excludedNodes; - public PPickPath(PCamera aCamera, PBounds aScreenPickBounds) { + public PPickPath(final PCamera aCamera, final PBounds aScreenPickBounds) { super(); pickBoundsStack = new PStack(); topCamera = aCamera; @@ -90,7 +90,7 @@ return (PBounds) pickBoundsStack.peek(); } - public boolean acceptsNode(PNode node) { + public boolean acceptsNode(final PNode node) { if (excludedNodes != null) { return !excludedNodes.containsKey(node); } @@ -101,11 +101,11 @@ // Picked Nodes // **************************************************************** - public void pushNode(PNode aNode) { + public void pushNode(final PNode aNode) { nodeStack.push(aNode); } - public void popNode(PNode aNode) { + public void popNode(final PNode aNode) { nodeStack.pop(); } @@ -128,17 +128,19 @@ * child. Return the camera when no more visual will be picked. */ public PNode nextPickedNode() { - PNode picked = getPickedNode(); + final PNode picked = getPickedNode(); - if (picked == topCamera) + if (picked == topCamera) { return null; - if (excludedNodes == null) + } + if (excludedNodes == null) { excludedNodes = new HashMap(); + } // exclude current picked node excludedNodes.put(picked, picked); - Object screenPickBounds = pickBoundsStack.get(0); + final Object screenPickBounds = pickBoundsStack.get(0); // reset path state pickBoundsStack = new PStack(); @@ -175,7 +177,7 @@ public PCamera getBottomCamera() { if (bottomCamera == null) { for (int i = nodeStack.size() - 1; i >= 0; i--) { - PNode each = (PNode) nodeStack.get(i); + final PNode each = (PNode) nodeStack.get(i); if (each instanceof PCamera) { bottomCamera = (PCamera) each; return bottomCamera; @@ -199,40 +201,42 @@ PTS[2] = 1;// x2 PTS[3] = 0;// y2 - int count = transformStack.size(); + final int count = transformStack.size(); for (int i = 0; i < count; i++) { - PAffineTransform each = ((PTuple) transformStack.get(i)).transform; - if (each != null) + final PAffineTransform each = ((PTuple) transformStack.get(i)).transform; + if (each != null) { each.transform(PTS, 0, PTS, 0, 2); + } } return Point2D.distance(PTS[0], PTS[1], PTS[2], PTS[3]); } - public void pushTransform(PAffineTransform aTransform) { + public void pushTransform(final PAffineTransform aTransform) { transformStack.push(new PTuple(getPickedNode(), aTransform)); if (aTransform != null) { - Rectangle2D newPickBounds = (Rectangle2D) getPickBounds().clone(); + final Rectangle2D newPickBounds = (Rectangle2D) getPickBounds().clone(); aTransform.inverseTransform(newPickBounds, newPickBounds); pickBoundsStack.push(newPickBounds); } } - public void popTransform(PAffineTransform aTransform) { + public void popTransform(final PAffineTransform aTransform) { transformStack.pop(); if (aTransform != null) { pickBoundsStack.pop(); } } - public PAffineTransform getPathTransformTo(PNode nodeOnPath) { - PAffineTransform aTransform = new PAffineTransform(); + public PAffineTransform getPathTransformTo(final PNode nodeOnPath) { + final PAffineTransform aTransform = new PAffineTransform(); - int count = transformStack.size(); + final int count = transformStack.size(); for (int i = 0; i < count; i++) { - PTuple each = (PTuple) transformStack.get(i); - if (each.transform != null) + final PTuple each = (PTuple) transformStack.get(i); + if (each.transform != null) { aTransform.concatenate(each.transform); + } if (nodeOnPath == each.node) { return aTransform; } @@ -246,19 +250,19 @@ // the bottom most one, a chance to handle the event. // **************************************************************** - public void processEvent(PInputEvent aEvent, int type) { + public void processEvent(final PInputEvent aEvent, final int type) { aEvent.setPath(this); for (int i = nodeStack.size() - 1; i >= 0; i--) { - PNode each = (PNode) nodeStack.get(i); + final PNode each = (PNode) nodeStack.get(i); - EventListenerList list = each.getListenerList(); + final EventListenerList list = each.getListenerList(); if (list != null) { - Object[] listeners = list.getListeners(PInputEventListener.class); + final Object[] listeners = list.getListeners(PInputEventListener.class); for (int j = 0; j < listeners.length; j++) { - PInputEventListener listener = (PInputEventListener) listeners[j]; + final PInputEventListener listener = (PInputEventListener) listeners[j]; listener.processEvent(aEvent, type); if (aEvent.isHandled()) { return; @@ -286,7 +290,7 @@ * pick path (and through any camera view transforms applied to the path) to * the local coordinates of the given node. */ - public Point2D canvasToLocal(Point2D canvasPoint, PNode nodeOnPath) { + public Point2D canvasToLocal(final Point2D canvasPoint, final PNode nodeOnPath) { return getPathTransformTo(nodeOnPath).inverseTransform(canvasPoint, canvasPoint); } @@ -295,7 +299,7 @@ * pick path (and through any camera view transforms applied to the path) to * the local coordinates of the given node. */ - public Dimension2D canvasToLocal(Dimension2D canvasDimension, PNode nodeOnPath) { + public Dimension2D canvasToLocal(final Dimension2D canvasDimension, final PNode nodeOnPath) { return getPathTransformTo(nodeOnPath).inverseTransform(canvasDimension, canvasDimension); } @@ -304,7 +308,7 @@ * pick path (and through any camera view transforms applied to the path) to * the local coordinates of the given node. */ - public Rectangle2D canvasToLocal(Rectangle2D canvasRectangle, PNode nodeOnPath) { + public Rectangle2D canvasToLocal(final Rectangle2D canvasRectangle, final PNode nodeOnPath) { return getPathTransformTo(nodeOnPath).inverseTransform(canvasRectangle, canvasRectangle); } @@ -315,7 +319,7 @@ public PNode node; public PAffineTransform transform; - public PTuple(PNode n, PAffineTransform t) { + public PTuple(final PNode n, final PAffineTransform t) { node = n; transform = t; } diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PStack.java b/core/src/main/java/edu/umd/cs/piccolo/util/PStack.java index a46f39c..7f4edca 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PStack.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PStack.java @@ -44,16 +44,16 @@ * formats. */ private static final long serialVersionUID = 1L; - + public PStack() { } - public void push(Object o) { + public void push(final Object o) { add(o); } public Object peek() { - int s = size(); + final int s = size(); if (s == 0) { return null; } diff --git a/core/src/main/java/edu/umd/cs/piccolo/util/PUtil.java b/core/src/main/java/edu/umd/cs/piccolo/util/PUtil.java index 1087787..8b8f11d 100644 --- a/core/src/main/java/edu/umd/cs/piccolo/util/PUtil.java +++ b/core/src/main/java/edu/umd/cs/piccolo/util/PUtil.java @@ -76,20 +76,20 @@ public void flush() { } - public void write(byte[] b) { + public void write(final byte[] b) { } - public void write(byte[] b, int off, int len) { + public void write(final byte[] b, final int off, final int len) { } - public void write(int b) { + public void write(final int b) { } }; public static PCamera createBasicScenegraph() { - PRoot r = new PRoot(); - PLayer l = new PLayer(); - PCamera c = new PCamera(); + final PRoot r = new PRoot(); + final PLayer l = new PLayer(); + final PCamera c = new PCamera(); r.addChild(c); r.addChild(l); @@ -98,7 +98,7 @@ return c; } - public static void writeStroke(Stroke stroke, ObjectOutputStream out) throws IOException { + public static void writeStroke(final Stroke stroke, final ObjectOutputStream out) throws IOException { if (stroke instanceof Serializable) { out.writeBoolean(true); out.writeBoolean(true); @@ -114,8 +114,9 @@ } } - private static void writeBasicStroke(BasicStroke basicStroke, ObjectOutputStream out) throws IOException { - float[] dash = basicStroke.getDashArray(); + private static void writeBasicStroke(final BasicStroke basicStroke, final ObjectOutputStream out) + throws IOException { + final float[] dash = basicStroke.getDashArray(); if (dash == null) { out.write(0); @@ -134,13 +135,13 @@ out.writeFloat(basicStroke.getDashPhase()); } - public static Stroke readStroke(ObjectInputStream in) throws IOException, ClassNotFoundException { - boolean wroteStroke = in.readBoolean(); + public static Stroke readStroke(final ObjectInputStream in) throws IOException, ClassNotFoundException { + final boolean wroteStroke = in.readBoolean(); if (!wroteStroke) { return null; } - boolean serializedStroke = in.readBoolean(); + final boolean serializedStroke = in.readBoolean(); if (serializedStroke) { return (Stroke) in.readObject(); } @@ -148,9 +149,9 @@ return readBasicStroke(in); } - private static Stroke readBasicStroke(ObjectInputStream in) throws IOException { + private static Stroke readBasicStroke(final ObjectInputStream in) throws IOException { float[] dash = null; - int dashLength = in.read(); + final int dashLength = in.read(); if (dashLength != 0) { dash = new float[dashLength]; @@ -159,20 +160,20 @@ } } - float lineWidth = in.readFloat(); - int endCap = in.readInt(); - int lineJoin = in.readInt(); - float miterLimit = in.readFloat(); - float dashPhase = in.readFloat(); + final float lineWidth = in.readFloat(); + final int endCap = in.readInt(); + final int lineJoin = in.readInt(); + final float miterLimit = in.readFloat(); + final float dashPhase = in.readFloat(); return new BasicStroke(lineWidth, endCap, lineJoin, miterLimit, dash, dashPhase); } - public static GeneralPath readPath(ObjectInputStream in) throws IOException, ClassNotFoundException { - GeneralPath path = new GeneralPath(); + public static GeneralPath readPath(final ObjectInputStream in) throws IOException, ClassNotFoundException { + final GeneralPath path = new GeneralPath(); while (true) { - int segType = in.readInt(); + final int segType = in.readInt(); switch (segType) { case PathIterator.SEG_MOVETO: @@ -205,9 +206,9 @@ } } - public static void writePath(GeneralPath path, ObjectOutputStream out) throws IOException { - PathIterator i = path.getPathIterator(null); - float[] data = new float[6]; + public static void writePath(final GeneralPath path, final ObjectOutputStream out) throws IOException { + final PathIterator i = path.getPathIterator(null); + final float[] data = new float[6]; while (!i.isDone()) { switch (i.currentSegment(data)) { diff --git a/core/src/test/java/edu/umd/cs/piccolo/MockPInputEventListener.java b/core/src/test/java/edu/umd/cs/piccolo/MockPInputEventListener.java index 8bdeee1..ddc2235 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/MockPInputEventListener.java +++ b/core/src/test/java/edu/umd/cs/piccolo/MockPInputEventListener.java @@ -7,28 +7,28 @@ import edu.umd.cs.piccolo.event.PInputEventListener; public class MockPInputEventListener implements PInputEventListener { - static class Notification { - public PInputEvent event; - public int type; - - public Notification(PInputEvent event, int type) { - this.event = event; - this.type = type; - } - } - - private List notifications = new ArrayList(); - - public void processEvent(PInputEvent aEvent, int type) { - notifications.add(new Notification(aEvent, type)); - } - - public int getNotificationCount() { - return notifications.size(); - } - - public Notification getNotification(int index) { - return (Notification) notifications.get(index); - } + static class Notification { + public PInputEvent event; + public int type; + + public Notification(final PInputEvent event, final int type) { + this.event = event; + this.type = type; + } + } + + private final List notifications = new ArrayList(); + + public void processEvent(final PInputEvent aEvent, final int type) { + notifications.add(new Notification(aEvent, type)); + } + + public int getNotificationCount() { + return notifications.size(); + } + + public Notification getNotification(final int index) { + return (Notification) notifications.get(index); + } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/MockPropertyChangeListener.java b/core/src/test/java/edu/umd/cs/piccolo/MockPropertyChangeListener.java index a218df6..cc15bd4 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/MockPropertyChangeListener.java +++ b/core/src/test/java/edu/umd/cs/piccolo/MockPropertyChangeListener.java @@ -9,17 +9,17 @@ import java.util.List; public class MockPropertyChangeListener implements PropertyChangeListener { - private List changes = new ArrayList(); + private final List changes = new ArrayList(); - public void propertyChange(PropertyChangeEvent evt) { - changes.add(evt); - } + public void propertyChange(final PropertyChangeEvent evt) { + changes.add(evt); + } - public int getPropertyChangeCount() { - return changes.size(); - } - - public PropertyChangeEvent getPropertyChange(int index) { - return (PropertyChangeEvent) changes.get(index); - } + public int getPropertyChangeCount() { + return changes.size(); + } + + public PropertyChangeEvent getPropertyChange(final int index) { + return (PropertyChangeEvent) changes.get(index); + } } \ No newline at end of file diff --git a/core/src/test/java/edu/umd/cs/piccolo/PCameraTest.java b/core/src/test/java/edu/umd/cs/piccolo/PCameraTest.java index f7487d2..4f084a3 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PCameraTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PCameraTest.java @@ -32,6 +32,7 @@ import java.awt.Cursor; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; +import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.IOException; @@ -48,7 +49,7 @@ private PCamera camera; - public PCameraTest(String name) { + public PCameraTest(final String name) { super(name); } @@ -59,13 +60,13 @@ } public void testClone() { - PNode n = new PNode(); + final PNode n = new PNode(); - PLayer layer1 = new PLayer(); - PLayer layer2 = new PLayer(); + final PLayer layer1 = new PLayer(); + final PLayer layer2 = new PLayer(); - PCamera camera1 = new PCamera(); - PCamera camera2 = new PCamera(); + final PCamera camera1 = new PCamera(); + final PCamera camera2 = new PCamera(); n.addChild(layer1); n.addChild(layer2); @@ -78,7 +79,7 @@ camera2.addLayer(layer2); // no layers should be written out since they are written conditionally. - PCamera cameraCopy = (PCamera) camera1.clone(); + final PCamera cameraCopy = (PCamera) camera1.clone(); assertEquals(cameraCopy.getLayerCount(), 0); n.clone(); @@ -89,7 +90,7 @@ public void testCameraShouldHaveNullComponentUntilAssigned() { assertNull(camera.getComponent()); - MockPComponent component = new MockPComponent(); + final MockPComponent component = new MockPComponent(); camera.setComponent(component); assertNotNull(camera.getComponent()); @@ -105,7 +106,7 @@ } public void testIndexOfLayerReturnsMinusOneWhenLayerNotFound() { - PLayer orphanLayer = new PLayer(); + final PLayer orphanLayer = new PLayer(); assertEquals(-1, camera.indexOfLayer(orphanLayer)); camera.addLayer(new PLayer()); @@ -113,61 +114,61 @@ } public void testRemoveLayerByReferenceWorks() { - PLayer layer = new PLayer(); + final PLayer layer = new PLayer(); camera.addLayer(layer); camera.removeLayer(layer); assertEquals(0, camera.getLayerCount()); } public void testRemoveLayerByReferenceDoesNothingWithStrangeLayerWorks() { - PLayer strangeLayer = new PLayer(); - camera.removeLayer(strangeLayer); + final PLayer strangeLayer = new PLayer(); + camera.removeLayer(strangeLayer); } - + public void testRemoveLayerRemovesTheCameraFromTheLayer() { - PLayer layer = new PLayer(); - camera.addLayer(layer); + final PLayer layer = new PLayer(); + camera.addLayer(layer); camera.removeLayer(layer); assertEquals(0, layer.getCameraCount()); } - + public void testAddingLayerAddCameraToLayer() { - PLayer layer = new PLayer(); - camera.addLayer(layer); + final PLayer layer = new PLayer(); + camera.addLayer(layer); assertSame(camera, layer.getCamera(0)); } public void testGetFullUnionOfLayerFullBoundsWorks() { - PLayer layer1 = new PLayer(); + final PLayer layer1 = new PLayer(); layer1.setBounds(0, 0, 10, 10); camera.addLayer(layer1); - PLayer layer2 = new PLayer(); + final PLayer layer2 = new PLayer(); layer2.setBounds(10, 10, 10, 10); camera.addLayer(layer2); - PBounds fullLayerBounds = camera.getUnionOfLayerFullBounds(); + final PBounds fullLayerBounds = camera.getUnionOfLayerFullBounds(); assertEquals(new PBounds(0, 0, 20, 20), fullLayerBounds); } public void testPaintPaintsAllLayers() { - PCanvas canvas = new PCanvas(); - PCamera camera = canvas.getCamera(); + final PCanvas canvas = new PCanvas(); + final PCamera camera = canvas.getCamera(); - BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); - Graphics2D g2 = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); + final BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + final Graphics2D g2 = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); - PLayer layer1 = canvas.getLayer(); - PNode blueSquare = new PNode(); + final PLayer layer1 = canvas.getLayer(); + final PNode blueSquare = new PNode(); blueSquare.setPaint(Color.BLUE); blueSquare.setBounds(0, 0, 10, 10); layer1.addChild(blueSquare); camera.addLayer(layer1); - PLayer layer2 = new PLayer(); + final PLayer layer2 = new PLayer(); canvas.getLayer().getRoot().addChild(layer2); layer2.setOffset(10, 10); - PNode redSquare = new PNode(); + final PNode redSquare = new PNode(); redSquare.setPaint(Color.RED); redSquare.setBounds(0, 0, 10, 10); layer2.addChild(redSquare); @@ -181,22 +182,22 @@ } public void testPickPackWorksInSimpleCases() { - PLayer layer = new PLayer(); + final PLayer layer = new PLayer(); camera.addChild(layer); - PNode node1 = new PNode(); + final PNode node1 = new PNode(); node1.setBounds(0, 0, 10, 10); layer.addChild(node1); - PNode node2 = new PNode(); + final PNode node2 = new PNode(); node2.setBounds(0, 0, 10, 10); node2.setOffset(10, 10); layer.addChild(node2); - PPickPath path1 = camera.pick(5, 5, 1); + final PPickPath path1 = camera.pick(5, 5, 1); assertEquals(node1, path1.getPickedNode()); - PPickPath path2 = camera.pick(15, 15, 1); + final PPickPath path2 = camera.pick(15, 15, 1); assertEquals(node2, path2.getPickedNode()); } @@ -232,16 +233,16 @@ } public void testViewTransformedFiresChangeEvent() { - MockPropertyChangeListener mockListener = new MockPropertyChangeListener(); + final MockPropertyChangeListener mockListener = new MockPropertyChangeListener(); camera.addPropertyChangeListener(PCamera.PROPERTY_VIEW_TRANSFORM, mockListener); - camera.setViewTransform(PAffineTransform.getScaleInstance(2, 2)); + camera.setViewTransform(AffineTransform.getScaleInstance(2, 2)); assertEquals(1, mockListener.getPropertyChangeCount()); } public void testAnimateViewToCenterBoundsIsImmediateWhenDurationIsZero() { camera.setViewBounds(new PBounds(0, 0, 10, 10)); - PBounds targetBounds = new PBounds(-5, -5, 10, 10); - PActivity activity = camera.animateViewToCenterBounds(targetBounds, true, 0); + final PBounds targetBounds = new PBounds(-5, -5, 10, 10); + final PActivity activity = camera.animateViewToCenterBounds(targetBounds, true, 0); assertNull(activity); assertEquals(-5, camera.getViewTransform().getTranslateX(), 0.001); @@ -250,8 +251,8 @@ public void testAnimateViewToCenterBoundsCreatesValidActivity() { camera.setViewBounds(new PBounds(0, 0, 10, 10)); - PBounds targetBounds = new PBounds(-5, -5, 10, 10); - PActivity activity = camera.animateViewToCenterBounds(targetBounds, true, 100); + final PBounds targetBounds = new PBounds(-5, -5, 10, 10); + final PActivity activity = camera.animateViewToCenterBounds(targetBounds, true, 100); assertNotNull(activity); assertEquals(100, activity.getDuration()); @@ -267,28 +268,28 @@ public void testAnimateViewToPanToBoundsIsImmediateWhenDurationIsZero() { camera.setViewBounds(new PBounds(0, 0, 10, 10)); - PActivity activity = camera.animateViewToPanToBounds(new PBounds(10, 10, 10, 10), 0); + final PActivity activity = camera.animateViewToPanToBounds(new PBounds(10, 10, 10, 10), 0); assertNull(activity); - assertEquals(PAffineTransform.getTranslateInstance(-15, -15), camera.getViewTransform()); + assertEquals(AffineTransform.getTranslateInstance(-15, -15), camera.getViewTransform()); } public void testAnimateViewToPanToBoundsReturnsAppropriatelyConfiguredActivity() { camera.setViewBounds(new PBounds(0, 0, 10, 10)); - PTransformActivity activity = camera.animateViewToPanToBounds(new PBounds(10, 10, 10, 10), 100); + final PTransformActivity activity = camera.animateViewToPanToBounds(new PBounds(10, 10, 10, 10), 100); assertNotNull(activity); assertEquals(100, activity.getDuration()); assertFalse(activity.isStepping()); - assertEquals(PAffineTransform.getTranslateInstance(-15, -15), new PAffineTransform(activity + assertEquals(AffineTransform.getTranslateInstance(-15, -15), new PAffineTransform(activity .getDestinationTransform())); } public void testPDebugDebugBoundsPaintsBounds() throws IOException { - PCanvas canvas = new PCanvas(); + final PCanvas canvas = new PCanvas(); - PNode parent = new PNode(); - PNode child = new PNode(); + final PNode parent = new PNode(); + final PNode child = new PNode(); parent.addChild(child); parent.setBounds(0, 0, 10, 10); @@ -303,11 +304,11 @@ PDebug.debugBounds = true; PDebug.debugFullBounds = false; - BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); + final BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + final Graphics2D graphics = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); graphics.setPaint(Color.WHITE); graphics.fillRect(0, 0, 100, 100); - PPaintContext pc = new PPaintContext(graphics); + final PPaintContext pc = new PPaintContext(graphics); canvas.setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); canvas.getCamera().paint(pc); @@ -327,7 +328,7 @@ assertPointColor(Color.WHITE, img, 15, 10); } - private void assertPointColor(Color expectedColor, BufferedImage img, int x, int y) { + private void assertPointColor(final Color expectedColor, final BufferedImage img, final int x, final int y) { assertEquals(expectedColor.getRGB(), img.getRGB(x, y)); } @@ -347,7 +348,7 @@ camera.setViewConstraint(PCamera.VIEW_CONSTRAINT_ALL); assertEquals(PCamera.VIEW_CONSTRAINT_ALL, camera.getViewConstraint()); } - + static class MockPComponent implements PComponent { public void paintImmediately() { @@ -356,13 +357,13 @@ public void popCursor() { } - public void pushCursor(Cursor cursor) { + public void pushCursor(final Cursor cursor) { } - public void repaint(PBounds bounds) { + public void repaint(final PBounds bounds) { } - public void setInteracting(boolean interacting) { + public void setInteracting(final boolean interacting) { } } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/PCanvasTest.java b/core/src/test/java/edu/umd/cs/piccolo/PCanvasTest.java index 3c3ea43..baad8ae 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PCanvasTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PCanvasTest.java @@ -28,8 +28,8 @@ assertFalse(canvas.getInteracting()); } - public void testDefaultNumberOfEventListenersIs2() { - PInputEventListener[] listeners = canvas.getInputEventListeners(); + public void testDefaultNumberOfEventListenersIs2() { + final PInputEventListener[] listeners = canvas.getInputEventListeners(); assertNotNull(listeners); assertEquals(2, listeners.length); } @@ -44,7 +44,7 @@ } public void testSetInteractingFiresChangeEvent() { - MockPropertyChangeListener mockListener = new MockPropertyChangeListener(); + final MockPropertyChangeListener mockListener = new MockPropertyChangeListener(); canvas.addPropertyChangeListener(PCanvas.INTERACTING_CHANGED_NOTIFICATION, mockListener); canvas.setInteracting(true); assertEquals(1, mockListener.getPropertyChangeCount()); @@ -71,9 +71,9 @@ } public void testCursorStackWorksAsExpected() { - Cursor moveCursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); - Cursor handCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - Cursor crosshairCursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + final Cursor moveCursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); + final Cursor handCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); + final Cursor crosshairCursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); canvas.pushCursor(moveCursor); canvas.pushCursor(handCursor); @@ -90,7 +90,7 @@ try { canvas.popCursor(); } - catch (IndexOutOfBoundsException e) { + catch (final IndexOutOfBoundsException e) { fail("Pop cursor shouldn't fail on an empty stack"); } assertEquals(Cursor.getDefaultCursor(), canvas.getCursor()); @@ -103,24 +103,30 @@ public void testAddInputEventListenersIsHonoured() { canvas.addInputEventListener(mockListener); - PInputEventListener[] listeners = canvas.getInputEventListeners(); + final PInputEventListener[] listeners = canvas.getInputEventListeners(); assertNotNull(listeners); - assertEquals(3, listeners.length); // 3 since pan and zoom are attached by default + assertEquals(3, listeners.length); // 3 since pan and zoom are attached + // by default } public void testRemoveInputEventListenersIsHonoured() { canvas.addInputEventListener(mockListener); canvas.removeInputEventListener(mockListener); - PInputEventListener[] listeners = canvas.getInputEventListeners(); + final PInputEventListener[] listeners = canvas.getInputEventListeners(); assertNotNull(listeners); - assertEquals(2, listeners.length); // 3 since pan and zoom are attached by default + assertEquals(2, listeners.length); // 3 since pan and zoom are attached + // by default } - public void testMemoryLeak() throws InterruptedException { - JPanel panel = new JPanel(); + final JPanel panel = new JPanel(); for (int i = 0; i < 10; i++) { PCanvas canvas = new PCanvas() { + /** + * + */ + private static final long serialVersionUID = 1L; + public void finalize() { pCanvasFinalizerCount++; } @@ -135,7 +141,7 @@ // Not sure why I need -1 here, but I do. If I create 10000 it'll always // be 1 less - //assertEquals(10-1, pCanvasFinalizerCount); + // assertEquals(10-1, pCanvasFinalizerCount); } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java b/core/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java index dabd832..10b6df7 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java @@ -10,97 +10,95 @@ import edu.umd.cs.piccolo.util.PPickPath; public class PInputManagerTest extends TestCase { - private PInputManager manager; + private PInputManager manager; private MockPInputEventListener mockListener; - public void setUp() { - manager = new PInputManager(); - mockListener = new MockPInputEventListener(); - } + public void setUp() { + manager = new PInputManager(); + mockListener = new MockPInputEventListener(); + } - public void testGetKeyboardFocusNullByDefault() { - assertNull(manager.getKeyboardFocus()); - } + public void testGetKeyboardFocusNullByDefault() { + assertNull(manager.getKeyboardFocus()); + } - public void testSetKeyboardFocusIsPersisted() { - manager.setKeyboardFocus(mockListener); - assertEquals(mockListener, manager.getKeyboardFocus()); - } + public void testSetKeyboardFocusIsPersisted() { + manager.setKeyboardFocus(mockListener); + assertEquals(mockListener, manager.getKeyboardFocus()); + } - public void testSetKeyboardFocusDispatchesEventsAboutFocus() { - MockPInputEventListener oldListener = new MockPInputEventListener(); - manager.setKeyboardFocus(oldListener); + public void testSetKeyboardFocusDispatchesEventsAboutFocus() { + final MockPInputEventListener oldListener = new MockPInputEventListener(); + manager.setKeyboardFocus(oldListener); - assertEquals(1, oldListener.getNotificationCount()); - assertEquals(FocusEvent.FOCUS_GAINED, - oldListener.getNotification(0).type); + assertEquals(1, oldListener.getNotificationCount()); + assertEquals(FocusEvent.FOCUS_GAINED, oldListener.getNotification(0).type); - MockPInputEventListener newListener = new MockPInputEventListener(); - manager.setKeyboardFocus(newListener); + final MockPInputEventListener newListener = new MockPInputEventListener(); + manager.setKeyboardFocus(newListener); - assertEquals(1, newListener.getNotificationCount()); - assertEquals(FocusEvent.FOCUS_GAINED, - newListener.getNotification(0).type); - assertEquals(2, oldListener.getNotificationCount()); - assertEquals(FocusEvent.FOCUS_LOST, oldListener.getNotification(1).type); - } + assertEquals(1, newListener.getNotificationCount()); + assertEquals(FocusEvent.FOCUS_GAINED, newListener.getNotification(0).type); + assertEquals(2, oldListener.getNotificationCount()); + assertEquals(FocusEvent.FOCUS_LOST, oldListener.getNotification(1).type); + } - public void testGetMouseFocusNullByDefault() { - assertNull(manager.getMouseFocus()); - } + public void testGetMouseFocusNullByDefault() { + assertNull(manager.getMouseFocus()); + } - public void testSetMouseFocusPersists() { - PCamera camera = new PCamera(); - PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); - manager.setMouseFocus(path); - assertEquals(path, manager.getMouseFocus()); - } + public void testSetMouseFocusPersists() { + final PCamera camera = new PCamera(); + final PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); + manager.setMouseFocus(path); + assertEquals(path, manager.getMouseFocus()); + } - public void testGetMouseOverNullByDefault() { - assertNull(manager.getMouseOver()); - } + public void testGetMouseOverNullByDefault() { + assertNull(manager.getMouseOver()); + } - public void testSetMouseOverPersists() { - PCamera camera = new PCamera(); - PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); - manager.setMouseOver(path); - assertEquals(path, manager.getMouseOver()); - } + public void testSetMouseOverPersists() { + final PCamera camera = new PCamera(); + final PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); + manager.setMouseOver(path); + assertEquals(path, manager.getMouseOver()); + } - public void testGetCurrentCanvasPositionIsOriginByDefault() { - assertEquals(new Point2D.Double(0, 0), manager - .getCurrentCanvasPosition()); - } + public void testGetCurrentCanvasPositionIsOriginByDefault() { + assertEquals(new Point2D.Double(0, 0), manager.getCurrentCanvasPosition()); + } - public void testGetLastCanvasPositionIsOriginByDefault() { - assertEquals(new Point2D.Double(0, 0), manager.getLastCanvasPosition()); - } - - public void testKeyPressedDispatchesToCurrentFocus() { - manager.setKeyboardFocus(mockListener); - PInputEvent event = new PInputEvent(manager, null); - manager.keyPressed(event); - assertEquals(2, mockListener.getNotificationCount()); - assertEquals(KeyEvent.KEY_PRESSED, mockListener.getNotification(1).type); - } - public void testKeyReleasedDispatchesToCurrentFocus() { - manager.setKeyboardFocus(mockListener); - PInputEvent event = new PInputEvent(manager, null); - manager.keyReleased(event); - assertEquals(2, mockListener.getNotificationCount()); - assertEquals(KeyEvent.KEY_RELEASED, mockListener.getNotification(1).type); - } - - public void testKeyTypedDispatchesToCurrentFocus() { - manager.setKeyboardFocus(mockListener); - PInputEvent event = new PInputEvent(manager, null); - manager.keyTyped(event); - assertEquals(2, mockListener.getNotificationCount()); - assertEquals(KeyEvent.KEY_TYPED, mockListener.getNotification(1).type); - } - - public void testProcessInputMayBeCalledOnFreshManager() { - manager.processInput(); - } - + public void testGetLastCanvasPositionIsOriginByDefault() { + assertEquals(new Point2D.Double(0, 0), manager.getLastCanvasPosition()); + } + + public void testKeyPressedDispatchesToCurrentFocus() { + manager.setKeyboardFocus(mockListener); + final PInputEvent event = new PInputEvent(manager, null); + manager.keyPressed(event); + assertEquals(2, mockListener.getNotificationCount()); + assertEquals(KeyEvent.KEY_PRESSED, mockListener.getNotification(1).type); + } + + public void testKeyReleasedDispatchesToCurrentFocus() { + manager.setKeyboardFocus(mockListener); + final PInputEvent event = new PInputEvent(manager, null); + manager.keyReleased(event); + assertEquals(2, mockListener.getNotificationCount()); + assertEquals(KeyEvent.KEY_RELEASED, mockListener.getNotification(1).type); + } + + public void testKeyTypedDispatchesToCurrentFocus() { + manager.setKeyboardFocus(mockListener); + final PInputEvent event = new PInputEvent(manager, null); + manager.keyTyped(event); + assertEquals(2, mockListener.getNotificationCount()); + assertEquals(KeyEvent.KEY_TYPED, mockListener.getNotification(1).type); + } + + public void testProcessInputMayBeCalledOnFreshManager() { + manager.processInput(); + } + } diff --git a/core/src/test/java/edu/umd/cs/piccolo/PLayerTest.java b/core/src/test/java/edu/umd/cs/piccolo/PLayerTest.java index e1b9bf3..ea446f7 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PLayerTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PLayerTest.java @@ -15,20 +15,20 @@ } public void testLayerHasEmptyCamerasCollectionByDefault() { - Collection cameras = layer.getCamerasReference(); + final Collection cameras = layer.getCamerasReference(); assertNotNull(cameras); assertTrue(cameras.isEmpty()); assertEquals(0, layer.getCameraCount()); } public void testGetCameraByIndexThrowsIndexOutOfBoundsExceptionWhenOutOfBounds() { - PCamera camera = new PCamera(); + final PCamera camera = new PCamera(); layer.addCamera(camera); try { layer.getCamera(-1); fail("Exception should have been thrown"); } - catch (IndexOutOfBoundsException e) { + catch (final IndexOutOfBoundsException e) { // expected; } @@ -36,15 +36,15 @@ layer.getCamera(1); fail("Exception should have been thrown"); } - catch (IndexOutOfBoundsException e) { + catch (final IndexOutOfBoundsException e) { // expected; } } public void testGetCameraReturnsCameraAtCorrectIndex() { - PCamera camera1 = new PCamera(); - PCamera camera2 = new PCamera(); - PCamera camera3 = new PCamera(); + final PCamera camera1 = new PCamera(); + final PCamera camera2 = new PCamera(); + final PCamera camera3 = new PCamera(); layer.addCamera(camera1); layer.addCamera(camera2); @@ -56,9 +56,9 @@ } public void testAddCameraCorrectlyHandlesIndex() { - PCamera camera1 = new PCamera(); - PCamera camera2 = new PCamera(); - PCamera camera3 = new PCamera(); + final PCamera camera1 = new PCamera(); + final PCamera camera2 = new PCamera(); + final PCamera camera3 = new PCamera(); layer.addCamera(0, camera1); layer.addCamera(0, camera2); @@ -70,43 +70,47 @@ } public void testRemovingCameraByReferenceWorksWhenCameraIsFound() { - PCamera camera = new PCamera(); + final PCamera camera = new PCamera(); layer.addCamera(camera); layer.removeCamera(camera); assertEquals(0, layer.getCameraCount()); } public void testRemovingCameraByIndexWorksWhenIndexIsValid() { - PCamera camera = new PCamera(); + final PCamera camera = new PCamera(); layer.addCamera(camera); layer.removeCamera(0); assertEquals(0, layer.getCameraCount()); } public void testRemovingCameraNotAttachedToCameraShouldDoNothing() { - PCamera strangerCamera = new PCamera(); + final PCamera strangerCamera = new PCamera(); layer.removeCamera(strangerCamera); assertEquals(0, layer.getCameraCount()); } public void testRepaintFromNotifiesCameras() { - MockPCamera camera = new MockPCamera(); + final MockPCamera camera = new MockPCamera(); layer.addCamera(camera); - PBounds bounds = new PBounds(0, 0, 100, 100); + final PBounds bounds = new PBounds(0, 0, 100, 100); layer.repaintFrom(bounds, layer); assertEquals(1, camera.notifications.size()); - MockPCamera.Notification notification = (MockPCamera.Notification) camera.notifications.get(0); + final MockPCamera.Notification notification = (MockPCamera.Notification) camera.notifications.get(0); assertEquals(layer, notification.layer); assertEquals(bounds, notification.bounds); } static class MockPCamera extends PCamera { + /** + * + */ + private static final long serialVersionUID = 1L; List notifications = new ArrayList(); - public void repaintFromLayer(PBounds bounds, PLayer layer) { + public void repaintFromLayer(final PBounds bounds, final PLayer layer) { notifications.add(new Notification("repaintFromLayer", bounds, layer)); super.repaintFromLayer(bounds, layer); } @@ -117,7 +121,7 @@ // this should really be PLayer PNode layer; - Notification(String type, PBounds bounds, PNode layer) { + Notification(final String type, final PBounds bounds, final PNode layer) { this.bounds = bounds; this.layer = layer; this.type = type; diff --git a/core/src/test/java/edu/umd/cs/piccolo/PNodeTest.java b/core/src/test/java/edu/umd/cs/piccolo/PNodeTest.java index 24bfd2c..6bd56ac 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PNodeTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PNodeTest.java @@ -66,7 +66,7 @@ private MockPropertyChangeListener mockListener; private PNode node; - public PNodeTest(String name) { + public PNodeTest(final String name) { super(name); } @@ -83,7 +83,7 @@ } public void testClientProperties() { - PNode n = new PNode(); + final PNode n = new PNode(); assertNull(n.getAttribute(null)); n.addAttribute("a", "b"); @@ -94,8 +94,8 @@ } public void testFullScale() { - PNode aParent = new PNode(); - PNode aNode = new PNode(); + final PNode aParent = new PNode(); + final PNode aNode = new PNode(); aParent.addChild(aNode); @@ -112,8 +112,8 @@ } public void testReparent() { - PNode aParent = new PNode(); - PNode aNode = new PNode(); + final PNode aParent = new PNode(); + final PNode aNode = new PNode(); aParent.setOffset(400, 500); aParent.scale(0.5); @@ -132,8 +132,8 @@ } public void testFindIntersectingNodes() { - PNode n = new PNode(); - PNode c = new PNode(); + final PNode n = new PNode(); + final PNode c = new PNode(); n.addChild(c); n.setBounds(0, 0, 100, 100); @@ -141,14 +141,14 @@ c.scale(200); ArrayList found = new ArrayList(); - Rectangle2D rect2d = new Rectangle2D.Double(50, 50, 10, 10); + final Rectangle2D rect2d = new Rectangle2D.Double(50, 50, 10, 10); n.findIntersectingNodes(rect2d, found); assertEquals(found.size(), 2); assertEquals(rect2d.getHeight(), 10, 0); found = new ArrayList(); - PBounds bounds = new PBounds(50, 50, 10, 10); + final PBounds bounds = new PBounds(50, 50, 10, 10); n.findIntersectingNodes(bounds, found); assertEquals(found.size(), 2); @@ -156,12 +156,12 @@ } public void testRemoveNonexistantListener() { - PNode n = new PNode(); + final PNode n = new PNode(); n.removeInputEventListener(new PBasicInputEventHandler()); } public void testAddChildHandleDuplicates() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); parent.addChild(new PNode()); parent.addChild(node); @@ -169,7 +169,7 @@ } public void testAddChildCanSpecifyAnIndexAndDoesntReplace() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(new PNode()); parent.addChild(0, node); assertEquals(0, parent.indexOfChild(node)); @@ -177,7 +177,7 @@ } public void testAddChildWithIndexMovesChildAround() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(new PNode()); parent.addChild(new PNode()); @@ -196,24 +196,24 @@ public void testCopy() { node.setPaint(Color.yellow); - PNode child = new PNode(); + final PNode child = new PNode(); node.addChild(child); - PNode clonedNode = (PNode) node.clone(); + final PNode clonedNode = (PNode) node.clone(); assertEquals(clonedNode.getPaint(), Color.yellow); assertEquals(clonedNode.getChildrenCount(), 1); } public void testLocalToGlobal() { - PNode aParent = new PNode(); - PNode aChild = new PNode(); + final PNode aParent = new PNode(); + final PNode aChild = new PNode(); aParent.addChild(aChild); aChild.scale(0.5); // bounds - PBounds bnds = new PBounds(0, 0, 50, 50); + final PBounds bnds = new PBounds(0, 0, 50, 50); aChild.localToGlobal(bnds); assertEquals(0, bnds.x, 0); @@ -231,7 +231,7 @@ aChild.getLocalToGlobalTransform(new PAffineTransform()).createTransformedShape(aChild.getBounds()); // dimensions - PDimension dim = new PDimension(50, 50); + final PDimension dim = new PDimension(50, 50); aChild.localToGlobal(dim); assertEquals(25, dim.getHeight(), 0); @@ -243,12 +243,12 @@ } public void testToString() { - PNode a = new PNode(); - PNode b = new PNode(); - PNode c = new PNode(); - PNode d = new PNode(); - PNode e = new PNode(); - PNode f = new PNode(); + final PNode a = new PNode(); + final PNode b = new PNode(); + final PNode c = new PNode(); + final PNode d = new PNode(); + final PNode e = new PNode(); + final PNode f = new PNode(); a.translate(100, 100); a.getFullBoundsReference(); @@ -263,7 +263,12 @@ } public void testRecursiveLayout() { - PNode layoutNode1 = new PNode() { + final PNode layoutNode1 = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; + protected void layoutChildren() { if (getChildrenCount() > 0) { getChild(0).setOffset(1, 0); @@ -271,7 +276,12 @@ } }; - PNode layoutNode2 = new PNode() { + final PNode layoutNode2 = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; + protected void layoutChildren() { if (getChildrenCount() > 0) { getChild(0).setOffset(1, 0); @@ -281,7 +291,7 @@ layoutNode1.addChild(layoutNode2); - PNode n = new PNode(); + final PNode n = new PNode(); n.setBounds(0, 0, 100, 100); layoutNode2.addChild(n); @@ -294,10 +304,10 @@ public void testAnimateToBoundsWithDuration0IsImmediate() { node.setBounds(0, 0, 100, 100); - PActivity activity = node.animateToBounds(50, 50, 150, 150, 0); + final PActivity activity = node.animateToBounds(50, 50, 150, 150, 0); assertNull(activity); - PBounds resultBounds = node.getBounds(); + final PBounds resultBounds = node.getBounds(); assertEquals(50.0, resultBounds.x, 0.001); assertEquals(50.0, resultBounds.y, 0.001); assertEquals(150.0, resultBounds.width, 0.001); @@ -306,7 +316,7 @@ public void testAnimateToBoundsHasProperSetup() { node.setBounds(0, 0, 100, 100); - PInterpolatingActivity activity = node.animateToBounds(50, 50, 150, 150, 50); + final PInterpolatingActivity activity = node.animateToBounds(50, 50, 150, 150, 50); assertEquals(50, activity.getDuration()); assertEquals(PUtil.DEFAULT_ACTIVITY_STEP_RATE, activity.getStepRate()); @@ -316,24 +326,24 @@ public void testAnimateTransformToBoundsWithDuration0IsImmediate() { node.setBounds(0, 0, 100, 100); - PActivity activity = node.animateTransformToBounds(0, 0, 10, 10, 0); + final PActivity activity = node.animateTransformToBounds(0, 0, 10, 10, 0); assertNull(activity); - PAffineTransform transform = node.getTransform(); + final PAffineTransform transform = node.getTransform(); assertEquals(0.1, transform.getScale(), 0.0001); } public void testAnimateTransformToBoundsHasProperSetup() { node.setBounds(0, 0, 100, 100); - PTransformActivity activity = node.animateTransformToBounds(0, 0, 10, 10, 50); + final PTransformActivity activity = node.animateTransformToBounds(0, 0, 10, 10, 50); assertEquals(50, activity.getDuration()); assertEquals(PUtil.DEFAULT_ACTIVITY_STEP_RATE, activity.getStepRate()); assertTrue(activity.getFirstLoop()); assertFalse(activity.isStepping()); - double[] resultTransform = activity.getDestinationTransform(); + final double[] resultTransform = activity.getDestinationTransform(); assertEquals(0.1, resultTransform[0], 0.001); assertEquals(0, resultTransform[1], 0.001); @@ -345,13 +355,13 @@ public void testAnimateToPositionScaleRotationWithDuration0IsImmediate() { node.setBounds(0, 0, 100, 100); - PActivity activity = node.animateToPositionScaleRotation(50, 50, 0.5, Math.PI, 0); + final PActivity activity = node.animateToPositionScaleRotation(50, 50, 0.5, Math.PI, 0); assertNull(activity); - PAffineTransform resultTransform = node.getTransform(); + final PAffineTransform resultTransform = node.getTransform(); - PAffineTransform expected = new PAffineTransform(); + final PAffineTransform expected = new PAffineTransform(); expected.translate(50, 50); expected.scale(0.5, 0.5); expected.rotate(Math.PI); @@ -361,16 +371,16 @@ public void testAnimateToPositionScaleRotationHasProperSetup() { node.setBounds(0, 0, 100, 100); - PTransformActivity activity = node.animateToPositionScaleRotation(50, 50, 0.5, Math.PI, 50); + final PTransformActivity activity = node.animateToPositionScaleRotation(50, 50, 0.5, Math.PI, 50); assertEquals(50, activity.getDuration()); assertEquals(PUtil.DEFAULT_ACTIVITY_STEP_RATE, activity.getStepRate()); assertTrue(activity.getFirstLoop()); assertFalse(activity.isStepping()); - double[] resultTransform = activity.getDestinationTransform(); + final double[] resultTransform = activity.getDestinationTransform(); - PAffineTransform expected = new PAffineTransform(); + final PAffineTransform expected = new PAffineTransform(); expected.translate(50, 50); expected.scale(0.5, 0.5); expected.rotate(Math.PI); @@ -386,7 +396,7 @@ public void testAnimateToColorWithDuration0IsImmediate() { node.setPaint(Color.WHITE); - PActivity activity = node.animateToColor(Color.BLACK, 0); + final PActivity activity = node.animateToColor(Color.BLACK, 0); assertNull(activity); @@ -395,7 +405,7 @@ public void testAnimateToColorHasProperSetup() { node.setPaint(Color.WHITE); - PInterpolatingActivity activity = node.animateToColor(Color.BLACK, 50); + final PInterpolatingActivity activity = node.animateToColor(Color.BLACK, 50); assertEquals(50, activity.getDuration()); assertEquals(PUtil.DEFAULT_ACTIVITY_STEP_RATE, activity.getStepRate()); @@ -406,11 +416,11 @@ } public void testAddActivityAddsActivityToScheduler() { - PCanvas canvas = new PCanvas(); + final PCanvas canvas = new PCanvas(); node.setPaint(Color.WHITE); canvas.getLayer().addChild(node); - PColorActivity activity = buildTestActivity(); + final PColorActivity activity = buildTestActivity(); node.addActivity(activity); @@ -418,25 +428,25 @@ } private PColorActivity buildTestActivity() { - Target testTarget = new PColorActivity.Target() { + final Target testTarget = new PColorActivity.Target() { public Color getColor() { return Color.BLACK; } - public void setColor(Color color) { + public void setColor(final Color color) { } }; - PColorActivity activity = new PColorActivity(1000, 0, testTarget, Color.BLACK); + final PColorActivity activity = new PColorActivity(1000, 0, testTarget, Color.BLACK); return activity; } public void testAnimateToTransparencyWithDuration0IsImmediate() { node.setPaint(Color.WHITE); - PActivity activity = node.animateToTransparency(0.5f, 0); + final PActivity activity = node.animateToTransparency(0.5f, 0); assertNull(activity); @@ -444,7 +454,7 @@ } public void testAnimateToTransparencyHasProperSetup() { - PInterpolatingActivity activity = node.animateToTransparency(0f, 50); + final PInterpolatingActivity activity = node.animateToTransparency(0f, 50); assertEquals(50, activity.getDuration()); assertEquals(PUtil.DEFAULT_ACTIVITY_STEP_RATE, activity.getStepRate()); @@ -455,26 +465,26 @@ } public void testGetClientPropertiesShouldReturnSetEvenIfNonePresent() { - MutableAttributeSet properties = node.getClientProperties(); + final MutableAttributeSet properties = node.getClientProperties(); assertNotNull(properties); assertEquals(0, properties.getAttributeCount()); } public void testGetClientPropertiesShouldReturnSameCollectionAlways() { - MutableAttributeSet properties1 = node.getClientProperties(); - MutableAttributeSet properties2 = node.getClientProperties(); + final MutableAttributeSet properties1 = node.getClientProperties(); + final MutableAttributeSet properties2 = node.getClientProperties(); assertSame(properties1, properties2); } public void testGetClientPropertyKeysEnumerationShouldReturnEnumarationOnNewNode() { - Enumeration enumeration = node.getClientPropertyKeysEnumeration(); + final Enumeration enumeration = node.getClientPropertyKeysEnumeration(); assertNotNull(enumeration); assertFalse(enumeration.hasMoreElements()); } public void testGetClientPropertyKeysEnumerationShouldReturnCorrectEnumWhenPropertiesExist() { node.addAttribute("Testing", "Hello"); - Enumeration enumeration = node.getClientPropertyKeysEnumeration(); + final Enumeration enumeration = node.getClientPropertyKeysEnumeration(); assertNotNull(enumeration); assertTrue(enumeration.hasMoreElements()); assertEquals("Testing", enumeration.nextElement()); @@ -533,7 +543,7 @@ } public void testGetClientPropertyKeysIteratorIsNotNullOnEmptyClientProperties() { - Iterator iterator = node.getClientPropertyKeysIterator(); + final Iterator iterator = node.getClientPropertyKeysIterator(); assertNotNull(iterator); assertFalse(iterator.hasNext()); } @@ -541,7 +551,7 @@ public void testGetClientPropertyKeysIteratorReturnsValidIteraotOnPropertiesExist() { node.addClientProperty("A", "Aval"); node.addClientProperty("B", "Bval"); - Iterator iterator = node.getClientPropertyKeysIterator(); + final Iterator iterator = node.getClientPropertyKeysIterator(); assertNotNull(iterator); assertTrue(iterator.hasNext()); assertEquals("A", iterator.next()); @@ -551,12 +561,12 @@ } public void testLocalToParentModifiesGivenPoint() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); node.scale(0.5); - Point2D point = new Point2D.Double(5, 6); + final Point2D point = new Point2D.Double(5, 6); node.localToParent(point); assertTrue(5 != point.getX()); assertTrue(6 != point.getY()); @@ -565,53 +575,53 @@ public void testLocalToParentDoesWorkWithOrphanChildWhenTransformed() { node.scale(0.5); - Point2D point = new Point2D.Double(5, 6); + final Point2D point = new Point2D.Double(5, 6); node.localToParent(point); assertTrue(5 != point.getX()); assertTrue(6 != point.getY()); } public void testLocalToParentDoesNothingWithOrphanChildWhenNotTransformed() { - Point2D point = new Point2D.Double(5, 6); + final Point2D point = new Point2D.Double(5, 6); node.localToParent(point); assertEquals(5, point.getX(), 0.0001); assertEquals(6, point.getY(), 0.0001); } public void testParentToLocalModifiesGivenPoint() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); node.scale(0.5); - Point2D point = new Point2D.Double(5, 6); + final Point2D point = new Point2D.Double(5, 6); node.parentToLocal(point); assertTrue(5 != point.getX()); assertTrue(6 != point.getY()); } public void testParentToLocalTransformsOrphanChildWhenTransformed() { - PNode aChild = new PNode(); + final PNode aChild = new PNode(); aChild.scale(0.5); - Point2D point = new Point2D.Double(5, 6); + final Point2D point = new Point2D.Double(5, 6); aChild.parentToLocal(point); assertEquals(10, point.getX(), 0.0001); assertEquals(12, point.getY(), 0.0001); } public void testGlobalToLocalWorksUnTransformedNodes() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); - Point2D point = new Point2D.Double(10, 11); + final Point2D point = new Point2D.Double(10, 11); node.globalToLocal(point); assertEquals(10, point.getX(), 0.0001); assertEquals(11, point.getY(), 0.0001); } public void testRemoveEventListener() { - PBasicInputEventHandler eventListener = new PBasicInputEventHandler(); + final PBasicInputEventHandler eventListener = new PBasicInputEventHandler(); node.addInputEventListener(eventListener); assertEquals(1, node.getListenerList().getListenerCount()); node.removeInputEventListener(eventListener); @@ -646,16 +656,16 @@ } public void testPropertyChangesCascadeToParent() { - PNode aParent = new PNode(); + final PNode aParent = new PNode(); aParent.addPropertyChangeListener(PNode.PROPERTY_BOUNDS, mockListener); - PNode aChild = new PNode(); + final PNode aChild = new PNode(); aChild.setPropertyChangeParentMask(PNode.PROPERTY_CODE_BOUNDS); aParent.addChild(aChild); aChild.setBounds(0, 0, 100, 100); assertEquals(1, mockListener.getPropertyChangeCount()); - PropertyChangeEvent propEvent = mockListener.getPropertyChange(0); + final PropertyChangeEvent propEvent = mockListener.getPropertyChange(0); assertEquals(PNode.PROPERTY_BOUNDS, propEvent.getPropertyName()); assertEquals(new PBounds(0, 0, 100, 100), propEvent.getNewValue()); } @@ -689,7 +699,7 @@ node.setBounds(10, 15, 100, 115); node.resetBounds(); - PBounds zeroBounds = new PBounds(); + final PBounds zeroBounds = new PBounds(); assertEquals(zeroBounds, node.getBounds()); } @@ -697,28 +707,28 @@ node.setBounds(0, 0, 100, 100); node.centerBoundsOnPoint(0, 0); - PBounds expected = new PBounds(-50, -50, 100, 100); + final PBounds expected = new PBounds(-50, -50, 100, 100); assertEquals(expected, node.getBounds()); } public void testCenterFullBoundsOnPointWorksAsExpected() { - PNode aParent = buildComplexSquareNode(); + final PNode aParent = buildComplexSquareNode(); aParent.centerFullBoundsOnPoint(0, 0); - PBounds expected = new PBounds(-50, -50, 100, 100); + final PBounds expected = new PBounds(-50, -50, 100, 100); assertEquals(expected, aParent.getFullBounds()); } private PNode buildComplexSquareNode() { - PNode aParent = new PNode(); + final PNode aParent = new PNode(); aParent.setBounds(0, 0, 50, 100); - PNode child1 = new PNode(); + final PNode child1 = new PNode(); child1.setBounds(50, 0, 50, 50); aParent.addChild(child1); - PNode child2 = new PNode(); + final PNode child2 = new PNode(); child2.setBounds(50, 50, 50, 50); aParent.addChild(child2); @@ -726,24 +736,24 @@ } public void testGetUnionOfChildrenBoundsAcceptsNull() { - PNode node = buildComplexSquareNode(); + final PNode node = buildComplexSquareNode(); - PBounds union = node.getUnionOfChildrenBounds(null); + final PBounds union = node.getUnionOfChildrenBounds(null); assertNotNull(union); assertEquals(new PBounds(50, 0, 50, 100), union); } public void testGetGlobalFullBoundsIsSameWhenNoTransforms() { - PNode parent = new PNode(); - PNode child = new PNode(); + final PNode parent = new PNode(); + final PNode child = new PNode(); parent.addChild(child); - PNode grandChild = new PNode(); + final PNode grandChild = new PNode(); child.addChild(grandChild); child.setBounds(50, 0, 50, 50); grandChild.setBounds(0, 50, 50, 50); - PBounds globalFullBounds = parent.getGlobalFullBounds(); + final PBounds globalFullBounds = parent.getGlobalFullBounds(); assertNotNull(globalFullBounds); assertEquals(new PBounds(0, 0, 100, 100), globalFullBounds); @@ -775,7 +785,7 @@ node.setBounds(25, 25, 50, 50); node.rotateAboutPoint(Math.PI, 50, 0); // It's top center point - PAffineTransform expectedTransform = new PAffineTransform(); + final PAffineTransform expectedTransform = new PAffineTransform(); expectedTransform.translate(100, 0); expectedTransform.rotate(Math.PI); @@ -788,7 +798,7 @@ // center // point - PAffineTransform expectedTransform = new PAffineTransform(); + final PAffineTransform expectedTransform = new PAffineTransform(); expectedTransform.translate(100, 0); expectedTransform.rotate(Math.PI); @@ -798,7 +808,7 @@ public void testScaleAboutPointWorksAsExpected() { node.setBounds(0, 0, 100, 100); node.scaleAboutPoint(2, new Point2D.Double(50, 50)); - PAffineTransform expectedTransform = new PAffineTransform(); + final PAffineTransform expectedTransform = new PAffineTransform(); expectedTransform.translate(-50, -50); expectedTransform.scale(2, 2); @@ -807,17 +817,17 @@ public void testRotateInPlaneLeavesFullBoundsUntouched() { node.setBounds(25, 25, 50, 50); - PBounds boundsBefore = node.getFullBounds(); + final PBounds boundsBefore = node.getFullBounds(); node.rotateInPlace(Math.PI); assertEquals(boundsBefore, node.getFullBounds()); } public void testSetGlobalScaleTakesParentsScaleIntoAccount() { - PNode aParent = new PNode(); + final PNode aParent = new PNode(); aParent.scale(2); - PNode aChild = new PNode(); + final PNode aChild = new PNode(); aParent.addChild(aChild); aChild.setGlobalScale(1); @@ -833,10 +843,10 @@ } public void testTransformByIsCummulative() { - node.transformBy(PAffineTransform.getScaleInstance(2, 2)); - node.transformBy(PAffineTransform.getScaleInstance(2, 2)); + node.transformBy(AffineTransform.getScaleInstance(2, 2)); + node.transformBy(AffineTransform.getScaleInstance(2, 2)); - assertEquals(PAffineTransform.getScaleInstance(4, 4), node.getTransform()); + assertEquals(AffineTransform.getScaleInstance(4, 4), node.getTransform()); } public void testLerp() { @@ -846,20 +856,20 @@ } public void testAnimateToRelativePositionResultsInProperTransform() { - PCanvas canvas = new PCanvas(); - PNode A = new PNode(); + final PCanvas canvas = new PCanvas(); + final PNode A = new PNode(); A.setBounds(0, 0, 50, 50); canvas.getLayer().addChild(A); - PNode B = new PNode(); + final PNode B = new PNode(); B.setBounds(0, 0, 100, 100); B.setOffset(100, 100); canvas.getLayer().addChild(B); - Point2D srcPt = new Point2D.Double(1.0, 0.0); - Point2D destPt = new Point2D.Double(0.0, 0.0); + final Point2D srcPt = new Point2D.Double(1.0, 0.0); + final Point2D destPt = new Point2D.Double(0.0, 0.0); A.animateToRelativePosition(srcPt, destPt, B.getGlobalBounds(), 0); - PAffineTransform expectedTransform = new PAffineTransform(); + final PAffineTransform expectedTransform = new PAffineTransform(); expectedTransform.translate(50, 100); assertEquals(expectedTransform, A.getTransform()); @@ -869,7 +879,7 @@ node.translate(50, 50); node.rotate(Math.PI); - PAffineTransform expectedTransform = new PAffineTransform(); + final PAffineTransform expectedTransform = new PAffineTransform(); expectedTransform.rotate(-Math.PI); expectedTransform.translate(-50, -50); assertEquals(expectedTransform, node.getInverseTransform()); @@ -881,7 +891,8 @@ try { node.getInverseTransform(); fail("Exception not thrown"); - } catch (PAffineTransformException e) { + } + catch (final PAffineTransformException e) { // expected } } @@ -889,18 +900,23 @@ public void testSetVisibleIsRespectedOnPaint() { final int[] paintCounts = new int[1]; - PNode node = new PNode() { - public void paint(PPaintContext pc) { + final PNode node = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void paint(final PPaintContext pc) { paintCounts[0]++; } }; node.setBounds(0, 0, 100, 100); node.setVisible(true); - PCanvas canvas = buildCanvasContainingNode(node); + final PCanvas canvas = buildCanvasContainingNode(node); - BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); - Graphics g = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); + final BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + final Graphics g = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); canvas.paintComponent(g); @@ -917,21 +933,21 @@ assertEquals(2, paintCounts[0]); } - private PCanvas buildCanvasContainingNode(PNode node) { - PCanvas canvas = new PCanvas(); + private PCanvas buildCanvasContainingNode(final PNode node) { + final PCanvas canvas = new PCanvas(); canvas.setSize(100, 100); canvas.getLayer().addChild(node); return canvas; } public void testPaintColourIsRespectedOnPaint() { - BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); - Graphics g = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); + final BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + final Graphics g = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); node.setPaint(Color.RED); node.setBounds(0, 0, 100, 100); - PCanvas canvas = buildCanvasContainingNode(node); + final PCanvas canvas = buildCanvasContainingNode(node); canvas.paintComponent(g); assertEquals(Color.RED.getRGB(), img.getRGB(0, 0)); @@ -943,7 +959,7 @@ // Really don't like casting here, but... without changing the // interface, I don't see a choice - BufferedImage img = (BufferedImage) node.toImage(); + final BufferedImage img = (BufferedImage) node.toImage(); assertEquals(10, img.getHeight(null)); assertEquals(10, img.getWidth(null)); @@ -956,14 +972,14 @@ public void testToImageWillAcceptBackgroundPaint() { node.setBounds(0, 0, 10, 10); - BufferedImage img = (BufferedImage) node.toImage(10, 10, Color.BLUE); + final BufferedImage img = (BufferedImage) node.toImage(10, 10, Color.BLUE); assertEquals(Color.BLUE.getRGB(), img.getRGB(5, 5)); } public void testToImageResultsInDesiredSizeImage() { node.setBounds(0, 0, 10, 10); - BufferedImage img = (BufferedImage) node.toImage(20, 40, null); + final BufferedImage img = (BufferedImage) node.toImage(20, 40, null); assertEquals(40, img.getHeight(null)); assertEquals(20, img.getWidth(null)); } @@ -972,7 +988,7 @@ node.setBounds(0, 0, 10, 10); node.setPaint(Color.RED); - BufferedImage img = (BufferedImage) node.toImage(20, 40, Color.BLUE); + final BufferedImage img = (BufferedImage) node.toImage(20, 40, Color.BLUE); assertEquals(Color.RED.getRGB(), img.getRGB(0, 0)); assertEquals(Color.BLUE.getRGB(), img.getRGB(15, 25)); } @@ -981,7 +997,7 @@ node.setBounds(0, 0, 10, 10); node.setPaint(Color.RED); - BufferedImage img = (BufferedImage) node.toImage(20, 40, Color.BLUE); + final BufferedImage img = (BufferedImage) node.toImage(20, 40, Color.BLUE); assertEquals(Color.RED.getRGB(), img.getRGB(0, 0)); assertEquals(Color.RED.getRGB(), img.getRGB(19, 0)); @@ -1012,39 +1028,39 @@ } public void testByDefaultNodesShouldNotPickThemselvesBeforeTheirChildren() { - PCanvas canvas = new PCanvas(); - PPickPath pickPath = new PPickPath(canvas.getCamera(), new PBounds(0, 0, 100, 100)); + final PCanvas canvas = new PCanvas(); + final PPickPath pickPath = new PPickPath(canvas.getCamera(), new PBounds(0, 0, 100, 100)); assertFalse(node.pick(pickPath)); } public void testfullPickReturnsTrueWhenOverlapsWithChildNode() { - PCanvas canvas = new PCanvas(); + final PCanvas canvas = new PCanvas(); node.setBounds(0, 0, 10, 10); - PNode child = new PNode(); + final PNode child = new PNode(); child.setBounds(20, 0, 10, 10); node.addChild(child); - PPickPath pickPath = new PPickPath(canvas.getCamera(), new PBounds(20, 0, 10, 10)); + final PPickPath pickPath = new PPickPath(canvas.getCamera(), new PBounds(20, 0, 10, 10)); canvas.getLayer().addChild(node); assertTrue(node.fullPick(pickPath)); } public void testfullPickReturnsFalseWhenNotOverlappingWithChildNode() { - PCanvas canvas = new PCanvas(); + final PCanvas canvas = new PCanvas(); node.setBounds(0, 0, 10, 10); - PNode child = new PNode(); + final PNode child = new PNode(); child.setBounds(10, 0, 10, 10); node.addChild(child); - PPickPath pickPath = new PPickPath(canvas.getCamera(), new PBounds(20, 0, 10, 10)); + final PPickPath pickPath = new PPickPath(canvas.getCamera(), new PBounds(20, 0, 10, 10)); canvas.getLayer().addChild(node); assertFalse(node.fullPick(pickPath)); } public void testAddChildrenAddsAllChildren() { - Collection newChildren = new ArrayList(); + final Collection newChildren = new ArrayList(); newChildren.add(new PNode()); newChildren.add(new PNode()); newChildren.add(new PNode()); @@ -1055,7 +1071,7 @@ } public void testRemoveChildrenWorks() { - Collection newChildren = new ArrayList(); + final Collection newChildren = new ArrayList(); newChildren.add(new PNode()); newChildren.add(new PNode()); newChildren.add(new PNode()); @@ -1067,7 +1083,7 @@ } public void testGetAllNodesUnrollsTheNodeGraph() { - Collection newChildren = new ArrayList(); + final Collection newChildren = new ArrayList(); newChildren.add(new PNode()); newChildren.add(new PNode()); newChildren.add(new PNode()); @@ -1087,7 +1103,7 @@ } public void testRemoveFromParentDoesSo() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); node.removeFromParent(); @@ -1096,10 +1112,10 @@ } public void testReplaceWithSwapsParents() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); - PNode newNode = new PNode(); + final PNode newNode = new PNode(); node.replaceWith(newNode); assertNull(node.getParent()); @@ -1107,16 +1123,16 @@ } public void testGetChildrenIteratorReturnsIteratorEvenWithNoChildren() { - ListIterator iterator = node.getChildrenIterator(); + final ListIterator iterator = node.getChildrenIterator(); assertNotNull(iterator); assertFalse(iterator.hasNext()); } public void testGetChildrenIteratorReturnsValidIteratorWhenHasChildren() { - PNode child = new PNode(); + final PNode child = new PNode(); node.addChild(child); - ListIterator iterator = node.getChildrenIterator(); + final ListIterator iterator = node.getChildrenIterator(); assertNotNull(iterator); assertTrue(iterator.hasNext()); assertEquals(child, iterator.next()); @@ -1124,13 +1140,13 @@ } public void testGetAllNodesDoesntIgnoreFilter() { - PNodeFilter nullFilter = new PNodeFilter() { + final PNodeFilter nullFilter = new PNodeFilter() { - public boolean accept(PNode aNode) { + public boolean accept(final PNode aNode) { return false; } - public boolean acceptChildrenOf(PNode aNode) { + public boolean acceptChildrenOf(final PNode aNode) { return true; } }; @@ -1138,19 +1154,19 @@ node.addChild(new PNode()); node.addChild(new PNode()); node.addChild(new PNode()); - Collection nodes = node.getAllNodes(nullFilter, null); + final Collection nodes = node.getAllNodes(nullFilter, null); assertNotNull(nodes); assertTrue(nodes.isEmpty()); } public void testAncestryMethods() { - PNode child = new PNode(); + final PNode child = new PNode(); node.addChild(child); - PNode grandChild = new PNode(); + final PNode grandChild = new PNode(); child.addChild(grandChild); - PNode unrelated = new PNode(); + final PNode unrelated = new PNode(); assertTrue(node.isAncestorOf(child)); assertTrue(node.isAncestorOf(grandChild)); @@ -1162,7 +1178,7 @@ } public void testMoveToBackMovesNodeToBeFirstChild() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(new PNode()); parent.addChild(new PNode()); parent.addChild(node); @@ -1171,7 +1187,7 @@ } public void testMoveToFrontMovesNodeToBeLastChild() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.addChild(node); parent.addChild(new PNode()); parent.addChild(new PNode()); @@ -1180,8 +1196,8 @@ } public void testMoveInBackOfMovesNodeToBeforeSibling() { - PNode parent = new PNode(); - PNode sibling = new PNode(); + final PNode parent = new PNode(); + final PNode sibling = new PNode(); parent.addChild(node); parent.addChild(new PNode()); @@ -1193,8 +1209,8 @@ } public void testMoveInFrontOfMovesNodeToAfterSibling() { - PNode parent = new PNode(); - PNode sibling = new PNode(); + final PNode parent = new PNode(); + final PNode sibling = new PNode(); parent.addChild(node); parent.addChild(new PNode()); @@ -1206,8 +1222,8 @@ } public void testMoveInFrontOfDoesNothingIfNotSibling() { - PNode parent = new PNode(); - PNode stranger = new PNode(); + final PNode parent = new PNode(); + final PNode stranger = new PNode(); parent.addChild(node); parent.addChild(new PNode()); @@ -1218,8 +1234,8 @@ } public void testMoveInBackOfDoesNothingIfNotSibling() { - PNode parent = new PNode(); - PNode stranger = new PNode(); + final PNode parent = new PNode(); + final PNode stranger = new PNode(); parent.addChild(node); parent.addChild(new PNode()); @@ -1230,7 +1246,7 @@ } public void testIsDescendentOfRootHandlesOrphans() { - PNode orphan = new PNode(); + final PNode orphan = new PNode(); assertFalse(orphan.isDescendentOfRoot()); orphan.addChild(node); @@ -1238,14 +1254,14 @@ } public void testIsDescendentOfRootHandlesDescendentsOfRoot() { - PCanvas canvas = new PCanvas(); + final PCanvas canvas = new PCanvas(); canvas.getLayer().addChild(node); assertTrue(node.isDescendentOfRoot()); } public void testGetGlobalRationTakesParentsIntoAccount() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.rotate(Math.PI / 4d); parent.addChild(node); @@ -1255,7 +1271,7 @@ } public void testSetGlobalRationTakesParentsIntoAccount() { - PNode parent = new PNode(); + final PNode parent = new PNode(); parent.rotate(Math.PI / 4d); parent.addChild(node); diff --git a/core/src/test/java/edu/umd/cs/piccolo/PRootTest.java b/core/src/test/java/edu/umd/cs/piccolo/PRootTest.java index 57c9b13..4306030 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PRootTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PRootTest.java @@ -8,7 +8,7 @@ import junit.framework.TestCase; import edu.umd.cs.piccolo.activities.PActivity; -public class PRootTest extends TestCase { +public class PRootTest extends TestCase { private PRoot root; private MockPropertyChangeListener mockListener; @@ -32,7 +32,7 @@ public void testAddInputSourceFirePropertyChangeEvent() { root.addPropertyChangeListener(PRoot.PROPERTY_INPUT_SOURCES, mockListener); - PRoot.InputSource newSource = new PRoot.InputSource() { + final PRoot.InputSource newSource = new PRoot.InputSource() { public void processInput() { } @@ -43,23 +43,23 @@ } public void testCreateTimerReturnsATimer() { - Timer timer = root.createTimer(1, new ActionListener() { - public void actionPerformed(ActionEvent arg0) { + final Timer timer = root.createTimer(1, new ActionListener() { + public void actionPerformed(final ActionEvent arg0) { } }); assertNotNull(timer); } public void testCreateTimerReturnsATimerWhenDelayIs0() { - Timer timer = root.createTimer(0, new ActionListener() { - public void actionPerformed(ActionEvent arg0) { + final Timer timer = root.createTimer(0, new ActionListener() { + public void actionPerformed(final ActionEvent arg0) { } }); assertNotNull(timer); } public void testRemoveInputSourceDoesNothingIfStranger() { - PRoot.InputSource strangeSource = new PRoot.InputSource() { + final PRoot.InputSource strangeSource = new PRoot.InputSource() { public void processInput() { } @@ -72,43 +72,43 @@ assertFalse(0 == root.getGlobalTime()); } - public void testProcessInputDelegatesToInputSources() { - MockInputSource newSource = new MockInputSource(); + public void testProcessInputDelegatesToInputSources() { + final MockInputSource newSource = new MockInputSource(); root.addInputSource(newSource); root.processInputs(); assertEquals(1, newSource.getProcessInputCalls()); } - + public void testProcessInputProcessesActivities() { - MockPActivity activity = new MockPActivity(100); + final MockPActivity activity = new MockPActivity(100); root.addActivity(activity); root.processInputs(); assertTrue(activity.isActivityStarted()); - - } - + + } + public void testSetFullBoundsInvalidPerists() { root.setFullBoundsInvalid(true); assertTrue(root.getFullBoundsInvalid()); } - + public void testSetChildBoundsInvalidPerists() { root.setChildBoundsInvalid(true); assertTrue(root.getChildBoundsInvalid()); } - + public void testSetPaintInvalidPersists() { root.setPaintInvalid(true); assertTrue(root.getPaintInvalid()); } - + public void testSetChildPaintInvalidPersists() { root.setChildPaintInvalid(true); assertTrue(root.getChildPaintInvalid()); } - + public void testWaitForActivitiesDoesSo() { - MockPActivity activity = new MockPActivity(1); + final MockPActivity activity = new MockPActivity(1); root.addActivity(activity); root.waitForActivities(); assertTrue(activity.isActivityFished()); @@ -120,17 +120,17 @@ public int getProcessInputCalls() { return processInputCalls; } - + public void processInput() { - processInputCalls ++; + processInputCalls++; } } - + private static final class MockPActivity extends PActivity { private boolean activityStarted; private boolean activityFinished; - private MockPActivity(long aDuration) { + private MockPActivity(final long aDuration) { super(aDuration); } @@ -143,12 +143,12 @@ } protected void activityStarted() { - this.activityStarted = true; + activityStarted = true; super.activityStarted(); } - + protected void activityFinished() { - this.activityFinished = true; + activityFinished = true; super.activityFinished(); } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/PerformanceLog.java b/core/src/test/java/edu/umd/cs/piccolo/PerformanceLog.java index ccf3132..dd19a34 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PerformanceLog.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PerformanceLog.java @@ -33,14 +33,14 @@ public class PerformanceLog { - private ArrayList log = new ArrayList(); + private final ArrayList log = new ArrayList(); private long testTime; public static class ZLogEntry { public String name; public long time; - public ZLogEntry(String aName, long aTime) { + public ZLogEntry(final String aName, final long aTime) { name = aName; time = aTime; } @@ -51,13 +51,13 @@ testTime = System.currentTimeMillis(); } - public void endTest(String name) { + public void endTest(final String name) { testTime = System.currentTimeMillis() - testTime; addEntry(name, testTime); System.gc(); } - public void addEntry(String aName, long aTime) { + public void addEntry(final String aName, final long aTime) { log.add(new ZLogEntry(aName, aTime)); } @@ -73,7 +73,7 @@ Iterator i = log.iterator(); while (i.hasNext()) { - ZLogEntry each = (ZLogEntry) i.next(); + final ZLogEntry each = (ZLogEntry) i.next(); System.out.println(each.time); } @@ -83,7 +83,7 @@ i = log.iterator(); while (i.hasNext()) { - ZLogEntry each = (ZLogEntry) i.next(); + final ZLogEntry each = (ZLogEntry) i.next(); System.out.println(each.name + ", " + each.time); } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/PerformanceTests.java b/core/src/test/java/edu/umd/cs/piccolo/PerformanceTests.java index 7d469b6..c8b8311 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PerformanceTests.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PerformanceTests.java @@ -50,13 +50,14 @@ private static PerformanceLog log = new PerformanceLog(); private static int NUMBER_NODES = 20000; - public PerformanceTests(String name) { + public PerformanceTests(final String name) { super(name); } public void testRunPerformanceTests() { - if (1 == 1) + if (1 == 1) { return; + } // three times to warm up JVM for (int i = 0; i < 3; i++) { @@ -78,7 +79,7 @@ } public void createNodes() { - PNode[] nodes = new PNode[NUMBER_NODES]; + final PNode[] nodes = new PNode[NUMBER_NODES]; log.startTest(); for (int i = 0; i < NUMBER_NODES; i++) { @@ -88,7 +89,7 @@ } public void createPaths() { - PNode[] nodes = new PNode[NUMBER_NODES]; + final PNode[] nodes = new PNode[NUMBER_NODES]; log.startTest(); for (int i = 0; i < NUMBER_NODES; i++) { @@ -96,15 +97,15 @@ } log.endTest("Create " + NUMBER_NODES + " new rect paths"); - Random r = new Random(); + final Random r = new Random(); for (int i = 0; i < NUMBER_NODES; i++) { nodes[i].translate(r.nextFloat() * 300, r.nextFloat() * 300); } } public void addNodes() { - PNode parent = new PNode(); - PNode[] nodes = new PNode[NUMBER_NODES]; + final PNode parent = new PNode(); + final PNode[] nodes = new PNode[NUMBER_NODES]; for (int i = 0; i < NUMBER_NODES; i++) { nodes[i] = new PNode(); @@ -118,9 +119,9 @@ } public void removeNodes() { - PNode parent = new PNode(); - PNode[] nodes = new PNode[NUMBER_NODES]; - ArrayList list = new ArrayList(); + final PNode parent = new PNode(); + final PNode[] nodes = new PNode[NUMBER_NODES]; + final ArrayList list = new ArrayList(); for (int i = 0; i < NUMBER_NODES; i++) { nodes[i] = new PNode(); @@ -165,10 +166,10 @@ } public void translateNodes() { - PNode parent = new PNode(); - PNode[] nodes = new PNode[NUMBER_NODES]; - PBounds b = new PBounds(); - Random r = new Random(); + final PNode parent = new PNode(); + final PNode[] nodes = new PNode[NUMBER_NODES]; + final PBounds b = new PBounds(); + final Random r = new Random(); for (int i = 0; i < NUMBER_NODES; i++) { nodes[i] = new PNode(); @@ -202,9 +203,9 @@ } public void fullIntersectsNodes() { - PNode parent = new PNode(); - PNode[] nodes = new PNode[NUMBER_NODES]; - PBounds b = new PBounds(0, 50, 100, 20); + final PNode parent = new PNode(); + final PNode[] nodes = new PNode[NUMBER_NODES]; + final PBounds b = new PBounds(0, 50, 100, 20); for (int i = 0; i < NUMBER_NODES; i++) { nodes[i] = new PNode(); @@ -223,10 +224,10 @@ } public void memorySizeOfNodes() { - PNode[] nodes = new PNode[NUMBER_NODES]; + final PNode[] nodes = new PNode[NUMBER_NODES]; Runtime.getRuntime().gc(); - long startTotalMemory = Runtime.getRuntime().totalMemory(); - long startFree = Runtime.getRuntime().freeMemory(); + final long startTotalMemory = Runtime.getRuntime().totalMemory(); + final long startFree = Runtime.getRuntime().freeMemory(); long endFree; long endTotal; @@ -239,13 +240,13 @@ endTotal = Runtime.getRuntime().totalMemory(); log.addEntry("Approximate k used by " + NUMBER_NODES + " nodes", - ((endTotal - startTotalMemory) + (startFree - endFree)) / 1024); + (endTotal - startTotalMemory + startFree - endFree) / 1024); nodes[0].getPaint(); } public void copyNodes() { - PNode parent = new PNode(); - PNode[] nodes = new PNode[NUMBER_NODES]; + final PNode parent = new PNode(); + final PNode[] nodes = new PNode[NUMBER_NODES]; for (int i = 0; i < NUMBER_NODES; i++) { nodes[i] = new PNode(); @@ -258,10 +259,10 @@ } public void costOfNoBoundsCache() { - PNode[] nodes = new PNode[NUMBER_NODES]; - PBounds[] bounds = new PBounds[NUMBER_NODES]; - PBounds pickRect = new PBounds(0, 0, 1, 1); - Random r = new Random(); + final PNode[] nodes = new PNode[NUMBER_NODES]; + final PBounds[] bounds = new PBounds[NUMBER_NODES]; + final PBounds pickRect = new PBounds(0, 0, 1, 1); + final Random r = new Random(); for (int i = 0; i < NUMBER_NODES; i++) { nodes[i] = new PNode(); @@ -288,7 +289,7 @@ } log.endTest("Sum " + NUMBER_NODES + " bounds"); - PBounds b = new PBounds(r.nextDouble(), r.nextDouble(), r.nextDouble(), r.nextDouble()); + final PBounds b = new PBounds(r.nextDouble(), r.nextDouble(), r.nextDouble(), r.nextDouble()); log.startTest(); for (int i = 0; i < NUMBER_NODES * 10; i++) { b.clone(); @@ -298,8 +299,8 @@ } public void renderSpeed() throws NoninvertibleTransformException { - Random r = new Random(); - PAffineTransform at = new PAffineTransform(); + final Random r = new Random(); + final PAffineTransform at = new PAffineTransform(); at.setScale(r.nextFloat()); at.translate(r.nextFloat(), r.nextFloat()); @@ -309,25 +310,25 @@ } log.endTest("Create inverse transform " + NUMBER_NODES + " times"); - int height = 400; - int width = 400; + final int height = 400; + final int width = 400; - double scale1 = 0.5; - double scale2 = 2; + final double scale1 = 0.5; + final double scale2 = 2; boolean scaleFlip = true; - PAffineTransform transorm1 = new PAffineTransform(); + final PAffineTransform transorm1 = new PAffineTransform(); // transorm1.scale(0.5, 0.5); transorm1.translate(0.5, 10.1); PAffineTransform transorm2 = null; transorm2 = new PAffineTransform(transorm1.createInverse()); - GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment() + final GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); - BufferedImage result = (BufferedImage) graphicsConfiguration.createCompatibleImage(width, height, + final BufferedImage result = graphicsConfiguration.createCompatibleImage(width, height, Transparency.TRANSLUCENT); - Graphics2D g2 = result.createGraphics(); + final Graphics2D g2 = result.createGraphics(); log.startTest(); for (int i = 0; i < NUMBER_NODES; i++) { @@ -365,8 +366,8 @@ } log.endTest("Transform graphics context " + NUMBER_NODES + " times"); - Rectangle2D rect = new Rectangle2D.Double(0, 0, 100, 80); - GeneralPath path = new GeneralPath(rect); + final Rectangle2D rect = new Rectangle2D.Double(0, 0, 100, 80); + final GeneralPath path = new GeneralPath(rect); log.startTest(); for (int i = 0; i < NUMBER_NODES; i++) { diff --git a/core/src/test/java/edu/umd/cs/piccolo/PiccoloAsserts.java b/core/src/test/java/edu/umd/cs/piccolo/PiccoloAsserts.java index 7587057..0a89cf3 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/PiccoloAsserts.java +++ b/core/src/test/java/edu/umd/cs/piccolo/PiccoloAsserts.java @@ -46,27 +46,29 @@ // Nothing to do } - public static final void assertEquals(PBounds expected, PBounds actual, double errorRate) { + public static final void assertEquals(final PBounds expected, final PBounds actual, final double errorRate) { assertEquals("Expected " + expected + " but was " + actual, expected, actual, errorRate); } - public static final void assertEquals(String message, PBounds expected, PBounds actual, double errorRate) { + public static final void assertEquals(final String message, final PBounds expected, final PBounds actual, + final double errorRate) { Assert.assertEquals(message, expected.getX(), actual.getX(), errorRate); Assert.assertEquals(message, expected.getY(), actual.getY(), errorRate); Assert.assertEquals(message, expected.getWidth(), actual.getWidth(), errorRate); Assert.assertEquals(message, expected.getHeight(), actual.getHeight(), errorRate); } - public static void assertEquals(PDimension expected, Dimension2D actual, double errorRate) { + public static void assertEquals(final PDimension expected, final Dimension2D actual, final double errorRate) { assertEquals("Expected " + expected + " but was " + actual, expected, actual, errorRate); } - public static void assertEquals(String message, PDimension expected, Dimension2D actual, double errorRate) { + public static void assertEquals(final String message, final PDimension expected, final Dimension2D actual, + final double errorRate) { Assert.assertEquals(message, expected.getWidth(), actual.getWidth(), errorRate); Assert.assertEquals(message, expected.getHeight(), actual.getHeight(), errorRate); } - public static void assertEquals(String[] expected, String[] actual) { + public static void assertEquals(final String[] expected, final String[] actual) { Assert.assertEquals("arrays are not same size", expected.length, actual.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], expected[i]); diff --git a/core/src/test/java/edu/umd/cs/piccolo/SerializationTest.java b/core/src/test/java/edu/umd/cs/piccolo/SerializationTest.java index 1c4c921..14f23ef 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/SerializationTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/SerializationTest.java @@ -8,7 +8,7 @@ public class SerializationTest extends TestCase { - public SerializationTest(String name) { + public SerializationTest(final String name) { super(name); } @@ -24,9 +24,9 @@ l = (PNode) l.clone(); // copy uses serialization internally assertTrue(l.getChildrenCount() == 300); - Iterator i = l.getChildrenIterator(); + final Iterator i = l.getChildrenIterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); assertEquals(l, each.getParent()); } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/activities/PTransformActivityTest.java b/core/src/test/java/edu/umd/cs/piccolo/activities/PTransformActivityTest.java index 0bff5e7..7270c4d 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/activities/PTransformActivityTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/activities/PTransformActivityTest.java @@ -28,18 +28,16 @@ */ package edu.umd.cs.piccolo.activities; -import edu.umd.cs.piccolo.activities.PTransformActivity; - import junit.framework.TestCase; public class PTransformActivityTest extends TestCase { - public PTransformActivityTest(String name) { + public PTransformActivityTest(final String name) { super(name); } public void testToString() { - PTransformActivity transformActivity = new PTransformActivity(1000, 0, null); + final PTransformActivity transformActivity = new PTransformActivity(1000, 0, null); assertNotNull(transformActivity.toString()); } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/event/MockPBasicInputEventHandler.java b/core/src/test/java/edu/umd/cs/piccolo/event/MockPBasicInputEventHandler.java index b5b0040..684f94b 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/event/MockPBasicInputEventHandler.java +++ b/core/src/test/java/edu/umd/cs/piccolo/event/MockPBasicInputEventHandler.java @@ -3,82 +3,82 @@ import java.util.ArrayList; public class MockPBasicInputEventHandler extends PBasicInputEventHandler { - private ArrayList methodCalls = new ArrayList(); - + private final ArrayList methodCalls = new ArrayList(); + public String[] getMethodCalls() { - String[] result = new String[methodCalls.size()]; - for (int i=0; i 0); } - - public void testWriteConditionalObjectAcceptsNull() throws IOException { - + + public void testWriteConditionalObjectAcceptsNull() throws IOException { + } } diff --git a/core/src/test/java/edu/umd/cs/piccolo/util/PPickPathTest.java b/core/src/test/java/edu/umd/cs/piccolo/util/PPickPathTest.java index f241e76..f4c81dc 100644 --- a/core/src/test/java/edu/umd/cs/piccolo/util/PPickPathTest.java +++ b/core/src/test/java/edu/umd/cs/piccolo/util/PPickPathTest.java @@ -28,36 +28,35 @@ */ package edu.umd.cs.piccolo.util; +import junit.framework.TestCase; import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolo.PCanvas; import edu.umd.cs.piccolo.PLayer; import edu.umd.cs.piccolo.PNode; import edu.umd.cs.piccolo.nodes.PPath; -import edu.umd.cs.piccolo.util.PPickPath; -import junit.framework.TestCase; public class PPickPathTest extends TestCase { - public PPickPathTest(String name) { + public PPickPathTest(final String name) { super(name); } public void testPick() { - PCanvas canvas = new PCanvas(); - PCamera camera = canvas.getCamera(); - PLayer layer = canvas.getLayer(); + final PCanvas canvas = new PCanvas(); + final PCamera camera = canvas.getCamera(); + final PLayer layer = canvas.getLayer(); camera.setBounds(0, 0, 100, 100); - PNode a = PPath.createRectangle(0, 0, 100, 100); - PNode b = PPath.createRectangle(0, 0, 100, 100); - PNode c = PPath.createRectangle(0, 0, 100, 100); + final PNode a = PPath.createRectangle(0, 0, 100, 100); + final PNode b = PPath.createRectangle(0, 0, 100, 100); + final PNode c = PPath.createRectangle(0, 0, 100, 100); layer.addChild(a); layer.addChild(b); layer.addChild(c); - PPickPath pickPath = camera.pick(50, 50, 2); + final PPickPath pickPath = camera.pick(50, 50, 2); assertTrue(pickPath.getPickedNode() == c); assertTrue(pickPath.nextPickedNode() == b); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/ActivityExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/ActivityExample.java index adec36a..7d0fae5 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/ActivityExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/ActivityExample.java @@ -42,31 +42,36 @@ */ public class ActivityExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public ActivityExample() { this(null); } - public ActivityExample(PCanvas aCanvas) { + public ActivityExample(final PCanvas aCanvas) { super("ActivityExample", false, aCanvas); } public void initialize() { - long currentTime = System.currentTimeMillis(); + final long currentTime = System.currentTimeMillis(); // Create a new node that we will apply different activities to, and // place that node at location 200, 200. final PNode aNode = PPath.createRectangle(0, 0, 100, 80); - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); layer.addChild(aNode); aNode.setOffset(200, 200); // Create a new custom "flash" activity. This activity will start // running in five seconds, and while it runs it will flash aNode's // paint between red and green every half second. - PActivity flash = new PActivity(-1, 500, currentTime + 5000) { + final PActivity flash = new PActivity(-1, 500, currentTime + 5000) { boolean fRed = true; - protected void activityStep(long elapsedTime) { + protected void activityStep(final long elapsedTime) { super.activityStep(elapsedTime); if (fRed) { @@ -89,10 +94,10 @@ // the node's position. Since our node already descends from the root // node the animate methods will automatically schedule these activities // for us. - PActivity a1 = aNode.animateToPositionScaleRotation(0, 0, 0.5, 0, 5000); - PActivity a2 = aNode.animateToPositionScaleRotation(100, 0, 1.5, Math.toRadians(110), 5000); - PActivity a3 = aNode.animateToPositionScaleRotation(200, 100, 1, 0, 5000); - PActivity a4 = aNode.animateToTransparency(0.25f, 3000); + final PActivity a1 = aNode.animateToPositionScaleRotation(0, 0, 0.5, 0, 5000); + final PActivity a2 = aNode.animateToPositionScaleRotation(100, 0, 1.5, Math.toRadians(110), 5000); + final PActivity a3 = aNode.animateToPositionScaleRotation(200, 100, 1, 0, 5000); + final PActivity a4 = aNode.animateToTransparency(0.25f, 3000); // the animate activities will start immediately (in the next call to // PRoot.processInputs) by default. Here we set their start times (in @@ -111,7 +116,7 @@ // a4.setStartTime(currentTime + 15000); } - public static void main(String[] args) { + public static void main(final String[] args) { new ActivityExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/AngleNodeExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/AngleNodeExample.java index 6284773..9566c2f 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/AngleNodeExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/AngleNodeExample.java @@ -53,26 +53,35 @@ */ public class AngleNodeExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public AngleNodeExample() { this(null); } - public AngleNodeExample(PCanvas aCanvas) { + public AngleNodeExample(final PCanvas aCanvas) { super("AngleNodeExample", false, aCanvas); } public void initialize() { - PCanvas c = getCanvas(); - PLayer l = c.getLayer(); + final PCanvas c = getCanvas(); + final PLayer l = c.getLayer(); l.addChild(new AngleNode()); } - public static void main(String[] args) { + public static void main(final String[] args) { new AngleNodeExample(); } // the angle node class public static class AngleNode extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; protected Point2D.Double pointOne; protected Point2D.Double pointTwo; protected Stroke stroke; @@ -89,6 +98,11 @@ public void addHandles() { // point one PLocator l = new PLocator() { + /** + * + */ + private static final long serialVersionUID = 1L; + public double locateX() { return pointOne.getX(); } @@ -98,7 +112,12 @@ } }; PHandle h = new PHandle(l) { - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { localToParent(aLocalDimension); pointOne.setLocation(pointOne.getX() + aLocalDimension.getWidth(), pointOne.getY() + aLocalDimension.getHeight()); @@ -110,6 +129,11 @@ // point two l = new PLocator() { + /** + * + */ + private static final long serialVersionUID = 1L; + public double locateX() { return pointTwo.getX(); } @@ -119,7 +143,12 @@ } }; h = new PHandle(l) { - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { localToParent(aLocalDimension); pointTwo.setLocation(pointTwo.getX() + aLocalDimension.getWidth(), pointTwo.getY() + aLocalDimension.getHeight()); @@ -130,28 +159,28 @@ addChild(h); } - protected void paint(PPaintContext paintContext) { - Graphics2D g2 = paintContext.getGraphics(); + protected void paint(final PPaintContext paintContext) { + final Graphics2D g2 = paintContext.getGraphics(); g2.setStroke(stroke); g2.setPaint(getPaint()); g2.draw(getAnglePath()); } protected void updateBounds() { - GeneralPath p = getAnglePath(); - Rectangle2D b = stroke.createStrokedShape(p).getBounds2D(); + final GeneralPath p = getAnglePath(); + final Rectangle2D b = stroke.createStrokedShape(p).getBounds2D(); super.setBounds(b.getX(), b.getY(), b.getWidth(), b.getHeight()); } public GeneralPath getAnglePath() { - GeneralPath p = new GeneralPath(); + final GeneralPath p = new GeneralPath(); p.moveTo((float) pointOne.getX(), (float) pointOne.getY()); p.lineTo(0, 0); p.lineTo((float) pointTwo.getX(), (float) pointTwo.getY()); return p; } - public boolean setBounds(double x, double y, double width, double height) { + public boolean setBounds(final double x, final double y, final double width, final double height) { return false; // bounds can be set externally } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/BirdsEyeViewExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/BirdsEyeViewExample.java index 8c3ac0e..96c5f86 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/BirdsEyeViewExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/BirdsEyeViewExample.java @@ -61,13 +61,17 @@ */ public class BirdsEyeViewExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; boolean fIsPressed = false; public BirdsEyeViewExample() { this(null); } - public BirdsEyeViewExample(PCanvas aCanvas) { + public BirdsEyeViewExample(final PCanvas aCanvas) { super("BirdsEyeViewExample", false, aCanvas); } @@ -86,9 +90,9 @@ getCanvas().addInputEventListener(new PDragEventHandler()); // this will create the actual BirdsEyeView and put it in a JDialog - BirdsEyeView bev = new BirdsEyeView(); + final BirdsEyeView bev = new BirdsEyeView(); bev.connect(getCanvas(), new PLayer[] { getCanvas().getLayer() }); - JDialog bird = new JDialog(); + final JDialog bird = new JDialog(); bird.getContentPane().add(bev); bird.pack(); bird.setSize(150, 150); @@ -99,8 +103,8 @@ // This method demonstrates the kinds of things that can be done with any // node. public void nodeDemo() { - PLayer layer = getCanvas().getLayer(); - PNode aNode = PPath.createRectangle(0, 0, 100, 80); + final PLayer layer = getCanvas().getLayer(); + final PNode aNode = PPath.createRectangle(0, 0, 100, 80); // A node needs to be a descendent of the root to be displayed on the // screen. @@ -128,7 +132,7 @@ aNode.setTransparency(0.75f); // Its easy to copy nodes. - PNode aCopy = (PNode) aNode.clone(); + final PNode aCopy = (PNode) aNode.clone(); // Make is so that the copies children are not pickable. For this // example that means you will not be able to grab the child and remove @@ -149,7 +153,7 @@ // So far we have just been using PNode, but of course PNode has many // subclasses that you can try out to. public void createNodeUsingExistingClasses() { - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); layer.addChild(PPath.createEllipse(0, 0, 100, 100)); layer.addChild(PPath.createRectangle(0, 100, 100, 100)); layer.addChild(new PText("Hello World")); @@ -167,10 +171,15 @@ public void subclassExistingClasses() { final PNode n = new PPath(new Ellipse2D.Float(0, 0, 100, 80)) { - public void paint(PPaintContext aPaintContext) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void paint(final PPaintContext aPaintContext) { if (fIsPressed) { // if mouse is pressed draw self as a square. - Graphics2D g2 = aPaintContext.getGraphics(); + final Graphics2D g2 = aPaintContext.getGraphics(); g2.setPaint(getPaint()); g2.fill(getBoundsReference()); } @@ -182,14 +191,14 @@ }; n.addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { super.mousePressed(aEvent); fIsPressed = true; n.invalidatePaint(); // this tells the framework that the node // needs to be redisplayed. } - public void mouseReleased(PInputEvent aEvent) { + public void mouseReleased(final PInputEvent aEvent) { super.mousePressed(aEvent); fIsPressed = false; n.invalidatePaint(); // this tells the framework that the node @@ -204,13 +213,13 @@ // Here a new "face" node is created. But instead of drawing the face // directly using Graphics2D we compose the face from other nodes. public void composeOtherNodes() { - PNode myCompositeFace = PPath.createRectangle(0, 0, 100, 80); + final PNode myCompositeFace = PPath.createRectangle(0, 0, 100, 80); // create parts for the face. - PNode eye1 = PPath.createEllipse(0, 0, 20, 20); + final PNode eye1 = PPath.createEllipse(0, 0, 20, 20); eye1.setPaint(Color.YELLOW); - PNode eye2 = (PNode) eye1.clone(); - PNode mouth = PPath.createRectangle(0, 0, 40, 20); + final PNode eye2 = (PNode) eye1.clone(); + final PNode mouth = PPath.createRectangle(0, 0, 40, 20); mouth.setPaint(Color.BLACK); // add the face parts @@ -226,7 +235,7 @@ mouth.translate(0, 30); // set the face bounds so that it neatly contains the face parts. - PBounds b = myCompositeFace.getUnionOfChildrenBounds(null); + final PBounds b = myCompositeFace.getUnionOfChildrenBounds(null); myCompositeFace.setBounds(b.inset(-5, -5)); // opps it to small, so scale it up. @@ -239,15 +248,20 @@ // all the drawing ourselves here instead of passing the work off to // other parts of the framework. public void createCustomNode() { - PNode n = new PNode() { - public void paint(PPaintContext aPaintContext) { - double bx = getX(); - double by = getY(); - double rightBorder = bx + getWidth(); - double bottomBorder = by + getHeight(); + final PNode n = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; - Line2D line = new Line2D.Double(); - Graphics2D g2 = aPaintContext.getGraphics(); + public void paint(final PPaintContext aPaintContext) { + final double bx = getX(); + final double by = getY(); + final double rightBorder = bx + getWidth(); + final double bottomBorder = by + getHeight(); + + final Line2D line = new Line2D.Double(); + final Graphics2D g2 = aPaintContext.getGraphics(); g2.setStroke(new BasicStroke(0)); g2.setPaint(getPaint()); @@ -269,7 +283,7 @@ getCanvas().getLayer().addChild(n); } - public static void main(String[] args) { + public static void main(final String[] args) { new BirdsEyeViewExample(); } @@ -279,6 +293,11 @@ public class BirdsEyeView extends PCanvas implements PropertyChangeListener { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * This is the node that shows the viewed area. */ PNode areaVisiblePNode; @@ -303,7 +322,7 @@ // create the PropertyChangeListener for listening to the viewed // canvas changeListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { updateFromViewed(); } }; @@ -317,13 +336,14 @@ // add the drag event handler getCamera().addInputEventListener(new PDragSequenceEventHandler() { - protected void startDrag(PInputEvent e) { - if (e.getPickedNode() == areaVisiblePNode) + protected void startDrag(final PInputEvent e) { + if (e.getPickedNode() == areaVisiblePNode) { super.startDrag(e); + } } - protected void drag(PInputEvent e) { - PDimension dim = e.getDelta(); + protected void drag(final PInputEvent e) { + final PDimension dim = e.getDelta(); viewedCanvas.getCamera().translateView(0 - dim.getWidth(), 0 - dim.getHeight()); } @@ -337,9 +357,9 @@ } - public void connect(PCanvas canvas, PLayer[] viewed_layers) { + public void connect(final PCanvas canvas, final PLayer[] viewed_layers) { - this.viewedCanvas = canvas; + viewedCanvas = canvas; layerCount = 0; viewedCanvas.getCamera().addPropertyChangeListener(changeListener); @@ -353,7 +373,7 @@ /** * Add a layer to list of viewed layers */ - public void addLayer(PLayer new_layer) { + public void addLayer(final PLayer new_layer) { getCamera().addLayer(new_layer); layerCount++; } @@ -361,7 +381,7 @@ /** * Remove the layer from the viewed layers */ - public void removeLayer(PLayer old_layer) { + public void removeLayer(final PLayer old_layer) { getCamera().removeLayer(old_layer); layerCount--; } @@ -382,7 +402,7 @@ /** * This method will get called when the viewed canvas changes */ - public void propertyChange(PropertyChangeEvent event) { + public void propertyChange(final PropertyChangeEvent event) { updateFromViewed(); } @@ -397,45 +417,53 @@ double viewedHeight; double viewedWidth; - double ul_camera_x = viewedCanvas.getCamera().getViewBounds().getX(); - double ul_camera_y = viewedCanvas.getCamera().getViewBounds().getY(); - double lr_camera_x = ul_camera_x + viewedCanvas.getCamera().getViewBounds().getWidth(); - double lr_camera_y = ul_camera_y + viewedCanvas.getCamera().getViewBounds().getHeight(); + final double ul_camera_x = viewedCanvas.getCamera().getViewBounds().getX(); + final double ul_camera_y = viewedCanvas.getCamera().getViewBounds().getY(); + final double lr_camera_x = ul_camera_x + viewedCanvas.getCamera().getViewBounds().getWidth(); + final double lr_camera_y = ul_camera_y + viewedCanvas.getCamera().getViewBounds().getHeight(); - Rectangle2D drag_bounds = getCamera().getUnionOfLayerFullBounds(); + final Rectangle2D drag_bounds = getCamera().getUnionOfLayerFullBounds(); - double ul_layer_x = drag_bounds.getX(); - double ul_layer_y = drag_bounds.getY(); - double lr_layer_x = drag_bounds.getX() + drag_bounds.getWidth(); - double lr_layer_y = drag_bounds.getY() + drag_bounds.getHeight(); + final double ul_layer_x = drag_bounds.getX(); + final double ul_layer_y = drag_bounds.getY(); + final double lr_layer_x = drag_bounds.getX() + drag_bounds.getWidth(); + final double lr_layer_y = drag_bounds.getY() + drag_bounds.getHeight(); // find the upper left corner // set to the lesser value - if (ul_camera_x < ul_layer_x) + if (ul_camera_x < ul_layer_x) { viewedX = ul_layer_x; - else + } + else { viewedX = ul_camera_x; + } // same for y - if (ul_camera_y < ul_layer_y) + if (ul_camera_y < ul_layer_y) { viewedY = ul_layer_y; - else + } + else { viewedY = ul_camera_y; + } // find the lower right corner // set to the greater value - if (lr_camera_x < lr_layer_x) + if (lr_camera_x < lr_layer_x) { viewedWidth = lr_camera_x - viewedX; - else + } + else { viewedWidth = lr_layer_x - viewedX; + } // same for height - if (lr_camera_y < lr_layer_y) + if (lr_camera_y < lr_layer_y) { viewedHeight = lr_camera_y - viewedY; - else + } + else { viewedHeight = lr_layer_y - viewedY; + } Rectangle2D bounds = new Rectangle2D.Double(viewedX, viewedY, viewedWidth, viewedHeight); bounds = getCamera().viewToLocal(bounds); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/CameraExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/CameraExample.java index a37b864..0348827 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/CameraExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/CameraExample.java @@ -42,24 +42,29 @@ */ public class CameraExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public CameraExample() { this(null); } - public CameraExample(PCanvas aCanvas) { + public CameraExample(final PCanvas aCanvas) { super("CameraExample", false, aCanvas); } public void initialize() { - PLayer l = new PLayer(); - PPath n = PPath.createEllipse(0, 0, 100, 80); + final PLayer l = new PLayer(); + final PPath n = PPath.createEllipse(0, 0, 100, 80); n.setPaint(Color.red); n.setStroke(null); PBoundsHandle.addBoundsHandlesTo(n); l.addChild(n); n.translate(200, 200); - PCamera c = new PCamera(); + final PCamera c = new PCamera(); c.setBounds(0, 0, 100, 80); c.scaleView(0.1); c.addLayer(l); @@ -70,7 +75,7 @@ getCanvas().getLayer().addChild(c); } - public static void main(String[] args) { + public static void main(final String[] args) { new CameraExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/CenterExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/CenterExample.java index 8cef4bf..2d6dde2 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/CenterExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/CenterExample.java @@ -36,21 +36,26 @@ public class CenterExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public CenterExample() { this(null); } - public CenterExample(PCanvas aCanvas) { + public CenterExample(final PCanvas aCanvas) { super("CenterExample", false, aCanvas); } public void initialize() { - PCanvas c = getCanvas(); - PLayer l = c.getLayer(); - PCamera cam = c.getCamera(); + final PCanvas c = getCanvas(); + final PLayer l = c.getLayer(); + final PCamera cam = c.getCamera(); cam.scaleView(2.0); - PPath path = PPath.createRectangle(0, 0, 100, 100); + final PPath path = PPath.createRectangle(0, 0, 100, 100); l.addChild(path); path.translate(100, 10); @@ -58,7 +63,7 @@ cam.animateViewToCenterBounds(path.getGlobalFullBounds(), true, 1000); } - public static void main(String[] args) { + public static void main(final String[] args) { new CenterExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/ChartLabelExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/ChartLabelExample.java index 7ab2670..4783da1 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/ChartLabelExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/ChartLabelExample.java @@ -46,6 +46,10 @@ * @author Tao */ public class ChartLabelExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; final int nodeHeight = 15; final int nodeWidth = 30; @@ -59,7 +63,7 @@ this(null); } - public ChartLabelExample(PCanvas aCanvas) { + public ChartLabelExample(final PCanvas aCanvas) { super("ChartLabelExample", false, aCanvas); } @@ -92,7 +96,7 @@ // create matrix nodes for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { - PPath path = PPath.createRectangle(nodeWidth * j + nodeWidth, nodeHeight * i + nodeHeight, + final PPath path = PPath.createRectangle(nodeWidth * j + nodeWidth, nodeHeight * i + nodeHeight, nodeWidth - 1, nodeHeight - 1); getCanvas().getLayer().addChild(path); } @@ -102,11 +106,11 @@ getCanvas().addInputEventListener(new PDragSequenceEventHandler() { Point2D oldP, newP; - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { oldP = getCanvas().getCamera().getViewBounds().getCenter2D(); } - public void mouseReleased(PInputEvent aEvent) { + public void mouseReleased(final PInputEvent aEvent) { newP = getCanvas().getCamera().getViewBounds().getCenter2D(); colBarLayer.translate(0, (oldP.getY() - newP.getY()) / getCanvas().getLayer().getScale()); rowBarLayer.translate((oldP.getX() - newP.getX()) / getCanvas().getLayer().getScale(), 0); @@ -114,7 +118,7 @@ }); } - public static void main(String[] args) { + public static void main(final String[] args) { new ChartLabelExample(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/ClipExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/ClipExample.java index f4a3036..b7e01fd 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/ClipExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/ClipExample.java @@ -41,16 +41,21 @@ */ public class ClipExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public ClipExample() { this(null); } - public ClipExample(PCanvas aCanvas) { + public ClipExample(final PCanvas aCanvas) { super("ClipExample", false, aCanvas); } public void initialize() { - PClip clip = new PClip(); + final PClip clip = new PClip(); clip.setPathToEllipse(0, 0, 100, 100); clip.setPaint(Color.red); @@ -61,7 +66,7 @@ getCanvas().addInputEventListener(new PDragEventHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new ClipExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/CompositeExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/CompositeExample.java index 745a72e..e732153 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/CompositeExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/CompositeExample.java @@ -44,20 +44,25 @@ */ public class CompositeExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public CompositeExample() { this(null); } - public CompositeExample(PCanvas aCanvas) { + public CompositeExample(final PCanvas aCanvas) { super("CompositeExample", false, aCanvas); } public void initialize() { - PComposite composite = new PComposite(); + final PComposite composite = new PComposite(); - PNode circle = PPath.createEllipse(0, 0, 100, 100); - PNode rectangle = PPath.createRectangle(50, 50, 100, 100); - PNode text = new PText("Hello world!"); + final PNode circle = PPath.createEllipse(0, 0, 100, 100); + final PNode rectangle = PPath.createRectangle(50, 50, 100, 100); + final PNode text = new PText("Hello world!"); composite.addChild(circle); composite.addChild(rectangle); @@ -74,7 +79,7 @@ getCanvas().addInputEventListener(new PDragEventHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new CompositeExample(); } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/DynamicExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/DynamicExample.java index de41e94..4c0f43c 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/DynamicExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/DynamicExample.java @@ -51,18 +51,23 @@ */ public class DynamicExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public DynamicExample() { this(null); } - public DynamicExample(PCanvas aCanvas) { + public DynamicExample(final PCanvas aCanvas) { super("DynamicExample", false, aCanvas); } public void initialize() { final PLayer layer = getCanvas().getLayer(); - PRoot root = getCanvas().getRoot(); - Random r = new Random(); + final PRoot root = getCanvas().getRoot(); + final Random r = new Random(); for (int i = 0; i < 1000; i++) { final PNode n = PPath.createRectangle(0, 0, 100, 80); n.translate(10000 * r.nextFloat(), 10000 * r.nextFloat()); @@ -70,32 +75,32 @@ layer.addChild(n); } getCanvas().getCamera().animateViewToCenterBounds(layer.getGlobalFullBounds(), true, 0); - PActivity a = new PActivity(-1, 20) { - public void activityStep(long currentTime) { + final PActivity a = new PActivity(-1, 20) { + public void activityStep(final long currentTime) { super.activityStep(currentTime); rotateNodes(); } }; root.addActivity(a); - PPath p = new PPath(); + final PPath p = new PPath(); p.moveTo(0, 0); p.lineTo(0, 1000); - PFixedWidthStroke stroke = new PFixedWidthStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, + final PFixedWidthStroke stroke = new PFixedWidthStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, new float[] { 5, 2 }, 0); p.setStroke(stroke); layer.addChild(p); } public void rotateNodes() { - Iterator i = getCanvas().getLayer().getChildrenReference().iterator(); + final Iterator i = getCanvas().getLayer().getChildrenReference().iterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); each.rotate(Math.toRadians(2)); } } - public static void main(String[] args) { + public static void main(final String[] args) { new DynamicExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/EventHandlerExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/EventHandlerExample.java index 4ad4d16..2340e68 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/EventHandlerExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/EventHandlerExample.java @@ -34,12 +34,12 @@ import edu.umd.cs.piccolo.PCanvas; import edu.umd.cs.piccolo.PLayer; -import edu.umd.cs.piccolox.PFrame; import edu.umd.cs.piccolo.event.PBasicInputEventHandler; import edu.umd.cs.piccolo.event.PInputEvent; import edu.umd.cs.piccolo.event.PInputEventFilter; import edu.umd.cs.piccolo.nodes.PPath; import edu.umd.cs.piccolo.util.PBounds; +import edu.umd.cs.piccolox.PFrame; /** * This example shows how to create and install a custom event listener that @@ -47,11 +47,16 @@ */ public class EventHandlerExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public EventHandlerExample() { this(null); } - public EventHandlerExample(PCanvas aCanvas) { + public EventHandlerExample(final PCanvas aCanvas) { super("EventHandlerExample", false, aCanvas); } @@ -60,7 +65,7 @@ // Create a new event handler the creates new rectangles on // mouse pressed, dragged, release. - PBasicInputEventHandler rectEventHandler = createRectangleEventHandler(); + final PBasicInputEventHandler rectEventHandler = createRectangleEventHandler(); // Make the event handler only work with BUTTON1 events, so that it does // not conflict with the zoom event handler that is installed by @@ -93,10 +98,10 @@ // The current drag location. protected Point2D dragPoint; - public void mousePressed(PInputEvent e) { + public void mousePressed(final PInputEvent e) { super.mousePressed(e); - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); // Initialize the locations. pressPoint = e.getPosition(); @@ -112,7 +117,7 @@ updateRectangle(); } - public void mouseDragged(PInputEvent e) { + public void mouseDragged(final PInputEvent e) { super.mouseDragged(e); // update the drag point location. dragPoint = e.getPosition(); @@ -121,7 +126,7 @@ updateRectangle(); } - public void mouseReleased(PInputEvent e) { + public void mouseReleased(final PInputEvent e) { super.mouseReleased(e); // update the rectangle shape. updateRectangle(); @@ -131,7 +136,7 @@ public void updateRectangle() { // create a new bounds that contains both the press and current // drag point. - PBounds b = new PBounds(); + final PBounds b = new PBounds(); b.add(pressPoint); b.add(dragPoint); @@ -141,7 +146,7 @@ }; } - public static void main(String[] args) { + public static void main(final String[] args) { new EventHandlerExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/ExampleRunner.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/ExampleRunner.java index 791387e..069a7bc 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/ExampleRunner.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/ExampleRunner.java @@ -39,12 +39,18 @@ import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; +import javax.swing.WindowConstants; import edu.umd.cs.piccolo.util.PDebug; import edu.umd.cs.piccolox.PFrame; public class ExampleRunner extends JFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public ExampleRunner() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Piccolo Example Runner"); @@ -57,24 +63,39 @@ } public void createExampleButtons() { - Container c = getContentPane(); + final Container c = getContentPane(); JPanel panel = new JPanel(new GridLayout(0, 1)); c.add(BorderLayout.NORTH, panel); panel.add(new JCheckBox(new AbstractAction("Print Frame Rates to Console") { - public void actionPerformed(ActionEvent e) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { PDebug.debugPrintFrameRate = !PDebug.debugPrintFrameRate; } })); panel.add(new JCheckBox(new AbstractAction("Show Region Managment") { - public void actionPerformed(ActionEvent e) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { PDebug.debugRegionManagement = !PDebug.debugRegionManagement; } })); panel.add(new JCheckBox(new AbstractAction("Show Full Bounds") { - public void actionPerformed(ActionEvent e) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { PDebug.debugFullBounds = !PDebug.debugFullBounds; } })); @@ -95,22 +116,27 @@ TwoCanvasExample.class, WaitForActivitiesExample.class }); } - private void addExampleButtons(JPanel panel, Class[] exampleClasses) { + private void addExampleButtons(final JPanel panel, final Class[] exampleClasses) { for (int i = 0; i < exampleClasses.length; i++) { panel.add(buildExampleButton(exampleClasses[i])); } } private JButton buildExampleButton(final Class exampleClass) { - String fullClassName = exampleClass.getName(); - String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1); + final String fullClassName = exampleClass.getName(); + final String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1); return new JButton(new AbstractAction(simpleClassName) { - public void actionPerformed(ActionEvent event) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent event) { try { - PFrame example = (PFrame) exampleClass.newInstance(); - example.setDefaultCloseOperation(PFrame.DISPOSE_ON_CLOSE); + final PFrame example = (PFrame) exampleClass.newInstance(); + example.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } - catch (Exception e) { + catch (final Exception e) { JOptionPane.showMessageDialog(ExampleRunner.this, "A problem was encountered running the example.\n\n" + e.getMessage()); } @@ -118,7 +144,7 @@ }); } - public static void main(String[] args) { + public static void main(final String[] args) { new ExampleRunner(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/FullScreenNodeExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/FullScreenNodeExample.java index 6ecbfd0..09cc5ee 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/FullScreenNodeExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/FullScreenNodeExample.java @@ -30,12 +30,17 @@ public class FullScreenNodeExample extends NodeExample { + /** + * + */ + private static final long serialVersionUID = 1L; + public void initialize() { super.initialize(); setFullScreenMode(true); } - public static void main(String[] args) { + public static void main(final String[] args) { new FullScreenNodeExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/GraphEditorExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/GraphEditorExample.java index 08fed7b..ccdb864 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/GraphEditorExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/GraphEditorExample.java @@ -49,29 +49,34 @@ */ public class GraphEditorExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public GraphEditorExample() { this(null); } - public GraphEditorExample(PCanvas aCanvas) { + public GraphEditorExample(final PCanvas aCanvas) { super("GraphEditorExample", false, aCanvas); } public void initialize() { - int numNodes = 50; - int numEdges = 50; + final int numNodes = 50; + final int numEdges = 50; // Initialize, and create a layer for the edges (always underneath the // nodes) - PLayer nodeLayer = getCanvas().getLayer(); - PLayer edgeLayer = new PLayer(); + final PLayer nodeLayer = getCanvas().getLayer(); + final PLayer edgeLayer = new PLayer(); getCanvas().getCamera().addLayer(0, edgeLayer); - Random rnd = new Random(); + final Random rnd = new Random(); ArrayList tmp; for (int i = 0; i < numNodes; i++) { - float x = (float) (300. * rnd.nextDouble()); - float y = (float) (400. * rnd.nextDouble()); - PPath path = PPath.createEllipse(x, y, 20, 20); + final float x = (float) (300. * rnd.nextDouble()); + final float y = (float) (400. * rnd.nextDouble()); + final PPath path = PPath.createEllipse(x, y, 20, 20); tmp = new ArrayList(); path.addAttribute("edges", tmp); nodeLayer.addChild(path); @@ -80,15 +85,15 @@ // Create some random edges // Each edge's Tag has an ArrayList used to store associated nodes for (int i = 0; i < numEdges; i++) { - int n1 = rnd.nextInt(numNodes); - int n2 = rnd.nextInt(numNodes); - PNode node1 = nodeLayer.getChild(n1); - PNode node2 = nodeLayer.getChild(n2); + final int n1 = rnd.nextInt(numNodes); + final int n2 = rnd.nextInt(numNodes); + final PNode node1 = nodeLayer.getChild(n1); + final PNode node2 = nodeLayer.getChild(n2); - Point2D.Double bound1 = (Point2D.Double) node1.getBounds().getCenter2D(); - Point2D.Double bound2 = (Point2D.Double) node2.getBounds().getCenter2D(); + final Point2D.Double bound1 = (Point2D.Double) node1.getBounds().getCenter2D(); + final Point2D.Double bound2 = (Point2D.Double) node2.getBounds().getCenter2D(); - PPath edge = new PPath(); + final PPath edge = new PPath(); edge.moveTo((float) bound1.getX(), (float) bound1.getY()); edge.lineTo((float) bound2.getX(), (float) bound2.getY()); @@ -109,7 +114,7 @@ nodeLayer.addInputEventListener(new NodeDragHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new GraphEditorExample(); } @@ -131,38 +136,38 @@ getEventFilter().setMarksAcceptedEventsAsHandled(true); } - public void mouseEntered(PInputEvent e) { + public void mouseEntered(final PInputEvent e) { if (e.getButton() == 0) { e.getPickedNode().setPaint(Color.red); } } - public void mouseExited(PInputEvent e) { + public void mouseExited(final PInputEvent e) { if (e.getButton() == 0) { e.getPickedNode().setPaint(Color.white); } } - public void drag(PInputEvent e) { - PNode node = e.getPickedNode(); + public void drag(final PInputEvent e) { + final PNode node = e.getPickedNode(); node.translate(e.getDelta().width, e.getDelta().height); - ArrayList edges = (ArrayList) e.getPickedNode().getAttribute("edges"); + final ArrayList edges = (ArrayList) e.getPickedNode().getAttribute("edges"); int i; for (i = 0; i < edges.size(); i++) { - PPath edge = (PPath) edges.get(i); - ArrayList nodes = (ArrayList) edge.getAttribute("nodes"); - PNode node1 = (PNode) nodes.get(0); - PNode node2 = (PNode) nodes.get(1); + final PPath edge = (PPath) edges.get(i); + final ArrayList nodes = (ArrayList) edge.getAttribute("nodes"); + final PNode node1 = (PNode) nodes.get(0); + final PNode node2 = (PNode) nodes.get(1); edge.reset(); // Note that the node's "FullBounds" must be used (instead of // just the "Bound") because the nodes have non-identity // transforms which must be included when determining their // position. - Point2D.Double bound1 = (Point2D.Double) node1.getFullBounds().getCenter2D(); - Point2D.Double bound2 = (Point2D.Double) node2.getFullBounds().getCenter2D(); + final Point2D.Double bound1 = (Point2D.Double) node1.getFullBounds().getCenter2D(); + final Point2D.Double bound2 = (Point2D.Double) node2.getFullBounds().getCenter2D(); edge.moveTo((float) bound1.getX(), (float) bound1.getY()); edge.lineTo((float) bound2.getX(), (float) bound2.getY()); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/GridExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/GridExample.java index 4105ca8..c11030e 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/GridExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/GridExample.java @@ -53,6 +53,10 @@ */ public class GridExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; protected Line2D gridLine = new Line2D.Double(); protected Stroke gridStroke = new BasicStroke(1); protected Color gridPaint = Color.BLACK; @@ -62,24 +66,29 @@ this(null); } - public GridExample(PCanvas aCanvas) { + public GridExample(final PCanvas aCanvas) { super("GridExample", false, aCanvas); } public void initialize() { - PRoot root = getCanvas().getRoot(); + final PRoot root = getCanvas().getRoot(); final PCamera camera = getCanvas().getCamera(); final PLayer gridLayer = new PLayer() { - protected void paint(PPaintContext paintContext) { + /** + * + */ + private static final long serialVersionUID = 1L; + + protected void paint(final PPaintContext paintContext) { // make sure grid gets drawn on snap to grid boundaries. And // expand a little to make sure that entire view is filled. - double bx = (getX() - (getX() % gridSpacing)) - gridSpacing; - double by = (getY() - (getY() % gridSpacing)) - gridSpacing; - double rightBorder = getX() + getWidth() + gridSpacing; - double bottomBorder = getY() + getHeight() + gridSpacing; + final double bx = getX() - getX() % gridSpacing - gridSpacing; + final double by = getY() - getY() % gridSpacing - gridSpacing; + final double rightBorder = getX() + getWidth() + gridSpacing; + final double bottomBorder = getY() + getHeight() + gridSpacing; - Graphics2D g2 = paintContext.getGraphics(); - Rectangle2D clip = paintContext.getLocalClip(); + final Graphics2D g2 = paintContext.getGraphics(); + final Rectangle2D clip = paintContext.getLocalClip(); g2.setStroke(gridStroke); g2.setPaint(gridPaint); @@ -109,20 +118,20 @@ // add constrains so that grid layers bounds always match cameras view // bounds. This makes it look like an infinite grid. camera.addPropertyChangeListener(PNode.PROPERTY_BOUNDS, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { gridLayer.setBounds(camera.getViewBounds()); } }); camera.addPropertyChangeListener(PCamera.PROPERTY_VIEW_TRANSFORM, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { gridLayer.setBounds(camera.getViewBounds()); } }); gridLayer.setBounds(camera.getViewBounds()); - PNode n = new PNode(); + final PNode n = new PNode(); n.setPaint(Color.BLUE); n.setBounds(0, 0, 100, 80); @@ -135,38 +144,39 @@ protected PNode draggedNode; protected Point2D nodeStartPosition; - protected boolean shouldStartDragInteraction(PInputEvent event) { + protected boolean shouldStartDragInteraction(final PInputEvent event) { if (super.shouldStartDragInteraction(event)) { return event.getPickedNode() != event.getTopCamera() && !(event.getPickedNode() instanceof PLayer); } return false; } - protected void startDrag(PInputEvent event) { + protected void startDrag(final PInputEvent event) { super.startDrag(event); draggedNode = event.getPickedNode(); draggedNode.moveToFront(); nodeStartPosition = draggedNode.getOffset(); } - protected void drag(PInputEvent event) { + protected void drag(final PInputEvent event) { super.drag(event); - Point2D start = getCanvas().getCamera().localToView((Point2D) getMousePressedCanvasPoint().clone()); - Point2D current = event.getPositionRelativeTo(getCanvas().getLayer()); - Point2D dest = new Point2D.Double(); + final Point2D start = getCanvas().getCamera().localToView( + (Point2D) getMousePressedCanvasPoint().clone()); + final Point2D current = event.getPositionRelativeTo(getCanvas().getLayer()); + final Point2D dest = new Point2D.Double(); - dest.setLocation(nodeStartPosition.getX() + (current.getX() - start.getX()), nodeStartPosition.getY() - + (current.getY() - start.getY())); + dest.setLocation(nodeStartPosition.getX() + current.getX() - start.getX(), nodeStartPosition.getY() + + current.getY() - start.getY()); - dest.setLocation(dest.getX() - (dest.getX() % gridSpacing), dest.getY() - (dest.getY() % gridSpacing)); + dest.setLocation(dest.getX() - dest.getX() % gridSpacing, dest.getY() - dest.getY() % gridSpacing); draggedNode.setOffset(dest.getX(), dest.getY()); } }); } - public static void main(String[] args) { + public static void main(final String[] args) { new GridExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/GroupExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/GroupExample.java index 9bab824..35bdc5e 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/GroupExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/GroupExample.java @@ -58,11 +58,16 @@ */ public class GroupExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public GroupExample() { this(null); } - public GroupExample(PCanvas aCanvas) { + public GroupExample(final PCanvas aCanvas) { super("GroupExample", false, aCanvas); } @@ -72,13 +77,13 @@ getCanvas().removeInputEventListener(getCanvas().getPanEventHandler()); // Create a decorator group that is NOT volatile - DecoratorGroup dg = new DecoratorGroup(); + final DecoratorGroup dg = new DecoratorGroup(); dg.setPaint(Color.magenta); // Put some nodes under the group for it to decorate - PPath p1 = PPath.createEllipse(25, 25, 75, 75); + final PPath p1 = PPath.createEllipse(25, 25, 75, 75); p1.setPaint(Color.red); - PPath p2 = PPath.createRectangle(125, 75, 50, 50); + final PPath p2 = PPath.createRectangle(125, 75, 50, 50); p2.setPaint(Color.blue); // Add everything to the Piccolo hierarchy @@ -87,13 +92,13 @@ getCanvas().getLayer().addChild(dg); // Create a decorator group that IS volatile - VolatileDecoratorGroup vdg = new VolatileDecoratorGroup(getCanvas().getCamera()); + final VolatileDecoratorGroup vdg = new VolatileDecoratorGroup(getCanvas().getCamera()); vdg.setPaint(Color.cyan); // Put some nodes under the group for it to decorate - PPath p3 = PPath.createEllipse(275, 175, 50, 50); + final PPath p3 = PPath.createEllipse(275, 175, 50, 50); p3.setPaint(Color.blue); - PPath p4 = PPath.createRectangle(175, 175, 75, 75); + final PPath p4 = PPath.createRectangle(175, 175, 75, 75); p4.setPaint(Color.green); // Add everything to the Piccolo hierarchy @@ -103,15 +108,15 @@ // Create a selection handler so we can see that the decorator actually // works - ArrayList selectableParents = new ArrayList(); + final ArrayList selectableParents = new ArrayList(); selectableParents.add(dg); selectableParents.add(vdg); - PSelectionEventHandler ps = new PSelectionEventHandler(getCanvas().getLayer(), selectableParents); + final PSelectionEventHandler ps = new PSelectionEventHandler(getCanvas().getLayer(), selectableParents); getCanvas().addInputEventListener(ps); } - public static void main(String[] args) { + public static void main(final String[] args) { new GroupExample(); } } @@ -121,6 +126,11 @@ * background rectangle based on the bounds of its children. */ class DecoratorGroup extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; + int INDENT = 10; PBounds cachedChildBounds = new PBounds(); @@ -134,13 +144,13 @@ * Change the default paint to fill an expanded bounding box based on its * children's bounds */ - public void paint(PPaintContext ppc) { - Paint paint = getPaint(); + public void paint(final PPaintContext ppc) { + final Paint paint = getPaint(); if (paint != null) { - Graphics2D g2 = ppc.getGraphics(); + final Graphics2D g2 = ppc.getGraphics(); g2.setPaint(paint); - PBounds bounds = getUnionOfChildrenBounds(null); + final PBounds bounds = getUnionOfChildrenBounds(null); bounds.setRect(bounds.getX() - INDENT, bounds.getY() - INDENT, bounds.getWidth() + 2 * INDENT, bounds .getHeight() + 2 * INDENT); @@ -153,8 +163,8 @@ * expanding the children's bounds Do this instead of overriding * getBoundsReference() since the node is not volatile */ - public PBounds computeFullBounds(PBounds dstBounds) { - PBounds result = getUnionOfChildrenBounds(dstBounds); + public PBounds computeFullBounds(final PBounds dstBounds) { + final PBounds result = getUnionOfChildrenBounds(dstBounds); cachedChildBounds.setRect(result); result.setRect(result.getX() - INDENT, result.getY() - INDENT, result.getWidth() + 2 * INDENT, result @@ -183,13 +193,18 @@ * background rectangle based on the bounds of its children. */ class VolatileDecoratorGroup extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; + int INDENT = 10; PBounds cachedChildBounds = new PBounds(); PBounds comparisonBounds = new PBounds(); PCamera renderCamera; - public VolatileDecoratorGroup(PCamera camera) { + public VolatileDecoratorGroup(final PCamera camera) { super(); renderCamera = camera; } @@ -206,11 +221,11 @@ * that we are expanding our bounds beyond our children */ public PBounds getBoundsReference() { - PBounds bds = super.getBoundsReference(); + final PBounds bds = super.getBoundsReference(); getUnionOfChildrenBounds(bds); cachedChildBounds.setRect(bds); - double scaledIndent = INDENT / renderCamera.getViewScale(); + final double scaledIndent = INDENT / renderCamera.getViewScale(); bds.setRect(bds.getX() - scaledIndent, bds.getY() - scaledIndent, bds.getWidth() + 2 * scaledIndent, bds .getHeight() + 2 * scaledIndent); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/HandleExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/HandleExample.java index 1e826bf..6b33ddb 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/HandleExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/HandleExample.java @@ -47,16 +47,21 @@ */ public class HandleExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public HandleExample() { this(null); } - public HandleExample(PCanvas aCanvas) { + public HandleExample(final PCanvas aCanvas) { super("HandleExample", false, aCanvas); } public void initialize() { - PPath n = PPath.createRectangle(0, 0, 100, 80); + final PPath n = PPath.createRectangle(0, 0, 100, 80); // add another node the the root as a reference point so that we can // tell that our node is getting dragged, as opposed the the canvas @@ -85,19 +90,24 @@ // around. This handle also updates its color when the is // pressed/released in it. final PHandle h = new PHandle(new PNodeLocator(n)) { + /** + * + */ + private static final long serialVersionUID = 1L; + // the default locator locates the center of a node. - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { localToParent(aLocalDimension); getParent().translate(aLocalDimension.getWidth(), aLocalDimension.getHeight()); } }; h.addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { h.setPaint(Color.YELLOW); } - public void mouseReleased(PInputEvent aEvent) { + public void mouseReleased(final PInputEvent aEvent) { h.setPaint(Color.RED); } }); @@ -111,7 +121,7 @@ n.addChild(h); } - public static void main(String[] args) { + public static void main(final String[] args) { new HandleExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/HelloWorldExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/HelloWorldExample.java index 5a5fbed..5790f4c 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/HelloWorldExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/HelloWorldExample.java @@ -34,20 +34,25 @@ public class HelloWorldExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public HelloWorldExample() { this(null); } - public HelloWorldExample(PCanvas aCanvas) { + public HelloWorldExample(final PCanvas aCanvas) { super("HelloWorldExample", false, aCanvas); } public void initialize() { - PText text = new PText("Hello World"); + final PText text = new PText("Hello World"); getCanvas().getLayer().addChild(text); } - public static void main(String[] args) { + public static void main(final String[] args) { new HelloWorldExample(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/HierarchyZoomExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/HierarchyZoomExample.java index 662e2bf..6c91a85 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/HierarchyZoomExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/HierarchyZoomExample.java @@ -40,30 +40,35 @@ */ public class HierarchyZoomExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public HierarchyZoomExample() { this(null); } - public HierarchyZoomExample(PCanvas aCanvas) { + public HierarchyZoomExample(final PCanvas aCanvas) { super("HierarchyZoomExample", false, aCanvas); } public void initialize() { - PNode root = createHierarchy(10); + final PNode root = createHierarchy(10); getCanvas().getLayer().addChild(root); getCanvas().removeInputEventListener(getCanvas().getPanEventHandler()); getCanvas().addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { getCanvas().getCamera().animateViewToCenterBounds(event.getPickedNode().getGlobalBounds(), true, 500); } }); } - public PNode createHierarchy(int level) { - PPath result = PPath.createRectangle(0, 0, 100, 100); + public PNode createHierarchy(final int level) { + final PPath result = PPath.createRectangle(0, 0, 100, 100); if (level > 0) { - PNode child = createHierarchy(level - 1); + final PNode child = createHierarchy(level - 1); child.scale(0.5); result.addChild(child); child.offset(25, 25); @@ -72,7 +77,7 @@ return result; } - public static void main(String[] args) { + public static void main(final String[] args) { new HierarchyZoomExample(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/KeyEventFocusExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/KeyEventFocusExample.java index 602b600..898214f 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/KeyEventFocusExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/KeyEventFocusExample.java @@ -42,19 +42,24 @@ */ public class KeyEventFocusExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public KeyEventFocusExample() { this(null); } - public KeyEventFocusExample(PCanvas aCanvas) { + public KeyEventFocusExample(final PCanvas aCanvas) { super("KeyEventFocusExample", false, aCanvas); } public void initialize() { // Create a green and red node and add them to canvas layer. - PCanvas canvas = getCanvas(); - PNode nodeGreen = PPath.createRectangle(0, 0, 100, 100); - PNode nodeRed = PPath.createRectangle(0, 0, 100, 100); + final PCanvas canvas = getCanvas(); + final PNode nodeGreen = PPath.createRectangle(0, 0, 100, 100); + final PNode nodeRed = PPath.createRectangle(0, 0, 100, 100); nodeRed.translate(200, 0); nodeGreen.setPaint(Color.green); nodeRed.setPaint(Color.red); @@ -67,7 +72,7 @@ // when // the key is pressed and the event listener has keyboard focus. nodeGreen.addInputEventListener(new PBasicInputEventHandler() { - public void keyPressed(PInputEvent event) { + public void keyPressed(final PInputEvent event) { System.out.println("green keypressed"); } @@ -79,42 +84,42 @@ // with it will set the keyfocus to itself. Now it will receive key // events // until someone else gets the focus. - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { event.getInputManager().setKeyboardFocus(event.getPath()); System.out.println("green mousepressed"); } - public void keyboardFocusGained(PInputEvent event) { + public void keyboardFocusGained(final PInputEvent event) { System.out.println("green focus gained"); } - public void keyboardFocusLost(PInputEvent event) { + public void keyboardFocusLost(final PInputEvent event) { System.out.println("green focus lost"); } }); // do the same thing with the red node. nodeRed.addInputEventListener(new PBasicInputEventHandler() { - public void keyPressed(PInputEvent event) { + public void keyPressed(final PInputEvent event) { System.out.println("red keypressed"); } - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { event.getInputManager().setKeyboardFocus(event.getPath()); System.out.println("red mousepressed"); } - public void keyboardFocusGained(PInputEvent event) { + public void keyboardFocusGained(final PInputEvent event) { System.out.println("red focus gained"); } - public void keyboardFocusLost(PInputEvent event) { + public void keyboardFocusLost(final PInputEvent event) { System.out.println("red focus lost"); } }); } - public static void main(String[] args) { + public static void main(final String[] args) { new KeyEventFocusExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/LayoutExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/LayoutExample.java index 13c7c28..fbaa72e 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/LayoutExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/LayoutExample.java @@ -43,11 +43,16 @@ */ public class LayoutExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public LayoutExample() { this(null); } - public LayoutExample(PCanvas aCanvas) { + public LayoutExample(final PCanvas aCanvas) { super("LayoutExample", false, aCanvas); } @@ -56,13 +61,18 @@ // so that it lays out its children in a row from left to right. final PNode layoutNode = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; + public void layoutChildren() { double xOffset = 0; - double yOffset = 0; + final double yOffset = 0; - Iterator i = getChildrenIterator(); + final Iterator i = getChildrenIterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); each.setOffset(xOffset - each.getX(), yOffset); xOffset += each.getWidth(); } @@ -74,7 +84,7 @@ // add some children to the layout node. for (int i = 0; i < 1000; i++) { // create child to add to the layout node. - PNode each = PPath.createRectangle(0, 0, 100, 80); + final PNode each = PPath.createRectangle(0, 0, 100, 80); // add the child to the layout node. layoutNode.addChild(each); @@ -86,7 +96,7 @@ getCanvas().getLayer().addChild(layoutNode); } - public static void main(String[] args) { + public static void main(final String[] args) { new LayoutExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/LensExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/LensExample.java index f3c0c95..71b5d51 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/LensExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/LensExample.java @@ -51,21 +51,26 @@ */ public class LensExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public LensExample() { this(null); } - public LensExample(PCanvas aCanvas) { + public LensExample(final PCanvas aCanvas) { super("LensExample", false, aCanvas); } public void initialize() { - PRoot root = getCanvas().getRoot(); - PCamera camera = getCanvas().getCamera(); + final PRoot root = getCanvas().getRoot(); + final PCamera camera = getCanvas().getCamera(); // viewed by the PCanvas camera, the lens is added to this layer. - PLayer mainLayer = getCanvas().getLayer(); + final PLayer mainLayer = getCanvas().getLayer(); // viewed by both the lens camera and the PCanvas camera - PLayer sharedLayer = new PLayer(); + final PLayer sharedLayer = new PLayer(); // viewed by only the lens camera final PLayer lensOnlyLayer = new PLayer(); @@ -82,12 +87,12 @@ // Create an event handler that draws squiggles on the first layer of // the bottom most camera. - PDragSequenceEventHandler squiggleEventHandler = new PDragSequenceEventHandler() { + final PDragSequenceEventHandler squiggleEventHandler = new PDragSequenceEventHandler() { protected PPath squiggle; - public void startDrag(PInputEvent e) { + public void startDrag(final PInputEvent e) { super.startDrag(e); - Point2D p = e.getPosition(); + final Point2D p = e.getPosition(); squiggle = new PPath(); squiggle.moveTo((float) p.getX(), (float) p.getY()); @@ -100,19 +105,19 @@ e.getCamera().getLayer(0).addChild(squiggle); } - public void drag(PInputEvent e) { + public void drag(final PInputEvent e) { super.drag(e); updateSquiggle(e); } - public void endDrag(PInputEvent e) { + public void endDrag(final PInputEvent e) { super.endDrag(e); updateSquiggle(e); squiggle = null; } - public void updateSquiggle(PInputEvent aEvent) { - Point2D p = aEvent.getPosition(); + public void updateSquiggle(final PInputEvent aEvent) { + final Point2D p = aEvent.getPosition(); squiggle.lineTo((float) p.getX(), (float) p.getY()); } }; @@ -136,10 +141,15 @@ // create a node that is viewed both by the main camera and by the // lens. Note that in its paint method it checks to see which camera // is painting it, and if its the lens uses a different color. - PNode sharedNode = new PNode() { - protected void paint(PPaintContext paintContext) { + final PNode sharedNode = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; + + protected void paint(final PPaintContext paintContext) { if (paintContext.getCamera() == lens.getCamera()) { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); g2.setPaint(Color.RED); g2.fill(getBoundsReference()); } @@ -153,7 +163,7 @@ sharedNode.translate(200, 200); sharedLayer.addChild(sharedNode); - PText label = new PText( + final PText label = new PText( "Move the lens \n (by dragging title bar) over the green rectangle, and it will appear red. press and drag the mouse on the canvas and it will draw squiggles. press and drag the mouse over the lens and drag squiggles that are only visible through the lens."); label.setConstrainWidthToTextWidth(false); label.setConstrainHeightToTextHeight(false); @@ -162,7 +172,7 @@ sharedLayer.addChild(label); } - public static void main(String[] args) { + public static void main(final String[] args) { new LensExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/NavigationExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/NavigationExample.java index 3d39158..5f8da9a 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/NavigationExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/NavigationExample.java @@ -40,24 +40,29 @@ public class NavigationExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public NavigationExample() { this(null); } - public NavigationExample(PCanvas aCanvas) { + public NavigationExample(final PCanvas aCanvas) { super("NavigationExample", false, aCanvas); } public void initialize() { - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); - Random random = new Random(); + final Random random = new Random(); for (int i = 0; i < 1000; i++) { - PPath each = PPath.createRectangle(0, 0, 100, 80); + final PPath each = PPath.createRectangle(0, 0, 100, 80); each.scale(random.nextFloat() * 2); each.offset(random.nextFloat() * 10000, random.nextFloat() * 10000); each.setPaint(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat())); - each.setStroke(new BasicStroke(1 + (10 * random.nextFloat()))); + each.setStroke(new BasicStroke(1 + 10 * random.nextFloat())); each.setStrokePaint(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat())); layer.addChild(each); } @@ -65,7 +70,7 @@ getCanvas().addInputEventListener(new PNavigationEventHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new NavigationExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeCacheExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeCacheExample.java index 94e4b23..1902f6f 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeCacheExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeCacheExample.java @@ -39,26 +39,31 @@ public class NodeCacheExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public NodeCacheExample() { this(null); } - public NodeCacheExample(PCanvas aCanvas) { + public NodeCacheExample(final PCanvas aCanvas) { super("NodeCacheExample", false, aCanvas); } public void initialize() { - PCanvas canvas = getCanvas(); + final PCanvas canvas = getCanvas(); - PPath circle = PPath.createEllipse(0, 0, 100, 100); + final PPath circle = PPath.createEllipse(0, 0, 100, 100); circle.setStroke(new BasicStroke(10)); circle.setPaint(Color.YELLOW); - PPath rectangle = PPath.createRectangle(-100, -50, 100, 100); + final PPath rectangle = PPath.createRectangle(-100, -50, 100, 100); rectangle.setStroke(new BasicStroke(15)); rectangle.setPaint(Color.ORANGE); - PNodeCache cache = new PNodeCache(); + final PNodeCache cache = new PNodeCache(); cache.addChild(circle); cache.addChild(rectangle); @@ -69,7 +74,7 @@ canvas.addInputEventListener(new PDragEventHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new NodeCacheExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeEventExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeEventExample.java index c8f8869..35e6db9 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeEventExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeEventExample.java @@ -44,16 +44,21 @@ */ public class NodeEventExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public NodeEventExample() { this(null); } - public NodeEventExample(PCanvas aCanvas) { + public NodeEventExample(final PCanvas aCanvas) { super("NodeEventExample", false, aCanvas); } public void initialize() { - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); // create a new node and override some of the event handling // methods so that the node changes to orange when the mouse (Button 1) @@ -70,20 +75,20 @@ // uncomment the aEvent.setHandled() calls and see what happens. final PNode aNode = new PNode(); aNode.addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { aNode.setPaint(Color.orange); printEventCoords(aEvent); aEvent.setHandled(true); } - public void mouseDragged(PInputEvent aEvent) { - Dimension2D delta = aEvent.getDeltaRelativeTo(aNode); + public void mouseDragged(final PInputEvent aEvent) { + final Dimension2D delta = aEvent.getDeltaRelativeTo(aNode); aNode.translate(delta.getWidth(), delta.getHeight()); printEventCoords(aEvent); aEvent.setHandled(true); } - public void mouseReleased(PInputEvent aEvent) { + public void mouseReleased(final PInputEvent aEvent) { aNode.setPaint(Color.green); printEventCoords(aEvent); aEvent.setHandled(true); @@ -99,7 +104,7 @@ // node then the local coordinates become different then the screen // and global coordinates. When you pan or zoom then the screen // coordinates become different from the global coordinates. - public void printEventCoords(PInputEvent aEvent) { + public void printEventCoords(final PInputEvent aEvent) { System.out.println("Canvas Location: " + aEvent.getCanvasPosition()); // System.out.println("Global Location: " + // aEvent.getGlobalLocation()); @@ -126,7 +131,7 @@ layer.addChild(aNode); } - public static void main(String[] args) { + public static void main(final String[] args) { new NodeEventExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeExample.java index 52e1837..e963feb 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeExample.java @@ -52,13 +52,17 @@ */ public class NodeExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; boolean fIsPressed = false; public NodeExample() { this(null); } - public NodeExample(PCanvas aCanvas) { + public NodeExample(final PCanvas aCanvas) { super("NodeExample", false, aCanvas); } @@ -79,8 +83,8 @@ // This method demonstrates the kinds of things that can be done with any // node. public void nodeDemo() { - PLayer layer = getCanvas().getLayer(); - PNode aNode = PPath.createRectangle(0, 0, 100, 80); + final PLayer layer = getCanvas().getLayer(); + final PNode aNode = PPath.createRectangle(0, 0, 100, 80); // A node needs to be a descendent of the root to be displayed on the // screen. @@ -109,7 +113,7 @@ aNode.setTransparency(0.75f); // Its easy to copy nodes. - PNode aCopy = (PNode) aNode.clone(); + final PNode aCopy = (PNode) aNode.clone(); // Make is so that the copies children are not pickable. For this // example @@ -131,7 +135,7 @@ // So far we have just been using PNode, but of course PNode has many // subclasses that you can try out to. public void createNodeUsingExistingClasses() { - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); layer.addChild(PPath.createEllipse(0, 0, 100, 100)); layer.addChild(PPath.createRectangle(0, 100, 100, 100)); layer.addChild(new PText("Hello World")); @@ -139,7 +143,7 @@ // Here we create an image node that displays a thumbnail // image of the root node. Note that you can easily get a thumbnail // of any node by using PNode.toImage(). - PImage image = new PImage(layer.toImage(300, 300, null)); + final PImage image = new PImage(layer.toImage(300, 300, null)); layer.addChild(image); } @@ -150,10 +154,15 @@ public void subclassExistingClasses() { final PNode n = new PPath(new Ellipse2D.Float(0, 0, 100, 80)) { - public void paint(PPaintContext aPaintContext) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void paint(final PPaintContext aPaintContext) { if (fIsPressed) { // if mouse is pressed draw self as a square. - Graphics2D g2 = aPaintContext.getGraphics(); + final Graphics2D g2 = aPaintContext.getGraphics(); g2.setPaint(getPaint()); g2.fill(getBoundsReference()); } @@ -165,18 +174,18 @@ }; n.addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { super.mousePressed(aEvent); fIsPressed = true; n.invalidatePaint(); // this tells the framework that the node - // needs to be redisplayed. + // needs to be redisplayed. } - public void mouseReleased(PInputEvent aEvent) { + public void mouseReleased(final PInputEvent aEvent) { super.mousePressed(aEvent); fIsPressed = false; n.invalidatePaint(); // this tells the framework that the node - // needs to be redisplayed. + // needs to be redisplayed. } }); @@ -188,13 +197,13 @@ // directly // using Graphics2D we compose the face from other nodes. public void composeOtherNodes() { - PNode myCompositeFace = PPath.createRectangle(0, 0, 100, 80); + final PNode myCompositeFace = PPath.createRectangle(0, 0, 100, 80); // create parts for the face. - PNode eye1 = PPath.createEllipse(0, 0, 20, 20); + final PNode eye1 = PPath.createEllipse(0, 0, 20, 20); eye1.setPaint(Color.YELLOW); - PNode eye2 = (PNode) eye1.clone(); - PNode mouth = PPath.createRectangle(0, 0, 40, 20); + final PNode eye2 = (PNode) eye1.clone(); + final PNode mouth = PPath.createRectangle(0, 0, 40, 20); mouth.setPaint(Color.BLACK); // add the face parts @@ -210,7 +219,7 @@ mouth.translate(0, 30); // set the face bounds so that it neatly contains the face parts. - PBounds b = myCompositeFace.getUnionOfChildrenBounds(null); + final PBounds b = myCompositeFace.getUnionOfChildrenBounds(null); myCompositeFace.setBounds(b.inset(-5, -5)); // opps it to small, so scale it up. @@ -223,15 +232,20 @@ // all the drawing ourselves here instead of passing the work off to // other parts of the framework. public void createCustomNode() { - PNode n = new PNode() { - public void paint(PPaintContext aPaintContext) { - double bx = getX(); - double by = getY(); - double rightBorder = bx + getWidth(); - double bottomBorder = by + getHeight(); + final PNode n = new PNode() { + /** + * + */ + private static final long serialVersionUID = 1L; - Line2D line = new Line2D.Double(); - Graphics2D g2 = aPaintContext.getGraphics(); + public void paint(final PPaintContext aPaintContext) { + final double bx = getX(); + final double by = getY(); + final double rightBorder = bx + getWidth(); + final double bottomBorder = by + getHeight(); + + final Line2D line = new Line2D.Double(); + final Graphics2D g2 = aPaintContext.getGraphics(); g2.setStroke(new BasicStroke(0)); g2.setPaint(getPaint()); @@ -253,7 +267,7 @@ getCanvas().getLayer().addChild(n); } - public static void main(String[] args) { + public static void main(final String[] args) { new NodeExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeLinkExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeLinkExample.java index 9d93ea8..17ca6b4 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeLinkExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/NodeLinkExample.java @@ -46,6 +46,10 @@ */ public class NodeLinkExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; PNode node1; PNode node2; PPath link; @@ -54,17 +58,17 @@ this(null); } - public NodeLinkExample(PCanvas aCanvas) { + public NodeLinkExample(final PCanvas aCanvas) { super("NodeLinkExample", false, aCanvas); } public void initialize() { - PCanvas canvas = getCanvas(); + final PCanvas canvas = getCanvas(); canvas.removeInputEventListener(canvas.getPanEventHandler()); canvas.addInputEventListener(new PDragEventHandler()); - PNode layer = canvas.getLayer(); + final PNode layer = canvas.getLayer(); node1 = PPath.createEllipse(0, 0, 100, 100); node2 = PPath.createEllipse(0, 0, 100, 100); @@ -77,26 +81,26 @@ node2.translate(200, 200); node1.addPropertyChangeListener(PNode.PROPERTY_FULL_BOUNDS, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent arg0) { + public void propertyChange(final PropertyChangeEvent arg0) { updateLink(); } }); node2.addPropertyChangeListener(PNode.PROPERTY_FULL_BOUNDS, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent arg0) { + public void propertyChange(final PropertyChangeEvent arg0) { updateLink(); } }); } public void updateLink() { - Point2D p1 = node1.getFullBoundsReference().getCenter2D(); - Point2D p2 = node2.getFullBoundsReference().getCenter2D(); - Line2D line = new Line2D.Double(p1.getX(), p1.getY(), p2.getX(), p2.getY()); + final Point2D p1 = node1.getFullBoundsReference().getCenter2D(); + final Point2D p2 = node2.getFullBoundsReference().getCenter2D(); + final Line2D line = new Line2D.Double(p1.getX(), p1.getY(), p2.getX(), p2.getY()); link.setPathTo(line); } - public static void main(String[] args) { + public static void main(final String[] args) { new NodeLinkExample(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/OffscreenCanvasExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/OffscreenCanvasExample.java index 0ddf29c..64028a9 100755 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/OffscreenCanvasExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/OffscreenCanvasExample.java @@ -57,14 +57,13 @@ /** Offscreen canvas. */ private final POffscreenCanvas canvas; - /** * Create a new offscreen canvas example with the specified graphics device. - * + * * @param device graphics device */ public OffscreenCanvasExample(final GraphicsDevice device) { - GraphicsConfiguration configuration = device.getDefaultConfiguration(); + final GraphicsConfiguration configuration = device.getDefaultConfiguration(); frame = new Frame(configuration); frame.setUndecorated(true); frame.setIgnoreRepaint(true); @@ -74,12 +73,12 @@ canvas = new POffscreenCanvas(400, 400); - PText text = new PText("Offscreen Canvas Example"); + final PText text = new PText("Offscreen Canvas Example"); text.setFont(text.getFont().deriveFont(32.0f)); text.setTextPaint(new Color(200, 200, 200)); - text.offset(200.0f - (text.getWidth() / 2.0f), 200.0f - (text.getHeight() / 2.0f)); + text.offset(200.0f - text.getWidth() / 2.0f, 200.0f - text.getHeight() / 2.0f); - PPath rect = PPath.createRectangle(0.0f, 0.0f, 360.0f, 360.0f); + final PPath rect = PPath.createRectangle(0.0f, 0.0f, 360.0f, 360.0f); rect.setPaint(new Color(20, 20, 20, 80)); rect.setStroke(new BasicStroke(2.0f)); rect.setStrokePaint(new Color(20, 20, 20)); @@ -88,50 +87,46 @@ canvas.getCamera().getLayer(0).addChild(text); canvas.getCamera().getLayer(0).addChild(rect); - Rectangle2D right = new Rectangle2D.Double(200.0f, 200.0f, 800.0f, 800.0f); - Rectangle2D left = new Rectangle2D.Double(-200.0f, 200.0f, 225.0f, 225.0f); - Rectangle2D start = new Rectangle2D.Double(0.0f, 0.0f, 400.0f, 400.0f); - PActivity toRight = canvas.getCamera().animateViewToCenterBounds(right, true, 5000); - PActivity toLeft = canvas.getCamera().animateViewToCenterBounds(left, true, 5000); - PActivity toStart = canvas.getCamera().animateViewToCenterBounds(start, true, 5000); + final Rectangle2D right = new Rectangle2D.Double(200.0f, 200.0f, 800.0f, 800.0f); + final Rectangle2D left = new Rectangle2D.Double(-200.0f, 200.0f, 225.0f, 225.0f); + final Rectangle2D start = new Rectangle2D.Double(0.0f, 0.0f, 400.0f, 400.0f); + final PActivity toRight = canvas.getCamera().animateViewToCenterBounds(right, true, 5000); + final PActivity toLeft = canvas.getCamera().animateViewToCenterBounds(left, true, 5000); + final PActivity toStart = canvas.getCamera().animateViewToCenterBounds(start, true, 5000); toLeft.setStartTime(toLeft.getStartTime() + 5000); toStart.setStartTime(toStart.getStartTime() + 10000); } - /** * Render offscreen graphics into the frame. */ private void render() { - BufferStrategy bufferStrategy = frame.getBufferStrategy(); + final BufferStrategy bufferStrategy = frame.getBufferStrategy(); do { do { - Graphics2D graphics = (Graphics2D) bufferStrategy.getDrawGraphics(); + final Graphics2D graphics = (Graphics2D) bufferStrategy.getDrawGraphics(); // canvas is not opaque, so fill with background color graphics.setPaint(background); graphics.fillRect(0, 0, 400, 400); // then let canvas render into graphics canvas.render(graphics); graphics.dispose(); - } - while (bufferStrategy.contentsRestored()); + } while (bufferStrategy.contentsRestored()); bufferStrategy.show(); - } - while (bufferStrategy.contentsLost()); + } while (bufferStrategy.contentsLost()); } - /** * Main. - * + * * @param args command line arguments */ public static void main(final String[] args) { - GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); - GraphicsDevice device = environment.getDefaultScreenDevice(); - OffscreenCanvasExample example = new OffscreenCanvasExample(device); + final GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); + final GraphicsDevice device = environment.getDefaultScreenDevice(); + final OffscreenCanvasExample example = new OffscreenCanvasExample(device); - boolean done = false; + final boolean done = false; while (!done) { example.render(); } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PSwingExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PSwingExample.java index 00222b5..88e7231 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PSwingExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PSwingExample.java @@ -28,49 +28,55 @@ */ package edu.umd.cs.piccolo.examples; +import javax.swing.BorderFactory; +import javax.swing.JSlider; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + import edu.umd.cs.piccolo.PCanvas; import edu.umd.cs.piccolo.PLayer; import edu.umd.cs.piccolox.PFrame; import edu.umd.cs.piccolox.pswing.PSwing; import edu.umd.cs.piccolox.pswing.PSwingCanvas; -import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - /** * Demonstrates the use of PSwing in a Piccolo application. */ public class PSwingExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PSwingExample() { this(new PSwingCanvas()); } - public PSwingExample(PCanvas aCanvas) { + public PSwingExample(final PCanvas aCanvas) { super("PSwingExample", false, aCanvas); } public void initialize() { - PSwingCanvas pswingCanvas = (PSwingCanvas) getCanvas(); - PLayer l = pswingCanvas.getLayer(); + final PSwingCanvas pswingCanvas = (PSwingCanvas) getCanvas(); + final PLayer l = pswingCanvas.getLayer(); - JSlider js = new JSlider(0, 100); + final JSlider js = new JSlider(0, 100); js.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent e) { + public void stateChanged(final ChangeEvent e) { System.out.println("e = " + e); } }); js.setBorder(BorderFactory.createTitledBorder("Test JSlider")); - PSwing pSwing = new PSwing(js); + final PSwing pSwing = new PSwing(js); pSwing.translate(100, 100); l.addChild(pSwing); pswingCanvas.setPanEventHandler(null); } - public static void main(String[] args) { + public static void main(final String[] args) { new PSwingExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PanToExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PanToExample.java index 15f9579..0b0c2ea 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PanToExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PanToExample.java @@ -46,11 +46,16 @@ */ public class PanToExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PanToExample() { this(null); } - public PanToExample(PCanvas aCanvas) { + public PanToExample(final PCanvas aCanvas) { super("PanToExample", false, aCanvas); } @@ -69,7 +74,7 @@ getCanvas().getLayer().addChild(eacha); getCanvas().getCamera().addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { if (!(event.getPickedNode() instanceof PCamera)) { event.setHandled(true); getCanvas().getCamera().animateViewToPanToBounds(event.getPickedNode().getGlobalFullBounds(), 500); @@ -77,15 +82,15 @@ } }); - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); - Random random = new Random(); + final Random random = new Random(); for (int i = 0; i < 1000; i++) { - PPath each = PPath.createRectangle(0, 0, 100, 80); + final PPath each = PPath.createRectangle(0, 0, 100, 80); each.scale(random.nextFloat() * 2); each.offset(random.nextFloat() * 10000, random.nextFloat() * 10000); each.setPaint(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat())); - each.setStroke(new BasicStroke(1 + (10 * random.nextFloat()))); + each.setStroke(new BasicStroke(1 + 10 * random.nextFloat())); each.setStrokePaint(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat())); layer.addChild(each); } @@ -93,7 +98,7 @@ getCanvas().removeInputEventListener(getCanvas().getZoomEventHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new PanToExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PathExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PathExample.java index ba76c86..4809154 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PathExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PathExample.java @@ -40,18 +40,23 @@ public class PathExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PathExample() { this(null); } - public PathExample(PCanvas aCanvas) { + public PathExample(final PCanvas aCanvas) { super("PathExample", false, aCanvas); } public void initialize() { - PPath n1 = PPath.createRectangle(0, 0, 100, 80); - PPath n2 = PPath.createEllipse(100, 100, 200, 34); - PPath n3 = new PPath(); + final PPath n1 = PPath.createRectangle(0, 0, 100, 80); + final PPath n2 = PPath.createEllipse(100, 100, 200, 34); + final PPath n3 = new PPath(); n3.moveTo(0, 0); n3.lineTo(20, 40); n3.lineTo(10, 200); @@ -77,7 +82,7 @@ getCanvas().addInputEventListener(new PDragEventHandler()); } - public static void main(String[] args) { + public static void main(final String[] args) { new PathExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionExample.java index dadd375..a4051b0 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionExample.java @@ -37,17 +37,22 @@ public class PositionExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PositionExample() { this(null); } - public PositionExample(PCanvas aCanvas) { + public PositionExample(final PCanvas aCanvas) { super("PositionExample", false, aCanvas); } public void initialize() { - PNode n1 = PPath.createRectangle(0, 0, 100, 80); - PNode n2 = PPath.createRectangle(0, 0, 100, 80); + final PNode n1 = PPath.createRectangle(0, 0, 100, 80); + final PNode n2 = PPath.createRectangle(0, 0, 100, 80); getCanvas().getLayer().addChild(n1); getCanvas().getLayer().addChild(n2); @@ -63,7 +68,7 @@ n2.offset(100, 0); } - public static void main(String[] args) { + public static void main(final String[] args) { new PositionExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionPathActivityExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionPathActivityExample.java index 1c48439..4402395 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionPathActivityExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PositionPathActivityExample.java @@ -43,17 +43,22 @@ */ public class PositionPathActivityExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PositionPathActivityExample() { super(); } public void initialize() { - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); final PNode animatedNode = PPath.createRectangle(0, 0, 100, 80); layer.addChild(animatedNode); // create animation path - GeneralPath path = new GeneralPath(); + final GeneralPath path = new GeneralPath(); path.moveTo(0, 0); path.lineTo(300, 300); path.lineTo(300, 0); @@ -61,13 +66,13 @@ path.closePath(); // create node to display animation path - PPath ppath = new PPath(path); + final PPath ppath = new PPath(path); layer.addChild(ppath); // create activity to run animation. - PPositionPathActivity positionPathActivity = new PPositionPathActivity(5000, 0, + final PPositionPathActivity positionPathActivity = new PPositionPathActivity(5000, 0, new PPositionPathActivity.Target() { - public void setPosition(double x, double y) { + public void setPosition(final double x, final double y) { animatedNode.setOffset(x, y); } }); @@ -79,7 +84,7 @@ animatedNode.addActivity(positionPathActivity); } - public static void main(String[] args) { + public static void main(final String[] args) { new PositionPathActivityExample(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PrintExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PrintExample.java index ae0bc25..2b1d651 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PrintExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PrintExample.java @@ -69,11 +69,16 @@ */ public class PrintExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PrintExample() { this(null); } - public PrintExample(PCanvas aCanvas) { + public PrintExample(final PCanvas aCanvas) { super("ScrollingExample", false, aCanvas); } @@ -87,14 +92,14 @@ // Make some rectangles on the surface so we can see where we are for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { - if (((x + y) % 2) == 0) { - PPath path = PPath.createRectangle(50 * x, 50 * y, 40, 40); + if ((x + y) % 2 == 0) { + final PPath path = PPath.createRectangle(50 * x, 50 * y, 40, 40); path.setPaint(Color.blue); path.setStrokePaint(Color.black); canvas.getLayer().addChild(path); } - else if (((x + y) % 2) == 1) { - PPath path = PPath.createEllipse(50 * x, 50 * y, 40, 40); + else if ((x + y) % 2 == 1) { + final PPath path = PPath.createEllipse(50 * x, 50 * y, 40, 40); path.setPaint(Color.blue); path.setStrokePaint(Color.black); canvas.getLayer().addChild(path); @@ -103,11 +108,11 @@ } // Now, create the toolbar - JToolBar toolBar = new JToolBar(); - JToggleButton window = new JToggleButton("Window Scrolling"); - JToggleButton document = new JToggleButton("Document Scrolling"); - JButton print = new JButton("Print"); - ButtonGroup bg = new ButtonGroup(); + final JToolBar toolBar = new JToolBar(); + final JToggleButton window = new JToggleButton("Window Scrolling"); + final JToggleButton document = new JToggleButton("Document Scrolling"); + final JButton print = new JButton("Print"); + final ButtonGroup bg = new ButtonGroup(); bg.add(window); bg.add(document); toolBar.add(window); @@ -117,7 +122,7 @@ toolBar.setFloatable(false); window.setSelected(true); window.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + public void actionPerformed(final ActionEvent ae) { viewport.setScrollDirector(windowSD); viewport.fireStateChanged(); scrollPane.revalidate(); @@ -125,7 +130,7 @@ } }); document.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + public void actionPerformed(final ActionEvent ae) { viewport.setScrollDirector(documentSD); viewport.fireStateChanged(); scrollPane.revalidate(); @@ -133,16 +138,16 @@ } }); print.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + public void actionPerformed(final ActionEvent ae) { try { print(); } - catch (PrinterException e) { + catch (final PrinterException e) { JOptionPane.showMessageDialog(PrintExample.this, "An error occured while printing"); } } }); - JPanel contentPane = new JPanel(); + final JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); contentPane.add("Center", scrollPane); contentPane.add("North", toolBar); @@ -171,14 +176,14 @@ * computed * @return The view position */ - public Point getViewPosition(Rectangle2D viewBounds) { - Point pos = new Point(); + public Point getViewPosition(final Rectangle2D viewBounds) { + final Point pos = new Point(); if (camera != null) { // First we compute the union of all the layers - PBounds layerBounds = new PBounds(); - java.util.List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final java.util.List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } @@ -210,7 +215,7 @@ * @param x The new x position * @param y The new y position */ - public void setViewPosition(double x, double y) { + public void setViewPosition(final double x, final double y) { if (camera != null) { // If a scroll is in progress - we ignore new scrolls - // if we didn't, since the scrollbars depend on the camera @@ -220,18 +225,18 @@ scrollInProgress = true; // Get the union of all the layers' bounds - PBounds layerBounds = new PBounds(); - java.util.List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final java.util.List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } - PAffineTransform at = camera.getViewTransform(); + final PAffineTransform at = camera.getViewTransform(); at.transform(layerBounds, layerBounds); // Union the camera view bounds - PBounds viewBounds = camera.getBoundsReference(); + final PBounds viewBounds = camera.getBoundsReference(); layerBounds.add(viewBounds); // Now find the new view position in view coordinates - @@ -240,7 +245,7 @@ // document // We then measure the offset from the lower right corner // of the document - Point2D newPoint = new Point2D.Double(layerBounds.getX() + layerBounds.getWidth() + final Point2D newPoint = new Point2D.Double(layerBounds.getX() + layerBounds.getWidth() - (x + viewBounds.getWidth()), layerBounds.getY() + layerBounds.getHeight() - (y + viewBounds.getHeight())); @@ -249,8 +254,8 @@ // Compute the new matrix values to put the camera at the // correct location - double newX = -(at.getScaleX() * newPoint.getX() + at.getShearX() * newPoint.getY()); - double newY = -(at.getShearY() * newPoint.getX() + at.getScaleY() * newPoint.getY()); + final double newX = -(at.getScaleX() * newPoint.getX() + at.getShearX() * newPoint.getY()); + final double newY = -(at.getShearY() * newPoint.getX() + at.getScaleY() * newPoint.getY()); at.setTransform(at.getScaleX(), at.getShearY(), at.getShearX(), at.getScaleY(), newX, newY); @@ -268,17 +273,18 @@ * @throws PrinterException */ private void print() throws PrinterException { - PrinterJob printJob = PrinterJob.getPrinterJob(); + final PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(new Printable() { - public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { + public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) + throws PrinterException { if (pageIndex > 0) { - return (NO_SUCH_PAGE); + return NO_SUCH_PAGE; } else { - Graphics2D g2 = (Graphics2D) graphics; + final Graphics2D g2 = (Graphics2D) graphics; g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); getCanvas().printAll(g2); - return (PAGE_EXISTS); + return PAGE_EXISTS; } } }); @@ -287,7 +293,7 @@ } } - public static void main(String[] args) { + public static void main(final String[] args) { new PrintExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/PulseExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/PulseExample.java index b1eb6ca..d82a26a 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/PulseExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/PulseExample.java @@ -48,18 +48,23 @@ */ public class PulseExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PulseExample() { this(null); } - public PulseExample(PCanvas aCanvas) { + public PulseExample(final PCanvas aCanvas) { super("PulseExample", false, aCanvas); } public void initialize() { - PRoot root = getCanvas().getRoot(); - PLayer layer = getCanvas().getLayer(); - PActivityScheduler scheduler = root.getActivityScheduler(); + final PRoot root = getCanvas().getRoot(); + final PLayer layer = getCanvas().getLayer(); + final PActivityScheduler scheduler = root.getActivityScheduler(); final PNode singlePulse = PPath.createRectangle(0, 0, 100, 80); final PPath repeatePulse = PPath.createRectangle(100, 80, 100, 80); @@ -70,38 +75,38 @@ layer.addChild(repeateReversePulse); // animate from source to destination color in one second, - PColorActivity singlePulseActivity = new PColorActivity(1000, 0, 1, + final PColorActivity singlePulseActivity = new PColorActivity(1000, 0, 1, PInterpolatingActivity.SOURCE_TO_DESTINATION, new PColorActivity.Target() { public Color getColor() { return (Color) singlePulse.getPaint(); } - public void setColor(Color color) { + public void setColor(final Color color) { singlePulse.setPaint(color); } }, Color.ORANGE); // animate from source to destination color in one second, loop 5 times - PColorActivity repeatPulseActivity = new PColorActivity(1000, 0, 5, + final PColorActivity repeatPulseActivity = new PColorActivity(1000, 0, 5, PInterpolatingActivity.SOURCE_TO_DESTINATION, new PColorActivity.Target() { public Color getColor() { return (Color) repeatePulse.getPaint(); } - public void setColor(Color color) { + public void setColor(final Color color) { repeatePulse.setPaint(color); } }, Color.BLUE); // animate from source to destination to source color in one second, // loop 10 times - PColorActivity repeatReversePulseActivity = new PColorActivity(500, 0, 10, + final PColorActivity repeatReversePulseActivity = new PColorActivity(500, 0, 10, PInterpolatingActivity.SOURCE_TO_DESTINATION_TO_SOURCE, new PColorActivity.Target() { public Color getColor() { return (Color) repeateReversePulse.getPaint(); } - public void setColor(Color color) { + public void setColor(final Color color) { repeateReversePulse.setPaint(color); } }, Color.GREEN); @@ -111,7 +116,7 @@ scheduler.addActivity(repeatReversePulseActivity); } - public static void main(String[] args) { + public static void main(final String[] args) { new PulseExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/ScrollingExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/ScrollingExample.java index ae2f77d..89d6ee3 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/ScrollingExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/ScrollingExample.java @@ -68,11 +68,16 @@ */ public class ScrollingExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public ScrollingExample() { this(null); } - public ScrollingExample(PCanvas aCanvas) { + public ScrollingExample(final PCanvas aCanvas) { super("ScrollingExample", false, aCanvas); } @@ -86,14 +91,14 @@ // Make some rectangles on the surface so we can see where we are for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { - if (((x + y) % 2) == 0) { - PPath path = PPath.createRectangle(50 * x, 50 * y, 40, 40); + if ((x + y) % 2 == 0) { + final PPath path = PPath.createRectangle(50 * x, 50 * y, 40, 40); path.setPaint(Color.blue); path.setStrokePaint(Color.black); canvas.getLayer().addChild(path); } - else if (((x + y) % 2) == 1) { - PPath path = PPath.createEllipse(50 * x, 50 * y, 40, 40); + else if ((x + y) % 2 == 1) { + final PPath path = PPath.createEllipse(50 * x, 50 * y, 40, 40); path.setPaint(Color.blue); path.setStrokePaint(Color.black); canvas.getLayer().addChild(path); @@ -102,10 +107,10 @@ } // Now, create the toolbar - JToolBar toolBar = new JToolBar(); - JToggleButton window = new JToggleButton("Window Scrolling"); - JToggleButton document = new JToggleButton("Document Scrolling"); - ButtonGroup bg = new ButtonGroup(); + final JToolBar toolBar = new JToolBar(); + final JToggleButton window = new JToggleButton("Window Scrolling"); + final JToggleButton document = new JToggleButton("Document Scrolling"); + final ButtonGroup bg = new ButtonGroup(); bg.add(window); bg.add(document); toolBar.add(window); @@ -113,7 +118,7 @@ toolBar.setFloatable(false); window.setSelected(true); window.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + public void actionPerformed(final ActionEvent ae) { viewport.setScrollDirector(windowSD); viewport.fireStateChanged(); scrollPane.revalidate(); @@ -121,7 +126,7 @@ } }); document.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + public void actionPerformed(final ActionEvent ae) { viewport.setScrollDirector(documentSD); viewport.fireStateChanged(); scrollPane.revalidate(); @@ -129,7 +134,7 @@ } }); - JPanel contentPane = new JPanel(); + final JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); contentPane.add("Center", scrollPane); contentPane.add("North", toolBar); @@ -158,14 +163,14 @@ * computed * @return The view position */ - public Point getViewPosition(Rectangle2D viewBounds) { - Point pos = new Point(); + public Point getViewPosition(final Rectangle2D viewBounds) { + final Point pos = new Point(); if (camera != null) { // First we compute the union of all the layers - PBounds layerBounds = new PBounds(); - java.util.List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final java.util.List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } @@ -197,7 +202,7 @@ * @param x The new x position * @param y The new y position */ - public void setViewPosition(double x, double y) { + public void setViewPosition(final double x, final double y) { if (camera != null) { // If a scroll is in progress - we ignore new scrolls - // if we didn't, since the scrollbars depend on the camera @@ -207,18 +212,18 @@ scrollInProgress = true; // Get the union of all the layers' bounds - PBounds layerBounds = new PBounds(); - java.util.List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final java.util.List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } - PAffineTransform at = camera.getViewTransform(); + final PAffineTransform at = camera.getViewTransform(); at.transform(layerBounds, layerBounds); // Union the camera view bounds - PBounds viewBounds = camera.getBoundsReference(); + final PBounds viewBounds = camera.getBoundsReference(); layerBounds.add(viewBounds); // Now find the new view position in view coordinates - @@ -227,7 +232,7 @@ // document // We then measure the offset from the lower right corner // of the document - Point2D newPoint = new Point2D.Double(layerBounds.getX() + layerBounds.getWidth() + final Point2D newPoint = new Point2D.Double(layerBounds.getX() + layerBounds.getWidth() - (x + viewBounds.getWidth()), layerBounds.getY() + layerBounds.getHeight() - (y + viewBounds.getHeight())); @@ -236,8 +241,8 @@ // Compute the new matrix values to put the camera at the // correct location - double newX = -(at.getScaleX() * newPoint.getX() + at.getShearX() * newPoint.getY()); - double newY = -(at.getShearY() * newPoint.getX() + at.getScaleY() * newPoint.getY()); + final double newX = -(at.getScaleX() * newPoint.getX() + at.getShearX() * newPoint.getY()); + final double newY = -(at.getShearY() * newPoint.getX() + at.getScaleY() * newPoint.getY()); at.setTransform(at.getScaleX(), at.getShearY(), at.getShearX(), at.getScaleY(), newX, newY); @@ -249,7 +254,7 @@ } } - public static void main(String[] args) { + public static void main(final String[] args) { new ScrollingExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/SelectionExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/SelectionExample.java index 2f5f027..091f945 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/SelectionExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/SelectionExample.java @@ -44,18 +44,23 @@ */ public class SelectionExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public SelectionExample() { this(null); } - public SelectionExample(PCanvas aCanvas) { + public SelectionExample(final PCanvas aCanvas) { super("SelectionExample", false, aCanvas); } public void initialize() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { - PNode rect = PPath.createRectangle(i * 60, j * 60, 50, 50); + final PNode rect = PPath.createRectangle(i * 60, j * 60, 50, 50); rect.setPaint(Color.blue); getCanvas().getLayer().addChild(rect); } @@ -66,8 +71,8 @@ getCanvas().removeInputEventListener(getCanvas().getZoomEventHandler()); // Create a selection event handler - PSelectionEventHandler selectionEventHandler = new PSelectionEventHandler(getCanvas().getLayer(), getCanvas() - .getLayer()); + final PSelectionEventHandler selectionEventHandler = new PSelectionEventHandler(getCanvas().getLayer(), + getCanvas().getLayer()); getCanvas().addInputEventListener(selectionEventHandler); getCanvas().getRoot().getDefaultInputManager().setKeyboardFocus(selectionEventHandler); @@ -75,11 +80,11 @@ PSelectionEventHandler.SELECTION_CHANGED_NOTIFICATION, selectionEventHandler); } - public void selectionChanged(PNotification notfication) { + public void selectionChanged(final PNotification notfication) { System.out.println("selection changed"); } - public static void main(String[] args) { + public static void main(final String[] args) { new SelectionExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/SliderExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/SliderExample.java index 98de6c2..e4846fa 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/SliderExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/SliderExample.java @@ -28,30 +28,46 @@ */ package edu.umd.cs.piccolo.examples; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JTabbedPane; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import javax.swing.border.EmptyBorder; + import edu.umd.cs.piccolox.pswing.PSwing; import edu.umd.cs.piccolox.pswing.PSwingCanvas; import edu.umd.cs.piccolox.swing.PScrollPane; -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - /** * Tests a set of Sliders and Checkboxes in panels. * * @author Martin Clifford */ public class SliderExample extends JFrame { - private PSwingCanvas canvas; - private PScrollPane scrollPane; - private JTabbedPane tabbedPane; - private PSwing swing; + /** + * + */ + private static final long serialVersionUID = 1L; + private final PSwingCanvas canvas; + private final PScrollPane scrollPane; + private final JTabbedPane tabbedPane; + private final PSwing swing; public SliderExample() { // Create main panel - JPanel mainPanel = new JPanel(false); + final JPanel mainPanel = new JPanel(false); // Create a tabbed pane tabbedPane = new JTabbedPane(); tabbedPane.setPreferredSize(new Dimension(700, 700)); @@ -69,7 +85,7 @@ tabbedPane.add("Tab 1", scrollPane); // Create the contents for "Tab 1" - JPanel tabPanel = new JPanel(false); + final JPanel tabPanel = new JPanel(false); tabPanel.setLayout(null); tabPanel.setPreferredSize(new Dimension(700, 700)); // Populate the tab panel with four instances of nested panel. @@ -91,9 +107,9 @@ panel.setLocation(350, 350); tabPanel.add(panel); // Add the default zoom button - JButton buttonPreset = new JButton("Zoom = 100%"); + final JButton buttonPreset = new JButton("Zoom = 100%"); buttonPreset.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(final ActionEvent e) { canvas.getCamera().setViewScale(1.0); canvas.getCamera().setViewOffset(0, 0); } @@ -127,19 +143,19 @@ label = new JLabel("A Panel within a panel"); label.setHorizontalAlignment(SwingConstants.CENTER); label.setForeground(Color.white); - JLabel label2 = new JLabel("A Panel within a panel"); + final JLabel label2 = new JLabel("A Panel within a panel"); label2.setHorizontalAlignment(SwingConstants.CENTER); - JSlider slider = new JSlider(); - JCheckBox cbox1 = new JCheckBox("Checkbox 1"); - JCheckBox cbox2 = new JCheckBox("Checkbox 2"); - JPanel panel3 = new JPanel(false); + final JSlider slider = new JSlider(); + final JCheckBox cbox1 = new JCheckBox("Checkbox 1"); + final JCheckBox cbox2 = new JCheckBox("Checkbox 2"); + final JPanel panel3 = new JPanel(false); panel3.setLayout(new BoxLayout(panel3, BoxLayout.PAGE_AXIS)); panel3.setBorder(new EmptyBorder(3, 3, 3, 3)); panel3.add(label2); panel3.add(slider); panel3.add(cbox1); panel3.add(cbox2); - JPanel panel2 = new JPanel(false); + final JPanel panel2 = new JPanel(false); panel2.setBackground(Color.blue); panel.setBorder(new EmptyBorder(1, 1, 1, 1)); panel2.add(label); @@ -152,7 +168,7 @@ return panel; } - public static void main(String[] args) { + public static void main(final String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SliderExample(); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/SquiggleExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/SquiggleExample.java index 0c0130e..a6d2023 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/SquiggleExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/SquiggleExample.java @@ -43,19 +43,23 @@ public class SquiggleExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; private PLayer layer; public SquiggleExample() { this(null); } - public SquiggleExample(PCanvas aCanvas) { + public SquiggleExample(final PCanvas aCanvas) { super("SquiggleExample", false, aCanvas); } public void initialize() { super.initialize(); - PBasicInputEventHandler squiggleEventHandler = createSquiggleEventHandler(); + final PBasicInputEventHandler squiggleEventHandler = createSquiggleEventHandler(); squiggleEventHandler.setEventFilter(new PInputEventFilter(InputEvent.BUTTON1_MASK)); getCanvas().removeInputEventListener(getCanvas().getPanEventHandler()); getCanvas().addInputEventListener(squiggleEventHandler); @@ -67,10 +71,10 @@ protected PPath squiggle; - public void startDrag(PInputEvent e) { + public void startDrag(final PInputEvent e) { super.startDrag(e); - Point2D p = e.getPosition(); + final Point2D p = e.getPosition(); squiggle = new PPath(); squiggle.moveTo((float) p.getX(), (float) p.getY()); @@ -78,25 +82,25 @@ layer.addChild(squiggle); } - public void drag(PInputEvent e) { + public void drag(final PInputEvent e) { super.drag(e); updateSquiggle(e); } - public void endDrag(PInputEvent e) { + public void endDrag(final PInputEvent e) { super.endDrag(e); updateSquiggle(e); squiggle = null; } - public void updateSquiggle(PInputEvent aEvent) { - Point2D p = aEvent.getPosition(); + public void updateSquiggle(final PInputEvent aEvent) { + final Point2D p = aEvent.getPosition(); squiggle.lineTo((float) p.getX(), (float) p.getY()); } }; } - public static void main(String[] args) { + public static void main(final String[] args) { new SquiggleExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyExample.java index 169abb8..0a72767 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyExample.java @@ -37,16 +37,21 @@ public class StickyExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public StickyExample() { this(null); } - public StickyExample(PCanvas aCanvas) { + public StickyExample(final PCanvas aCanvas) { super("StickyExample", false, aCanvas); } public void initialize() { - PPath sticky = PPath.createRectangle(0, 0, 50, 50); + final PPath sticky = PPath.createRectangle(0, 0, 50, 50); sticky.setPaint(Color.YELLOW); sticky.setStroke(null); PBoundsHandle.addBoundsHandlesTo(sticky); @@ -54,7 +59,7 @@ getCanvas().getCamera().addChild(sticky); } - public static void main(String[] args) { + public static void main(final String[] args) { new StickyExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyHandleLayerExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyHandleLayerExample.java index e36b469..c77b1b1 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyHandleLayerExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/StickyHandleLayerExample.java @@ -57,29 +57,34 @@ */ public class StickyHandleLayerExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public StickyHandleLayerExample() { this(null); } - public StickyHandleLayerExample(PCanvas aCanvas) { + public StickyHandleLayerExample(final PCanvas aCanvas) { super("StickyHandleLayerExample", false, aCanvas); } public void initialize() { - PCanvas c = getCanvas(); + final PCanvas c = getCanvas(); - PActivity updateHandles = new PActivity(-1, 0) { - protected void activityStep(long elapsedTime) { + final PActivity updateHandles = new PActivity(-1, 0) { + protected void activityStep(final long elapsedTime) { super.activityStep(elapsedTime); - PRoot root = getActivityScheduler().getRoot(); + final PRoot root = getActivityScheduler().getRoot(); if (root.getPaintInvalid() || root.getChildPaintInvalid()) { - Iterator i = getCanvas().getCamera().getChildrenIterator(); + final Iterator i = getCanvas().getCamera().getChildrenIterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); if (each instanceof PHandle) { - PHandle handle = (PHandle) each; + final PHandle handle = (PHandle) each; handle.relocateHandle(); } } @@ -87,7 +92,7 @@ } }; - PPath rect = PPath.createRectangle(0, 0, 100, 100); + final PPath rect = PPath.createRectangle(0, 0, 100, 100); rect.setPaint(Color.RED); c.getLayer().addChild(rect); @@ -99,7 +104,7 @@ c.getRoot().getActivityScheduler().addActivity(updateHandles, true); } - public static void main(String[] args) { + public static void main(final String[] args) { new StickyHandleLayerExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/StrokeExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/StrokeExample.java index 4afac41..5b40b8b 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/StrokeExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/StrokeExample.java @@ -32,12 +32,9 @@ import java.awt.Color; import edu.umd.cs.piccolo.PCanvas; - import edu.umd.cs.piccolo.nodes.PPath; import edu.umd.cs.piccolo.nodes.PText; - import edu.umd.cs.piccolox.PFrame; - import edu.umd.cs.piccolox.util.PFixedWidthStroke; /** @@ -46,6 +43,11 @@ public final class StrokeExample extends PFrame { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * Create a new stroke example. */ public StrokeExample() { @@ -54,40 +56,43 @@ /** * Create a new stroke example with the specified canvas. - * + * * @param canvas canvas */ public StrokeExample(final PCanvas canvas) { super("StrokeExample", false, canvas); } - /** {@inheritDoc} */ public void initialize() { - PText label = new PText("Stroke Example"); + final PText label = new PText("Stroke Example"); label.setFont(label.getFont().deriveFont(24.0f)); label.offset(20.0d, 20.0d); - PPath rect = PPath.createRectangle(50.0f, 50.0f, 300.0f, 300.0f); + final PPath rect = PPath.createRectangle(50.0f, 50.0f, 300.0f, 300.0f); rect.setStroke(new BasicStroke(4.0f)); rect.setStrokePaint(new Color(80, 80, 80)); - PText fixedWidthLabel = new PText("PFixedWidthStrokes"); + final PText fixedWidthLabel = new PText("PFixedWidthStrokes"); fixedWidthLabel.setTextPaint(new Color(80, 0, 0)); fixedWidthLabel.offset(100.0d, 80.0d); - PPath fixedWidthRect0 = PPath.createRectangle(100.0f, 100.0f, 200.0f, 50.0f); + final PPath fixedWidthRect0 = PPath.createRectangle(100.0f, 100.0f, 200.0f, 50.0f); fixedWidthRect0.setStroke(new PFixedWidthStroke(2.0f)); fixedWidthRect0.setStrokePaint(new Color(60, 60, 60)); - PPath fixedWidthRect1 = PPath.createRectangle(100.0f, 175.0f, 200.0f, 50.0f); + final PPath fixedWidthRect1 = PPath.createRectangle(100.0f, 175.0f, 200.0f, 50.0f); fixedWidthRect1.setStroke(new PFixedWidthStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10.0f)); - //fixedWidthRect1.setStroke(new PFixedWidthStroke(1.5f, PFixedWidthStroke.CAP_ROUND, PFixedWidthStroke.JOIN_MITER, 10.0f)); + // fixedWidthRect1.setStroke(new PFixedWidthStroke(1.5f, + // PFixedWidthStroke.CAP_ROUND, PFixedWidthStroke.JOIN_MITER, 10.0f)); fixedWidthRect1.setStrokePaint(new Color(40, 40, 40)); - PPath fixedWidthRect2 = PPath.createRectangle(100.0f, 250.0f, 200.0f, 50.0f); - fixedWidthRect2.setStroke(new PFixedWidthStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10.0f, new float[] { 2.0f, 3.0f, 4.0f }, 1.0f)); - //fixedWidthRect2.setStroke(new PFixedWidthStroke(1.0f, PFixedWidthStroke.CAP_ROUND, PFixedWidthStroke.JOIN_MITER, 10.0f, new float[] { 2.0f, 3.0f, 4.0f }, 1.0f)); + final PPath fixedWidthRect2 = PPath.createRectangle(100.0f, 250.0f, 200.0f, 50.0f); + fixedWidthRect2.setStroke(new PFixedWidthStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10.0f, + new float[] { 2.0f, 3.0f, 4.0f }, 1.0f)); + // fixedWidthRect2.setStroke(new PFixedWidthStroke(1.0f, + // PFixedWidthStroke.CAP_ROUND, PFixedWidthStroke.JOIN_MITER, 10.0f, new + // float[] { 2.0f, 3.0f, 4.0f }, 1.0f)); fixedWidthRect2.setStrokePaint(new Color(20, 20, 20)); getCanvas().getLayer().addChild(label); @@ -98,10 +103,9 @@ getCanvas().getLayer().addChild(fixedWidthRect2); } - /** * Main. - * + * * @param args command line arguments */ public static void main(final String[] args) { diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/TextExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/TextExample.java index 6654906..81dc675 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/TextExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/TextExample.java @@ -37,21 +37,26 @@ */ public class TextExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public TextExample() { this(null); } - public TextExample(PCanvas aCanvas) { + public TextExample(final PCanvas aCanvas) { super("TextExample", false, aCanvas); } public void initialize() { getCanvas().removeInputEventListener(getCanvas().getPanEventHandler()); - PStyledTextEventHandler textHandler = new PStyledTextEventHandler(getCanvas()); + final PStyledTextEventHandler textHandler = new PStyledTextEventHandler(getCanvas()); getCanvas().addInputEventListener(textHandler); } - public static void main(String[] args) { + public static void main(final String[] args) { new TextExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/TooltipExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/TooltipExample.java index 5a121d0..35f6d86 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/TooltipExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/TooltipExample.java @@ -46,17 +46,22 @@ */ public class TooltipExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public TooltipExample() { this(null); } - public TooltipExample(PCanvas aCanvas) { + public TooltipExample(final PCanvas aCanvas) { super("TooltipExample", false, aCanvas); } public void initialize() { - PNode n1 = PPath.createEllipse(0, 0, 100, 100); - PNode n2 = PPath.createRectangle(300, 200, 100, 100); + final PNode n1 = PPath.createEllipse(0, 0, 100, 100); + final PNode n2 = PPath.createRectangle(300, 200, 100, 100); n1.addAttribute("tooltip", "node 1"); n2.addAttribute("tooltip", "node 2"); @@ -70,18 +75,18 @@ camera.addChild(tooltipNode); camera.addInputEventListener(new PBasicInputEventHandler() { - public void mouseMoved(PInputEvent event) { + public void mouseMoved(final PInputEvent event) { updateToolTip(event); } - public void mouseDragged(PInputEvent event) { + public void mouseDragged(final PInputEvent event) { updateToolTip(event); } - public void updateToolTip(PInputEvent event) { - PNode n = event.getInputManager().getMouseOver().getPickedNode(); - String tooltipString = (String) n.getAttribute("tooltip"); - Point2D p = event.getCanvasPosition(); + public void updateToolTip(final PInputEvent event) { + final PNode n = event.getInputManager().getMouseOver().getPickedNode(); + final String tooltipString = (String) n.getAttribute("tooltip"); + final Point2D p = event.getCanvasPosition(); event.getPath().canvasToLocal(p, camera); @@ -91,7 +96,7 @@ }); } - public static void main(String[] argv) { + public static void main(final String[] argv) { new TooltipExample(); } } \ No newline at end of file diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/TwoCanvasExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/TwoCanvasExample.java index 557bc60..865ffe5 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/TwoCanvasExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/TwoCanvasExample.java @@ -41,20 +41,25 @@ public class TwoCanvasExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public TwoCanvasExample() { this(null); } - public TwoCanvasExample(PCanvas aCanvas) { + public TwoCanvasExample(final PCanvas aCanvas) { super("TwoCanvasExample", false, aCanvas); } public void initialize() { - PRoot root = getCanvas().getRoot(); - PLayer layer = getCanvas().getLayer(); + final PRoot root = getCanvas().getRoot(); + final PLayer layer = getCanvas().getLayer(); - PNode n = PPath.createRectangle(0, 0, 100, 80); - PNode sticky = PPath.createRectangle(0, 0, 50, 50); + final PNode n = PPath.createRectangle(0, 0, 100, 80); + final PNode sticky = PPath.createRectangle(0, 0, 50, 50); PBoundsHandle.addBoundsHandlesTo(n); sticky.setPaint(Color.YELLOW); PBoundsHandle.addBoundsHandlesTo(sticky); @@ -62,18 +67,18 @@ layer.addChild(n); getCanvas().getCamera().addChild(sticky); - PCamera otherCamera = new PCamera(); + final PCamera otherCamera = new PCamera(); otherCamera.addLayer(layer); root.addChild(otherCamera); - PCanvas other = new PCanvas(); + final PCanvas other = new PCanvas(); other.setCamera(otherCamera); - PFrame result = new PFrame("TwoCanvasExample", false, other); + final PFrame result = new PFrame("TwoCanvasExample", false, other); result.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); result.setLocation(500, 100); } - public static void main(String[] args) { + public static void main(final String[] args) { new TwoCanvasExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/WaitForActivitiesExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/WaitForActivitiesExample.java index 614ab31..93942a9 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/WaitForActivitiesExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/WaitForActivitiesExample.java @@ -41,30 +41,35 @@ */ public class WaitForActivitiesExample extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public WaitForActivitiesExample() { this(null); } - public WaitForActivitiesExample(PCanvas aCanvas) { + public WaitForActivitiesExample(final PCanvas aCanvas) { super("WaitForActivitiesExample", false, aCanvas); } public void initialize() { - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); - PNode a = PPath.createRectangle(0, 0, 100, 80); - PNode b = PPath.createRectangle(0, 0, 100, 80); + final PNode a = PPath.createRectangle(0, 0, 100, 80); + final PNode b = PPath.createRectangle(0, 0, 100, 80); layer.addChild(a); layer.addChild(b); - PActivity a1 = a.animateToPositionScaleRotation(200, 200, 1, 0, 5000); - PActivity a2 = b.animateToPositionScaleRotation(200, 200, 1, 0, 5000); + final PActivity a1 = a.animateToPositionScaleRotation(200, 200, 1, 0, 5000); + final PActivity a2 = b.animateToPositionScaleRotation(200, 200, 1, 0, 5000); a2.startAfter(a1); } - public static void main(String[] args) { + public static void main(final String[] args) { new WaitForActivitiesExample(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample1.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample1.java index 8e879f9..43e5d77 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample1.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample1.java @@ -61,18 +61,18 @@ */ public class PSwingExample1 { - public static void main(String[] args) { - PSwingCanvas pCanvas = new PSwingCanvas(); + public static void main(final String[] args) { + final PSwingCanvas pCanvas = new PSwingCanvas(); final PText pText = new PText("PText"); pCanvas.getLayer().addChild(pText); - JFrame frame = new JFrame("Test Piccolo"); + final JFrame frame = new JFrame("Test Piccolo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(pCanvas); frame.setSize(600, 800); frame.setVisible(true); - PText text2 = new PText("Text2"); + final PText text2 = new PText("Text2"); text2.setFont(new Font("Lucida Sans", Font.BOLD, 18)); pCanvas.getLayer().addChild(text2); text2.translate(100, 100); @@ -80,9 +80,9 @@ pCanvas.removeInputEventListener(pCanvas.getPanEventHandler()); - JButton jButton = new JButton("MyButton!"); + final JButton jButton = new JButton("MyButton!"); jButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(final ActionEvent e) { System.out.println("TestZSwing.actionPerformed!!!!!!!!!!!!!!*********************"); } }); @@ -90,67 +90,67 @@ pCanvas.getLayer().addChild(pSwing); pSwing.repaint(); - JSpinner jSpinner = new JSpinner(); + final JSpinner jSpinner = new JSpinner(); jSpinner.setPreferredSize(new Dimension(100, jSpinner.getPreferredSize().height)); - PSwing pSpinner = new PSwing(jSpinner); + final PSwing pSpinner = new PSwing(jSpinner); pCanvas.getLayer().addChild(pSpinner); pSpinner.translate(0, 150); - JCheckBox jcb = new JCheckBox("CheckBox", true); + final JCheckBox jcb = new JCheckBox("CheckBox", true); jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(final ActionEvent e) { System.out.println("TestZSwing.JCheckBox.actionPerformed"); } }); jcb.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent e) { + public void stateChanged(final ChangeEvent e) { System.out.println("TestPSwing.JChekbox.stateChanged@" + System.currentTimeMillis()); } }); - PSwing pCheckBox = new PSwing(jcb); + final PSwing pCheckBox = new PSwing(jcb); pCanvas.getLayer().addChild(pCheckBox); pCheckBox.translate(100, 0); // Growable JTextArea - JTextArea textArea = new JTextArea("This is a growable TextArea.\nTry it out!"); + final JTextArea textArea = new JTextArea("This is a growable TextArea.\nTry it out!"); textArea.setBorder(new LineBorder(Color.blue, 3)); PSwing swing = new PSwing(textArea); swing.translate(150, 150); pCanvas.getLayer().addChild(swing); // A Slider - JSlider slider = new JSlider(); - PSwing pSlider = new PSwing(slider); + final JSlider slider = new JSlider(); + final PSwing pSlider = new PSwing(slider); pSlider.translate(200, 200); pCanvas.getLayer().addChild(pSlider); // A Scrollable JTree - JTree tree = new JTree(); + final JTree tree = new JTree(); tree.setEditable(true); - JScrollPane p = new JScrollPane(tree); + final JScrollPane p = new JScrollPane(tree); p.setPreferredSize(new Dimension(150, 150)); - PSwing pTree = new PSwing(p); + final PSwing pTree = new PSwing(p); pCanvas.getLayer().addChild(pTree); pTree.translate(0, 250); // A JColorChooser - also demonstrates JTabbedPane - JColorChooser chooser = new JColorChooser(); - PSwing pChooser = new PSwing(chooser); + final JColorChooser chooser = new JColorChooser(); + final PSwing pChooser = new PSwing(chooser); pCanvas.getLayer().addChild(pChooser); pChooser.translate(100, 300); - JPanel myPanel = new JPanel(); + final JPanel myPanel = new JPanel(); myPanel.setBorder(BorderFactory.createTitledBorder("Titled Border")); myPanel.add(new JCheckBox("CheckBox")); - PSwing panelSwing = new PSwing(myPanel); + final PSwing panelSwing = new PSwing(myPanel); pCanvas.getLayer().addChild(panelSwing); panelSwing.translate(400, 50); // A Slider - JSlider slider2 = new JSlider(); - PSwing pSlider2 = new PSwing(slider2); + final JSlider slider2 = new JSlider(); + final PSwing pSlider2 = new PSwing(slider2); pSlider2.translate(200, 200); - PNode root = new PNode(); + final PNode root = new PNode(); root.addChild(pSlider2); root.scale(1.5); root.rotate(Math.PI / 4); @@ -158,13 +158,13 @@ pCanvas.getLayer().addChild(root); // A Combo Box - JPanel comboPanel = new JPanel(); - comboPanel.setBorder( BorderFactory.createTitledBorder( "Combo Box" ) ); - String[] listItems = { "Summer Teeth", "Mermaid Avenue", "Being There", "A.M." }; - PComboBox box = new PComboBox(listItems); + final JPanel comboPanel = new JPanel(); + comboPanel.setBorder(BorderFactory.createTitledBorder("Combo Box")); + final String[] listItems = { "Summer Teeth", "Mermaid Avenue", "Being There", "A.M." }; + final PComboBox box = new PComboBox(listItems); comboPanel.add(box); swing = new PSwing(comboPanel); - swing.translate( 200, 230 ); + swing.translate(200, 230); pCanvas.getLayer().addChild(swing); box.setEnvironment(swing, pCanvas);// has to be done manually at present diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample2.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample2.java index 8fb0c87..7a853f9 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample2.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingExample2.java @@ -80,6 +80,11 @@ */ public class PSwingExample2 extends JFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public PSwingExample2() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ClassLoader loader; @@ -102,7 +107,7 @@ PSwing swing2; // JButton - JButton button = new JButton("Button"); + final JButton button = new JButton("Button"); button.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); swing = new PSwing(button); leaf = new ZVisualLeaf(swing); @@ -112,7 +117,7 @@ canvas.getLayer().addChild(transform); // JButton - JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 10, 1)); + final JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 10, 1)); spinner.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); swing = new PSwing(spinner); leaf = new ZVisualLeaf(swing); @@ -131,7 +136,7 @@ canvas.getLayer().addChild(transform); // Growable JTextArea - JTextArea textArea = new JTextArea("This is a growable TextArea.\nTry it out!"); + final JTextArea textArea = new JTextArea("This is a growable TextArea.\nTry it out!"); textArea.setBorder(new LineBorder(Color.blue, 3)); swing = new PSwing(textArea); leaf = new ZVisualLeaf(swing); @@ -150,7 +155,7 @@ canvas.getLayer().addChild(transform); // A Slider - JSlider slider = new JSlider(); + final JSlider slider = new JSlider(); swing = new PSwing(slider); leaf = new ZVisualLeaf(swing); transform = new PNode(); @@ -159,9 +164,9 @@ canvas.getLayer().addChild(transform); // A Scrollable JTree - JTree tree = new JTree(); + final JTree tree = new JTree(); tree.setEditable(true); - JScrollPane p = new JScrollPane(tree); + final JScrollPane p = new JScrollPane(tree); p.setPreferredSize(new Dimension(150, 150)); swing = new PSwing(p); leaf = new ZVisualLeaf(swing); @@ -212,13 +217,13 @@ panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.RAISED), "A JList", TitledBorder.LEFT, TitledBorder.TOP)); panel.setPreferredSize(new Dimension(200, 200)); - Vector data = new Vector(); + final Vector data = new Vector(); data.addElement("Choice 1"); data.addElement("Choice 2"); data.addElement("Choice 3"); data.addElement("Choice 4"); data.addElement("Choice 5"); - JList list = new JList(data); + final JList list = new JList(data); list.setBackground(Color.lightGray); panel.add(list); swing = new PSwing(panel); @@ -236,7 +241,7 @@ transform.translate(-500, 0); transform.addChild(leaf); canvas.getLayer().addChild(transform); - + label = new JLabel("A JLabel", SwingConstants.CENTER); label.setIcon(new Icon() { @@ -248,10 +253,11 @@ return 20; } - public void paintIcon(Component c, Graphics g, int x, int y) { + public void paintIcon(final Component c, final Graphics g, final int x, final int y) { g.setColor(Color.BLUE); g.drawRect(0, 0, 20, 20); - }}); + } + }); swing = new PSwing(label); leaf = new ZVisualLeaf(swing); transform = new PNode(); @@ -271,8 +277,8 @@ // A panel MUST be created with double buffering off panel = new JPanel(false); panel.setLayout(new BorderLayout()); - JButton button1 = new JButton("Button 1"); - JButton button2 = new JButton("Button 2"); + final JButton button1 = new JButton("Button 1"); + final JButton button2 = new JButton("Button 2"); label = new JLabel("A Panel with Layout"); label.setHorizontalAlignment(SwingConstants.CENTER); label.setForeground(Color.white); @@ -291,11 +297,11 @@ canvas.getLayer().addChild(transform); // JTable Example - Vector columns = new Vector(); + final Vector columns = new Vector(); columns.addElement("Check Number"); columns.addElement("Description"); columns.addElement("Amount"); - Vector rows = new Vector(); + final Vector rows = new Vector(); Vector row = new Vector(); row.addElement("101"); row.addElement("Sandwich"); @@ -341,7 +347,7 @@ row.addElement("Swing Set"); row.addElement("$146.59"); rows.addElement(row); - JTable table = new JTable(rows, columns); + final JTable table = new JTable(rows, columns); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setRowHeight(30); TableColumn c = table.getColumn(table.getColumnName(0)); @@ -370,12 +376,12 @@ pane.setDoubleBuffered(false); pane.setPreferredSize(new Dimension(400, 400)); editorPane.addHyperlinkListener(new HyperlinkListener() { - public void hyperlinkUpdate(HyperlinkEvent e) { + public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { editorPane.setPage(e.getURL()); } - catch (IOException ioe) { + catch (final IOException ioe) { System.out.println("Couldn't Load Web Page"); } } @@ -389,40 +395,55 @@ canvas.getLayer().addChild(transform); } - catch (IOException ioe) { + catch (final IOException ioe) { System.out.println("Couldn't Load Web Page"); } // A JInternalFrame with a JSplitPane - a JOptionPane - and a // JToolBar - JInternalFrame iframe = new JInternalFrame("JInternalFrame"); + final JInternalFrame iframe = new JInternalFrame("JInternalFrame"); iframe.getRootPane().setDoubleBuffered(false); ((JComponent) iframe.getContentPane()).setDoubleBuffered(false); iframe.setPreferredSize(new Dimension(500, 500)); - JTabbedPane tabby = new JTabbedPane(); + final JTabbedPane tabby = new JTabbedPane(); tabby.setDoubleBuffered(false); iframe.getContentPane().setLayout(new BorderLayout()); - JOptionPane options = new JOptionPane("This is a JOptionPane!", JOptionPane.INFORMATION_MESSAGE, + final JOptionPane options = new JOptionPane("This is a JOptionPane!", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION); options.setDoubleBuffered(false); options.setMinimumSize(new Dimension(50, 50)); options.setPreferredSize(new Dimension(225, 225)); - JPanel tools = new JPanel(false); + final JPanel tools = new JPanel(false); tools.setMinimumSize(new Dimension(150, 150)); tools.setPreferredSize(new Dimension(225, 225)); - JToolBar bar = new JToolBar(); - Action letter = new AbstractAction("Big A!") { + final JToolBar bar = new JToolBar(); + final Action letter = new AbstractAction("Big A!") { - public void actionPerformed(ActionEvent e) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { } }; - Action hand = new AbstractAction("Hi!") { - public void actionPerformed(ActionEvent e) { + final Action hand = new AbstractAction("Hi!") { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { } }; - Action select = new AbstractAction("There!") { - public void actionPerformed(ActionEvent e) { + final Action select = new AbstractAction("There!") { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { } }; @@ -437,7 +458,7 @@ tools.add(bar, "North"); tools.add(label, "Center"); - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, options, tools); + final JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, options, tools); split.setDoubleBuffered(false); iframe.getContentPane().add(split); swing = new PSwing(iframe); @@ -460,7 +481,7 @@ // A JColorChooser - also demonstrates JTabbedPane // JColorChooser chooser = new JColorChooser(); - JCheckBox chooser = new JCheckBox("Check Box"); + final JCheckBox chooser = new JCheckBox("Check Box"); swing = new PSwing(chooser); leaf = new ZVisualLeaf(swing); transform = new PNode(); @@ -472,19 +493,24 @@ canvas.revalidate(); canvas.repaint(); - PSwing message = new PSwing(new JTextArea("Click-drag to zoom in and out.")); + final PSwing message = new PSwing(new JTextArea("Click-drag to zoom in and out.")); message.translate(0, -50); canvas.getLayer().addChild(message); canvas.getCamera().animateViewToCenterBounds(message.getFullBounds(), false, 1200); } - public static void main(String[] args) { + public static void main(final String[] args) { new PSwingExample2().setVisible(true); } public static class ZVisualLeaf extends PNode { - public ZVisualLeaf(PNode node) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public ZVisualLeaf(final PNode node) { addChild(node); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingMemoryLeakExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingMemoryLeakExample.java index eed74f8..15d289d 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingMemoryLeakExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/pswing/PSwingMemoryLeakExample.java @@ -31,7 +31,6 @@ import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -42,15 +41,13 @@ import javax.swing.Timer; import edu.umd.cs.piccolo.PCanvas; - import edu.umd.cs.piccolo.nodes.PText; - import edu.umd.cs.piccolox.pswing.PSwing; import edu.umd.cs.piccolox.pswing.PSwingCanvas; /** - * Attempt to replicate the PSwingRepaintManager-related memory leak - * reported in Issue 74. + * Attempt to replicate the PSwingRepaintManager-related memory leak reported in + * Issue 74. */ public final class PSwingMemoryLeakExample extends JFrame { @@ -78,22 +75,21 @@ /** Main panel, container for PSwingCanvases. */ private final JPanel mainPanel; - /** * Create a new PSwing memory leak example. */ public PSwingMemoryLeakExample() { super("PSwing memory leak example"); - PText label0 = new PText("Number of active PSwingCanvases:"); + final PText label0 = new PText("Number of active PSwingCanvases:"); active = new PText("0"); - PText label4 = new PText("Number of finalized PSwingCanvases:"); + final PText label4 = new PText("Number of finalized PSwingCanvases:"); finalized = new PText("0"); - PText label1 = new PText("Total memory:"); + final PText label1 = new PText("Total memory:"); totalMemory = new PText("0"); - PText label2 = new PText("Free memory:"); + final PText label2 = new PText("Free memory:"); freeMemory = new PText("0"); - PText label3 = new PText("Used memory:"); + final PText label3 = new PText("Used memory:"); usedMemory = new PText("0"); label0.offset(20.0d, 20.0d); @@ -128,15 +124,19 @@ getContentPane().add("North", canvas); getContentPane().add("Center", mainPanel); - final Timer add = new Timer(10, new ActionListener() - { + final Timer add = new Timer(10, new ActionListener() { int id = 0; /** {@inheritDoc} */ public void actionPerformed(final ActionEvent e) { - JLabel label = new JLabel("Label" + id); - PSwing pswing = new PSwing(label); - PSwingCanvas pswingCanvas = new PSwingCanvas() { + final JLabel label = new JLabel("Label" + id); + final PSwing pswing = new PSwing(label); + final PSwingCanvas pswingCanvas = new PSwingCanvas() { + /** + * + */ + private static final long serialVersionUID = 1L; + /** {@inheritDoc} */ public void finalize() { incrementFinalized(); @@ -156,14 +156,13 @@ add.setDelay(5); add.setRepeats(true); - final Timer remove = new Timer(20000, new ActionListener() - { + final Timer remove = new Timer(20000, new ActionListener() { /** {@inheritDoc} */ public void actionPerformed(final ActionEvent e) { if (add.isRunning()) { add.stop(); } - int i = mainPanel.getComponentCount() - 1; + final int i = mainPanel.getComponentCount() - 1; if (i > 0) { mainPanel.remove(mainPanel.getComponentCount() - 1); mainPanel.invalidate(); @@ -176,8 +175,7 @@ remove.setDelay(5); remove.setRepeats(true); - final Timer updateMemory = new Timer(500, new ActionListener() - { + final Timer updateMemory = new Timer(500, new ActionListener() { /** {@inheritDoc} */ public void actionPerformed(final ActionEvent e) { updateMemory(); @@ -228,28 +226,27 @@ /** * Update memory. */ - private void updateMemory() { + private void updateMemory() { new Thread(new Runnable() { - /** {@inheritDoc} */ - public void run() { - System.gc(); - System.runFinalization(); - } - }).run(); + /** {@inheritDoc} */ + public void run() { + System.gc(); + System.runFinalization(); + } + }).run(); - long total = Runtime.getRuntime().totalMemory(); + final long total = Runtime.getRuntime().totalMemory(); totalMemory.setText(String.valueOf(total)); - long free = Runtime.getRuntime().freeMemory(); + final long free = Runtime.getRuntime().freeMemory(); freeMemory.setText(String.valueOf(free)); - long used = (total - free); + final long used = total - free; usedMemory.setText(String.valueOf(used)); canvas.repaint(); } - /** * Main. - * + * * @param args command line arguments, ignored */ public static void main(final String[] args) { diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBasicExample.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBasicExample.java index 27b495d..d94d379 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBasicExample.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBasicExample.java @@ -50,20 +50,21 @@ super(); } - public static void main(String[] args) { - Display display = new Display(); - Shell shell = open(display); + public static void main(final String[] args) { + final Display display = new Display(); + final Shell shell = open(display); while (!shell.isDisposed()) { - if (!display.readAndDispatch()) + if (!display.readAndDispatch()) { display.sleep(); + } } display.dispose(); } - public static Shell open(Display display) { + public static Shell open(final Display display) { final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); - PSWTCanvas canvas = new PSWTCanvas(shell, 0); + final PSWTCanvas canvas = new PSWTCanvas(shell, 0); PSWTPath rect = PSWTPath.createRectangle(25, 25, 50, 50); rect.setPaint(Color.red); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBenchTest.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBenchTest.java index 9aee2f9..f59dcfb 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBenchTest.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTBenchTest.java @@ -28,10 +28,17 @@ */ package edu.umd.cs.piccolo.examples.swt; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.AffineTransform; +import java.awt.geom.GeneralPath; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; import java.util.Random; -import java.io.*; -import java.awt.*; -import java.awt.geom.*; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; @@ -116,78 +123,78 @@ static String testNames[] = { "line", "rect", "fill rect", "oval", "fill oval", "poly", "fill poly", "text", "image", "scaled image", "mask image", "alpha image", "argb image", }; - void testDrawLine(SWTGraphics2D g, Random r) { + void testDrawLine(final SWTGraphics2D g, final Random r) { g.drawLine(rand(r), rand(r), rand(r), rand(r)); } - void testDrawRect(SWTGraphics2D g, Random r) { + void testDrawRect(final SWTGraphics2D g, final Random r) { g.drawRect(rand(r), rand(r), rand(r), rand(r)); } - void testFillRect(SWTGraphics2D g, Random r) { + void testFillRect(final SWTGraphics2D g, final Random r) { g.fillRect(rand(r), rand(r), rand(r), rand(r)); } - void testDrawOval(SWTGraphics2D g, Random r) { + void testDrawOval(final SWTGraphics2D g, final Random r) { g.drawOval(rand(r), rand(r), rand(r), rand(r)); } - void testFillOval(SWTGraphics2D g, Random r) { + void testFillOval(final SWTGraphics2D g, final Random r) { g.fillOval(rand(r), rand(r), rand(r), rand(r)); } - void genPoly(Random r) { + void genPoly(final Random r) { for (int i = 0; i < pts.length / 2; i++) { pts[2 * i] = rand(r); pts[2 * i + 1] = rand(r); } } - void testDrawPoly(SWTGraphics2D g, Random r) { + void testDrawPoly(final SWTGraphics2D g, final Random r) { genPoly(r); g.drawPolyline(pts); } - void testFillPoly(SWTGraphics2D g, Random r) { + void testFillPoly(final SWTGraphics2D g, final Random r) { genPoly(r); g.fillPolygon(pts); } - void testDrawText(SWTGraphics2D g, Random r) { + void testDrawText(final SWTGraphics2D g, final Random r) { g.drawString("Abcdefghijklmnop", rand(r), rand(r)); } // Basic image - void testDrawImg1(SWTGraphics2D g, Random r) { + void testDrawImg1(final SWTGraphics2D g, final Random r) { g.drawImage(testImageOpaque, rand(r), rand(r)); } // Scaled image - void testDrawImg2(SWTGraphics2D g, Random r) { - Rectangle rect = testImageOpaque.getBounds(); + void testDrawImg2(final SWTGraphics2D g, final Random r) { + final Rectangle rect = testImageOpaque.getBounds(); g.drawImage(testImageOpaque, 0, 0, rect.width, rect.height, rand(r), rand(r), rand(r), rand(r)); } // Bitmask image (unscaled) - void testDrawImg3(SWTGraphics2D g, Random r) { + void testDrawImg3(final SWTGraphics2D g, final Random r) { g.drawImage(testImageBitmask, rand(r), rand(r)); } // Translucent image (unscaled) - void testDrawImg4(SWTGraphics2D g, Random r) { + void testDrawImg4(final SWTGraphics2D g, final Random r) { g.drawImage(testImageTranslucent, rand(r), rand(r)); } // Buffered image (unscaled) - void testDrawImg5(SWTGraphics2D g, Random r) { + void testDrawImg5(final SWTGraphics2D g, final Random r) { g.drawImage(testImageARGB, rand(r), rand(r)); } - Image loadImage(Display display, String name) { + Image loadImage(final Display display, final String name) { try { - InputStream stream = SWTBenchTest.class.getResourceAsStream(name); + final InputStream stream = SWTBenchTest.class.getResourceAsStream(name); if (stream != null) { - ImageData imageData = new ImageData(stream); + final ImageData imageData = new ImageData(stream); return new Image(display, imageData); // if (imageData != null) { // ImageData mask = imageData.getTransparencyMask(); @@ -196,12 +203,12 @@ } } - catch (Exception e) { + catch (final Exception e) { } return null; } - SWTBenchTest(Composite parent, int style) { + SWTBenchTest(final Composite parent, final int style) { super(parent, style); testImageOpaque = loadImage(getDisplay(), "opaque.jpg"); @@ -209,24 +216,24 @@ testImageTranslucent = loadImage(getDisplay(), "translucent.png"); testImageARGB = new Image(getDisplay(), 128, 128); - GC tmpGC = new GC(testImageARGB); + final GC tmpGC = new GC(testImageARGB); tmpGC.drawImage(testImageTranslucent, 0, 0); tmpGC.dispose(); addPaintListener(new PaintListener() { - public void paintControl(PaintEvent pe) { + public void paintControl(final PaintEvent pe) { runAll(new SWTGraphics2D(pe.gc, getDisplay())); } }); } - void setupTransform(Graphics2D g, Random r) { + void setupTransform(final Graphics2D g, final Random r) { transform.setToIdentity(); switch (abs(r.nextInt()) % 5) { default: // case 0: // UNIFORM SCALE - double s = r.nextDouble(); + final double s = r.nextDouble(); transform.scale(5 * s + 0.1, 5 * s + 0.1); break; // case 1: // NON-UNIFORM SCALE @@ -250,15 +257,15 @@ g.setTransform(transform); } - void setupClip(Graphics2D g, Random r) { + void setupClip(final Graphics2D g, final Random r) { // g.setClip(rand(r), rand(r), rand(r), rand(r)); } - void setupBlend(Graphics2D g, Random r) { + void setupBlend(final Graphics2D g, final Random r) { g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, r.nextFloat())); } - void setup(int ctx, Graphics2D g, Random r) { + void setup(final int ctx, final Graphics2D g, final Random r) { switch (ctx) { case CTX_NORMAL: break; @@ -277,7 +284,7 @@ } } - void test(int testNum, SWTGraphics2D g, Random r) { + void test(final int testNum, final SWTGraphics2D g, final Random r) { g.setColor(colors[abs(r.nextInt()) % colors.length]); g.setBackground(colors[abs(r.nextInt()) % colors.length]); @@ -325,28 +332,29 @@ } } - void runTest(SWTGraphics2D g, int ctx, int testNum) { - Random r1 = new Random(1); - Random r2 = new Random(1); + void runTest(final SWTGraphics2D g, final int ctx, final int testNum) { + final Random r1 = new Random(1); + final Random r2 = new Random(1); System.out.println("Test: " + testNames[testNum]); - long t1 = System.currentTimeMillis(); + final long t1 = System.currentTimeMillis(); int i = 0; while (true) { - if (i % 10 == 0) + if (i % 10 == 0) { setup(ctx, g, r1); + } test(testNum, g, r2); i++; - long t2 = System.currentTimeMillis(); + final long t2 = System.currentTimeMillis(); if (t2 - t1 >= 5000) { break; } } results[ctx][testNum] += i / 5; - System.out.println("Shapes per second: " + (results[ctx][testNum])); + System.out.println("Shapes per second: " + results[ctx][testNum]); } - void runAll(SWTGraphics2D g) { + void runAll(final SWTGraphics2D g) { System.out.println("BENCHMARKING: " + g); if (antialiased) { @@ -369,18 +377,20 @@ } String fileName = g.getClass().getName().replace('.', '_'); - if (offscreen) + if (offscreen) { fileName += "-offscreen"; - if (antialiased) + } + if (antialiased) { fileName += "-antialiased"; + } dumpResults(fileName + ".txt"); System.exit(0); } - void dumpResults(String fileName) { + void dumpResults(final String fileName) { try { - FileOutputStream fout = new FileOutputStream(fileName); - PrintWriter out = new PrintWriter(fout); + final FileOutputStream fout = new FileOutputStream(fileName); + final PrintWriter out = new PrintWriter(fout); out.print('\t'); for (int i = 0; i < NUM_TESTS; i++) { out.print(testNames[i]); @@ -398,42 +408,44 @@ out.close(); results = new int[NUM_CONTEXTS][NUM_TESTS]; } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); System.exit(1); } } - public Point computeSize(int wHint, int hHint) { + public Point computeSize(final int wHint, final int hHint) { return new Point(512, 512); } - public Point computeSize(int wHint, int hHint, boolean changed) { + public Point computeSize(final int wHint, final int hHint, final boolean changed) { return computeSize(wHint, hHint); } - final static int abs(int x) { - return (x < 0 ? -x : x); + final static int abs(final int x) { + return x < 0 ? -x : x; } - final static double rand(Random r) { + final static double rand(final Random r) { return abs(r.nextInt()) % 500; } - public static void main(String args[]) { + public static void main(final String args[]) { // Create frame - Display display = new Display(); - Shell shell = new Shell(display); + final Display display = new Display(); + final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); // Add bench test - SWTBenchTest m = new SWTBenchTest(shell, SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND); + final SWTBenchTest m = new SWTBenchTest(shell, SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND); m.setSize(512, 512); for (int i = 0; i < args.length; i++) { - if (args[i].intern() == "-offscreen") + if (args[i].intern() == "-offscreen") { m.offscreen = true; - else if (args[i].intern() == "-anti") + } + else if (args[i].intern() == "-anti") { m.antialiased = true; + } else { System.out.println("Usage: java BenchTest [-anti] [-offscreen]"); System.exit(1); @@ -444,8 +456,9 @@ shell.open(); while (!shell.isDisposed()) { - if (!display.readAndDispatch()) + if (!display.readAndDispatch()) { display.sleep(); + } } display.dispose(); } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTHelloWorld.java b/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTHelloWorld.java index a20dcf4..2caccbd 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTHelloWorld.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/examples/swt/SWTHelloWorld.java @@ -47,22 +47,23 @@ super(); } - public static void main(String[] args) { - Display display = new Display(); - Shell shell = open(display); + public static void main(final String[] args) { + final Display display = new Display(); + final Shell shell = open(display); while (!shell.isDisposed()) { - if (!display.readAndDispatch()) + if (!display.readAndDispatch()) { display.sleep(); + } } display.dispose(); } - public static Shell open(Display display) { + public static Shell open(final Display display) { final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); - PSWTCanvas canvas = new PSWTCanvas(shell, 0); + final PSWTCanvas canvas = new PSWTCanvas(shell, 0); - PSWTText text = new PSWTText("Hello World"); + final PSWTText text = new PSWTText("Hello World"); canvas.getLayer().addChild(text); shell.open(); diff --git a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/InterfaceFrame.java b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/InterfaceFrame.java index cedf5e5..96854b2 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/InterfaceFrame.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/InterfaceFrame.java @@ -31,14 +31,25 @@ import java.awt.Color; import java.awt.Graphics2D; -import edu.umd.cs.piccolo.*; -import edu.umd.cs.piccolo.event.*; -import edu.umd.cs.piccolo.nodes.*; -import edu.umd.cs.piccolo.util.*; -import edu.umd.cs.piccolox.*; +import edu.umd.cs.piccolo.PLayer; +import edu.umd.cs.piccolo.PNode; +import edu.umd.cs.piccolo.event.PBasicInputEventHandler; +import edu.umd.cs.piccolo.event.PDragEventHandler; +import edu.umd.cs.piccolo.event.PInputEvent; +import edu.umd.cs.piccolo.nodes.PImage; +import edu.umd.cs.piccolo.nodes.PPath; +import edu.umd.cs.piccolo.nodes.PText; +import edu.umd.cs.piccolo.util.PBounds; +import edu.umd.cs.piccolo.util.PPaintContext; +import edu.umd.cs.piccolox.PFrame; public class InterfaceFrame extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public void initialize() { // Remove the Default pan event handler and add a drag event handler // so that we can drag the nodes around individually. @@ -48,18 +59,18 @@ // Add Some Default Nodes // Create a node. - PNode aNode = new PNode(); + final PNode aNode = new PNode(); // A node will not be visible until its bounds and brush are set. aNode.setBounds(0, 0, 100, 80); aNode.setPaint(Color.RED); // A node needs to be a descendent of the root to be displayed. - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); layer.addChild(aNode); // A node can have child nodes added to it. - PNode anotherNode = new PNode(); + final PNode anotherNode = new PNode(); anotherNode.setBounds(0, 0, 100, 80); anotherNode.setPaint(Color.YELLOW); aNode.addChild(anotherNode); @@ -82,18 +93,18 @@ // Here we create a PImage node that displays a thumbnail image // of the root node. Then we add the new PImage to the main layer. - PImage image = new PImage(layer.toImage(300, 300, null)); + final PImage image = new PImage(layer.toImage(300, 300, null)); layer.addChild(image); // Create a New Node using Composition - PNode myCompositeFace = PPath.createRectangle(0, 0, 100, 80); + final PNode myCompositeFace = PPath.createRectangle(0, 0, 100, 80); // Create parts for the face. - PNode eye1 = PPath.createEllipse(0, 0, 20, 20); + final PNode eye1 = PPath.createEllipse(0, 0, 20, 20); eye1.setPaint(Color.YELLOW); - PNode eye2 = (PNode) eye1.clone(); - PNode mouth = PPath.createRectangle(0, 0, 40, 20); + final PNode eye2 = (PNode) eye1.clone(); + final PNode mouth = PPath.createRectangle(0, 0, 40, 20); mouth.setPaint(Color.BLACK); // Add the face parts. @@ -109,7 +120,7 @@ mouth.translate(0, 30); // Set the face bounds so that it neatly contains the face parts. - PBounds b = myCompositeFace.getUnionOfChildrenBounds(null); + final PBounds b = myCompositeFace.getUnionOfChildrenBounds(null); b.inset(-5, -5); myCompositeFace.setBounds(b); @@ -119,26 +130,30 @@ layer.addChild(myCompositeFace); // Create a New Node using Inheritance. - ToggleShape ts = new ToggleShape(); + final ToggleShape ts = new ToggleShape(); ts.setPaint(Color.ORANGE); layer.addChild(ts); } class ToggleShape extends PPath { + /** + * + */ + private static final long serialVersionUID = 1L; private boolean fIsPressed = false; public ToggleShape() { setPathToEllipse(0, 0, 100, 80); addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { super.mousePressed(event); fIsPressed = true; repaint(); } - public void mouseReleased(PInputEvent event) { + public void mouseReleased(final PInputEvent event) { super.mouseReleased(event); fIsPressed = false; repaint(); @@ -146,9 +161,9 @@ }); } - protected void paint(PPaintContext paintContext) { + protected void paint(final PPaintContext paintContext) { if (fIsPressed) { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); g2.setPaint(getPaint()); g2.fill(getBoundsReference()); } @@ -158,7 +173,7 @@ } } - public static void main(String[] args) { + public static void main(final String[] args) { new InterfaceFrame(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/PiccoloPresentation.java b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/PiccoloPresentation.java index fe2cf90..b917ca9 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/PiccoloPresentation.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/PiccoloPresentation.java @@ -42,6 +42,10 @@ public class PiccoloPresentation extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; protected PNode slideBar; protected PNode currentSlide; protected PBasicInputEventHandler eventHandler; @@ -56,17 +60,17 @@ loadSlides(); eventHandler = new PBasicInputEventHandler() { - public void keyReleased(PInputEvent event) { + public void keyReleased(final PInputEvent event) { if (event.getKeyCode() == KeyEvent.VK_SPACE) { - int newIndex = slides.indexOf(currentSlide) + 1; + final int newIndex = slides.indexOf(currentSlide) + 1; if (newIndex < slides.size()) { goToSlide((PNode) slides.get(newIndex)); } } } - public void mouseReleased(PInputEvent event) { - PNode picked = event.getPickedNode(); + public void mouseReleased(final PInputEvent event) { + final PNode picked = event.getPickedNode(); if (picked.getParent() == slideBar) { picked.moveToFront(); @@ -87,7 +91,7 @@ getCanvas().removeInputEventListener(getCanvas().getPanEventHandler()); } - public void goToSlide(PNode slide) { + public void goToSlide(final PNode slide) { if (currentSlide != null) { currentSlide.animateToTransform((AffineTransform) currentSlide.getAttribute("small"), 1000); } @@ -107,11 +111,11 @@ slideBar.setOffset(0, getCanvas().getHeight() - 100); getCanvas().getLayer().addChild(slideBar); - File[] slideFiles = new File("slides").listFiles(); + final File[] slideFiles = new File("slides").listFiles(); for (int i = 0; i < slideFiles.length; i++) { PNode slide = new PImage(slideFiles[i].getPath()); - if (slide.getHeight() != (getHeight() - 100)) { + if (slide.getHeight() != getHeight() - 100) { slide = new PImage(slide.toImage(getWidth(), getHeight() - 100, null)); } slide.offset((getWidth() - slide.getWidth()) / 2, -(getHeight() - 100)); @@ -129,7 +133,7 @@ goToSlide((PNode) slides.get(0)); } - public static void main(String[] argv) { + public static void main(final String[] argv) { new PiccoloPresentation(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/SpecialEffects.java b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/SpecialEffects.java index 97a68fa..9a5a470 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/SpecialEffects.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/SpecialEffects.java @@ -30,34 +30,40 @@ import java.awt.Color; -import edu.umd.cs.piccolo.*; -import edu.umd.cs.piccolo.activities.*; -import edu.umd.cs.piccolo.nodes.*; -import edu.umd.cs.piccolox.*; +import edu.umd.cs.piccolo.PLayer; +import edu.umd.cs.piccolo.PNode; +import edu.umd.cs.piccolo.activities.PActivity; +import edu.umd.cs.piccolo.nodes.PPath; +import edu.umd.cs.piccolox.PFrame; public class SpecialEffects extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public void initialize() { // Create the Target for our Activities. // Create a new node that we will apply different activities to, and // place that node at location 200, 200. final PNode aNode = PPath.createRectangle(0, 0, 100, 80); - PLayer layer = getCanvas().getLayer(); + final PLayer layer = getCanvas().getLayer(); layer.addChild(aNode); aNode.setOffset(200, 200); // Extend PActivity. // Store the current time in milliseconds for use below. - long currentTime = System.currentTimeMillis(); + final long currentTime = System.currentTimeMillis(); // Create a new custom "flash" activity. This activity will start // running in five seconds, and while it runs it will flash aNode's // paint between red and green every half second. - PActivity flash = new PActivity(-1, 500, currentTime + 5000) { + final PActivity flash = new PActivity(-1, 500, currentTime + 5000) { boolean fRed = true; - protected void activityStep(long elapsedTime) { + protected void activityStep(final long elapsedTime) { super.activityStep(elapsedTime); // Toggle the target node's brush color between red and green @@ -79,9 +85,9 @@ // Create three activities that animate the node's position. Since our // node already descends from the root node the animate methods will // automatically schedule these activities for us. - PActivity a1 = aNode.animateToPositionScaleRotation(0, 0, 0.5, 0, 5000); - PActivity a2 = aNode.animateToPositionScaleRotation(100, 0, 1.5, Math.toRadians(110), 5000); - PActivity a3 = aNode.animateToPositionScaleRotation(200, 100, 1, 0, 5000); + final PActivity a1 = aNode.animateToPositionScaleRotation(0, 0, 0.5, 0, 5000); + final PActivity a2 = aNode.animateToPositionScaleRotation(100, 0, 1.5, Math.toRadians(110), 5000); + final PActivity a3 = aNode.animateToPositionScaleRotation(200, 100, 1, 0, 5000); // The animate activities will start immediately (in the next call to // PRoot.processInputs) by default. Here we set their start times (in @@ -92,20 +98,20 @@ a3.startAfter(a2); a1.setDelegate(new PActivity.PActivityDelegate() { - public void activityStarted(PActivity activity) { + public void activityStarted(final PActivity activity) { System.out.println("a1 started"); } - public void activityStepped(PActivity activity) { + public void activityStepped(final PActivity activity) { } - public void activityFinished(PActivity activity) { + public void activityFinished(final PActivity activity) { System.out.println("a1 finished"); } }); } - public static void main(String[] args) { + public static void main(final String[] args) { new SpecialEffects(); } } diff --git a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/UserInteraction.java b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/UserInteraction.java index 51b543f..5c61aa4 100644 --- a/examples/src/main/java/edu/umd/cs/piccolo/tutorial/UserInteraction.java +++ b/examples/src/main/java/edu/umd/cs/piccolo/tutorial/UserInteraction.java @@ -34,14 +34,23 @@ import java.awt.event.KeyEvent; import java.awt.geom.Point2D; -import edu.umd.cs.piccolo.*; -import edu.umd.cs.piccolo.event.*; -import edu.umd.cs.piccolo.nodes.*; -import edu.umd.cs.piccolo.util.*; -import edu.umd.cs.piccolox.*; +import edu.umd.cs.piccolo.PCanvas; +import edu.umd.cs.piccolo.PNode; +import edu.umd.cs.piccolo.event.PBasicInputEventHandler; +import edu.umd.cs.piccolo.event.PDragSequenceEventHandler; +import edu.umd.cs.piccolo.event.PInputEvent; +import edu.umd.cs.piccolo.event.PInputEventFilter; +import edu.umd.cs.piccolo.nodes.PPath; +import edu.umd.cs.piccolo.util.PDimension; +import edu.umd.cs.piccolox.PFrame; public class UserInteraction extends PFrame { + /** + * + */ + private static final long serialVersionUID = 1L; + public UserInteraction() { super(); } @@ -54,38 +63,38 @@ getCanvas().setPanEventHandler(null); // Create a squiggle handler and register it with the Canvas. - PBasicInputEventHandler squiggleHandler = new SquiggleHandler(getCanvas()); + final PBasicInputEventHandler squiggleHandler = new SquiggleHandler(getCanvas()); getCanvas().addInputEventListener(squiggleHandler); // Create a Node Event Listener. // Create a green rectangle node. - PNode nodeGreen = PPath.createRectangle(0, 0, 100, 100); + final PNode nodeGreen = PPath.createRectangle(0, 0, 100, 100); nodeGreen.setPaint(Color.GREEN); getCanvas().getLayer().addChild(nodeGreen); // Attach event handler directly to the node. nodeGreen.addInputEventListener(new PBasicInputEventHandler() { - public void mousePressed(PInputEvent event) { + public void mousePressed(final PInputEvent event) { event.getPickedNode().setPaint(Color.ORANGE); event.getInputManager().setKeyboardFocus(event.getPath()); event.setHandled(true); } - public void mouseDragged(PInputEvent event) { - PNode aNode = event.getPickedNode(); - PDimension delta = event.getDeltaRelativeTo(aNode); + public void mouseDragged(final PInputEvent event) { + final PNode aNode = event.getPickedNode(); + final PDimension delta = event.getDeltaRelativeTo(aNode); aNode.translate(delta.width, delta.height); event.setHandled(true); } - public void mouseReleased(PInputEvent event) { + public void mouseReleased(final PInputEvent event) { event.getPickedNode().setPaint(Color.GREEN); event.setHandled(true); } - public void keyPressed(PInputEvent event) { - PNode node = event.getPickedNode(); + public void keyPressed(final PInputEvent event) { + final PNode node = event.getPickedNode(); switch (event.getKeyCode()) { case KeyEvent.VK_UP: node.translate(0, -10f); @@ -110,15 +119,15 @@ // The squiggle that is currently getting created. protected PPath squiggle; - public SquiggleHandler(PCanvas aCanvas) { + public SquiggleHandler(final PCanvas aCanvas) { canvas = aCanvas; setEventFilter(new PInputEventFilter(InputEvent.BUTTON1_MASK)); } - public void startDrag(PInputEvent e) { + public void startDrag(final PInputEvent e) { super.startDrag(e); - Point2D p = e.getPosition(); + final Point2D p = e.getPosition(); // Create a new squiggle and add it to the canvas. squiggle = new PPath(); @@ -130,28 +139,28 @@ e.getInputManager().setKeyboardFocus(null); } - public void drag(PInputEvent e) { + public void drag(final PInputEvent e) { super.drag(e); // Update the squiggle while dragging. updateSquiggle(e); } - public void endDrag(PInputEvent e) { + public void endDrag(final PInputEvent e) { super.endDrag(e); // Update the squiggle one last time. updateSquiggle(e); squiggle = null; } - public void updateSquiggle(PInputEvent aEvent) { + public void updateSquiggle(final PInputEvent aEvent) { // Add a new segment to the squiggle from the last mouse position // to the current mouse position. - Point2D p = aEvent.getPosition(); + final Point2D p = aEvent.getPosition(); squiggle.lineTo((float) p.getX(), (float) p.getY()); } } - public static void main(String[] args) { + public static void main(final String[] args) { new UserInteraction(); } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/PApplet.java b/extras/src/main/java/edu/umd/cs/piccolox/PApplet.java index a2f522c..a15a496 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/PApplet.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/PApplet.java @@ -42,6 +42,10 @@ */ public class PApplet extends JApplet { + /** + * + */ + private static final long serialVersionUID = 1L; private PCanvas canvas; public void init() { diff --git a/extras/src/main/java/edu/umd/cs/piccolox/PFrame.java b/extras/src/main/java/edu/umd/cs/piccolox/PFrame.java index 95dfc98..15b3ae9 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/PFrame.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/PFrame.java @@ -57,19 +57,23 @@ */ public class PFrame extends JFrame { + /** + * + */ + private static final long serialVersionUID = 1L; private PCanvas canvas; - private GraphicsDevice graphicsDevice; + private final GraphicsDevice graphicsDevice; private EventListener escapeFullScreenModeListener; public PFrame() { this("", false, null); } - public PFrame(String title, boolean fullScreenMode, PCanvas aCanvas) { + public PFrame(final String title, final boolean fullScreenMode, final PCanvas aCanvas) { this(title, GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(), fullScreenMode, aCanvas); } - public PFrame(String title, GraphicsDevice aDevice, final boolean fullScreenMode, final PCanvas aCanvas) { + public PFrame(final String title, final GraphicsDevice aDevice, final boolean fullScreenMode, final PCanvas aCanvas) { super(title, aDevice.getDefaultConfiguration()); graphicsDevice = aDevice; @@ -80,7 +84,7 @@ try { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } - catch (SecurityException e) { + catch (final SecurityException e) { } // expected from applets if (aCanvas == null) { @@ -125,7 +129,7 @@ return graphicsDevice.getFullScreenWindow() != null; } - public void setFullScreenMode(boolean fullScreenMode) { + public void setFullScreenMode(final boolean fullScreenMode) { if (fullScreenMode) { addEscapeFullScreenModeListener(); @@ -157,18 +161,18 @@ } } - protected void chooseBestDisplayMode(GraphicsDevice device) { - DisplayMode best = getBestDisplayMode(device); + protected void chooseBestDisplayMode(final GraphicsDevice device) { + final DisplayMode best = getBestDisplayMode(device); if (best != null) { device.setDisplayMode(best); } } - protected DisplayMode getBestDisplayMode(GraphicsDevice device) { - Iterator itr = getPreferredDisplayModes(device).iterator(); + protected DisplayMode getBestDisplayMode(final GraphicsDevice device) { + final Iterator itr = getPreferredDisplayModes(device).iterator(); while (itr.hasNext()) { - DisplayMode each = (DisplayMode) itr.next(); - DisplayMode[] modes = device.getDisplayModes(); + final DisplayMode each = (DisplayMode) itr.next(); + final DisplayMode[] modes = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { if (modes[i].getWidth() == each.getWidth() && modes[i].getHeight() == each.getHeight() && modes[i].getBitDepth() == each.getBitDepth()) { @@ -184,8 +188,8 @@ * By default return the current display mode. Subclasses may override this * method to return other modes in the collection. */ - protected Collection getPreferredDisplayModes(GraphicsDevice device) { - ArrayList result = new ArrayList(); + protected Collection getPreferredDisplayModes(final GraphicsDevice device) { + final ArrayList result = new ArrayList(); result.add(device.getDisplayMode()); /* @@ -205,7 +209,7 @@ public void addEscapeFullScreenModeListener() { removeEscapeFullScreenModeListener(); escapeFullScreenModeListener = new KeyAdapter() { - public void keyPressed(KeyEvent aEvent) { + public void keyPressed(final KeyEvent aEvent) { if (aEvent.getKeyCode() == KeyEvent.VK_ESCAPE) { setFullScreenMode(false); } @@ -249,7 +253,7 @@ public void initialize() { } - public static void main(String[] argv) { + public static void main(final String[] argv) { new PFrame(); } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/POffscreenCanvas.java b/extras/src/main/java/edu/umd/cs/piccolox/POffscreenCanvas.java index 56d864c..17d5e89 100755 --- a/extras/src/main/java/edu/umd/cs/piccolox/POffscreenCanvas.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/POffscreenCanvas.java @@ -33,7 +33,6 @@ import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolo.PComponent; - import edu.umd.cs.piccolo.util.PBounds; import edu.umd.cs.piccolo.util.PPaintContext; import edu.umd.cs.piccolo.util.PUtil; @@ -51,14 +50,16 @@ /** Render quality. */ private int renderQuality = DEFAULT_RENDER_QUALITY; - - /** Default render quality, PPaintContext.HIGH_QUALITY_RENDERING. */ - static final int DEFAULT_RENDER_QUALITY = PPaintContext.HIGH_QUALITY_RENDERING; + /** + * Default render quality, PPaintContext.HIGH_QUALITY_RENDERING + * . + */ + static final int DEFAULT_RENDER_QUALITY = PPaintContext.HIGH_QUALITY_RENDERING; /** * Create a new offscreen canvas the specified width and height. - * + * * @param width width of this offscreen canvas, must be at least zero * @param height height of this offscreen canvas, must be at least zero */ @@ -73,24 +74,24 @@ setCamera(PUtil.createBasicScenegraph()); } - /** * Render this offscreen canvas to the specified graphics. - * - * @param graphics graphics to render this offscreen canvas to, must not be null + * + * @param graphics graphics to render this offscreen canvas to, must not be + * null */ public void render(final Graphics2D graphics) { if (graphics == null) { throw new IllegalArgumentException("graphics must not be null"); } - PPaintContext paintContext = new PPaintContext(graphics); + final PPaintContext paintContext = new PPaintContext(graphics); paintContext.setRenderQuality(renderQuality); camera.fullPaint(paintContext); } /** * Set the camera for this offscreen canvas to camera. - * + * * @param camera camera for this offscreen canvas */ public void setCamera(final PCamera camera) { @@ -106,7 +107,7 @@ /** * Return the camera for this offscreen canvas. - * + * * @return the camera for this offscreen canvas */ public PCamera getCamera() { @@ -114,16 +115,19 @@ } /** - * Set the render quality hint for this offscreen canvas to renderQuality. - * - * @param renderQuality render quality hint, must be one of PPaintContext.HIGH_QUALITY_RENDERING - * or PPaintContext.LOW_QUALITY_RENDERING + * Set the render quality hint for this offscreen canvas to + * renderQuality. + * + * @param renderQuality render quality hint, must be one of + * PPaintContext.HIGH_QUALITY_RENDERING or + * PPaintContext.LOW_QUALITY_RENDERING */ public void setRenderQuality(final int renderQuality) { - if ((renderQuality == PPaintContext.HIGH_QUALITY_RENDERING) - || (renderQuality == PPaintContext.LOW_QUALITY_RENDERING)) { + if (renderQuality == PPaintContext.HIGH_QUALITY_RENDERING + || renderQuality == PPaintContext.LOW_QUALITY_RENDERING) { this.renderQuality = renderQuality; - } else { + } + else { throw new IllegalArgumentException("renderQuality must be one of PPaintContext.HIGH_QUALITY_RENDERING" + " or PPaintContext.LOW_QUALITY_RENDERING, was " + renderQuality); } @@ -131,34 +135,34 @@ /** * Return the render quality hint for this offscreen canvas. - * + * * @return the render quality hint for this offscreen canvas */ public int getRenderQuality() { return renderQuality; } - /**{@inheritDoc} */ + /** {@inheritDoc} */ public final void paintImmediately() { // empty } - /**{@inheritDoc} */ + /** {@inheritDoc} */ public final void popCursor() { // empty } - /**{@inheritDoc} */ + /** {@inheritDoc} */ public final void pushCursor(final Cursor cursor) { // empty } - /**{@inheritDoc} */ + /** {@inheritDoc} */ public final void repaint(final PBounds repaintBounds) { // empty } - /**{@inheritDoc} */ + /** {@inheritDoc} */ public final void setInteracting(final boolean interacting) { // empty } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/activities/PPathActivity.java b/extras/src/main/java/edu/umd/cs/piccolox/activities/PPathActivity.java index 1304e20..c402f33 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/activities/PPathActivity.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/activities/PPathActivity.java @@ -53,11 +53,12 @@ protected float[] knots; - public PPathActivity(long duration, long stepRate, float[] knots) { + public PPathActivity(final long duration, final long stepRate, final float[] knots) { this(duration, stepRate, 0, PInterpolatingActivity.SOURCE_TO_DESTINATION, knots); } - public PPathActivity(long duration, long stepRate, int loopCount, int mode, float[] knots) { + public PPathActivity(final long duration, final long stepRate, final int loopCount, final int mode, + final float[] knots) { super(duration, stepRate, loopCount, mode); setKnots(knots); } @@ -66,7 +67,7 @@ return knots.length; } - public void setKnots(float[] knots) { + public void setKnots(final float[] knots) { this.knots = knots; } @@ -74,15 +75,15 @@ return knots; } - public void setKnot(int index, float knot) { + public void setKnot(final int index, final float knot) { knots[index] = knot; } - public float getKnot(int index) { + public float getKnot(final int index) { return knots[index]; } - public void setRelativeTargetValue(float zeroToOne) { + public void setRelativeTargetValue(final float zeroToOne) { int currentKnotIndex = 0; while (zeroToOne > knots[currentKnotIndex]) { @@ -92,13 +93,15 @@ int startKnot = currentKnotIndex - 1; int endKnot = currentKnotIndex; - if (startKnot < 0) + if (startKnot < 0) { startKnot = 0; - if (endKnot > getKnotsLength() - 1) + } + if (endKnot > getKnotsLength() - 1) { endKnot = getKnotsLength() - 1; + } - float currentRange = knots[endKnot] - knots[startKnot]; - float currentPointOnRange = zeroToOne - knots[startKnot]; + final float currentRange = knots[endKnot] - knots[startKnot]; + final float currentPointOnRange = zeroToOne - knots[startKnot]; float normalizedPointOnRange = currentPointOnRange; if (currentRange != 0) { diff --git a/extras/src/main/java/edu/umd/cs/piccolox/activities/PPositionPathActivity.java b/extras/src/main/java/edu/umd/cs/piccolox/activities/PPositionPathActivity.java index edd0202..748a0fb 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/activities/PPositionPathActivity.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/activities/PPositionPathActivity.java @@ -50,16 +50,17 @@ public void setPosition(double x, double y); } - public PPositionPathActivity(long duration, long stepRate, Target aTarget) { + public PPositionPathActivity(final long duration, final long stepRate, final Target aTarget) { this(duration, stepRate, aTarget, null, null); } - public PPositionPathActivity(long duration, long stepRate, Target aTarget, float[] knots, Point2D[] positions) { + public PPositionPathActivity(final long duration, final long stepRate, final Target aTarget, final float[] knots, + final Point2D[] positions) { this(duration, stepRate, 1, PInterpolatingActivity.SOURCE_TO_DESTINATION, aTarget, knots, positions); } - public PPositionPathActivity(long duration, long stepRate, int loopCount, int mode, Target aTarget, float[] knots, - Point2D[] positions) { + public PPositionPathActivity(final long duration, final long stepRate, final int loopCount, final int mode, + final Target aTarget, final float[] knots, final Point2D[] positions) { super(duration, stepRate, loopCount, mode, knots); target = aTarget; this.positions = positions; @@ -73,28 +74,28 @@ return positions; } - public Point2D getPosition(int index) { + public Point2D getPosition(final int index) { return positions[index]; } - public void setPositions(Point2D[] positions) { + public void setPositions(final Point2D[] positions) { this.positions = positions; } - public void setPosition(int index, Point2D position) { + public void setPosition(final int index, final Point2D position) { positions[index] = position; } - public void setPositions(GeneralPath path) { - PathIterator pi = path.getPathIterator(null, 1); - ArrayList points = new ArrayList(); - float point[] = new float[6]; + public void setPositions(final GeneralPath path) { + final PathIterator pi = path.getPathIterator(null, 1); + final ArrayList points = new ArrayList(); + final float point[] = new float[6]; float distanceSum = 0; float lastMoveToX = 0; float lastMoveToY = 0; while (!pi.isDone()) { - int type = pi.currentSegment(point); + final int type = pi.currentSegment(point); switch (type) { case PathIterator.SEG_MOVETO: @@ -117,23 +118,23 @@ } if (points.size() > 1) { - Point2D last = (Point2D) points.get(points.size() - 2); - Point2D current = (Point2D) points.get(points.size() - 1); + final Point2D last = (Point2D) points.get(points.size() - 2); + final Point2D current = (Point2D) points.get(points.size() - 1); distanceSum += last.distance(current); } pi.next(); } - int size = points.size(); - Point2D newPositions[] = new Point2D[size]; - float newKnots[] = new float[size]; + final int size = points.size(); + final Point2D newPositions[] = new Point2D[size]; + final float newKnots[] = new float[size]; for (int i = 0; i < size; i++) { newPositions[i] = (Point2D) points.get(i); if (i > 0) { - float dist = (float) newPositions[i - 1].distance(newPositions[i]); - newKnots[i] = newKnots[i - 1] + (dist / distanceSum); + final float dist = (float) newPositions[i - 1].distance(newPositions[i]); + newKnots[i] = newKnots[i - 1] + dist / distanceSum; } } @@ -141,10 +142,10 @@ setKnots(newKnots); } - public void setRelativeTargetValue(float zeroToOne, int startKnot, int endKnot) { - Point2D start = getPosition(startKnot); - Point2D end = getPosition(endKnot); - target.setPosition(start.getX() + (zeroToOne * (end.getX() - start.getX())), start.getY() - + (zeroToOne * (end.getY() - start.getY()))); + public void setRelativeTargetValue(final float zeroToOne, final int startKnot, final int endKnot) { + final Point2D start = getPosition(startKnot); + final Point2D end = getPosition(endKnot); + target.setPosition(start.getX() + zeroToOne * (end.getX() - start.getX()), start.getY() + zeroToOne + * (end.getY() - start.getY())); } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/event/PNavigationEventHandler.java b/extras/src/main/java/edu/umd/cs/piccolox/event/PNavigationEventHandler.java index 352b822..f3d412f 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/event/PNavigationEventHandler.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/event/PNavigationEventHandler.java @@ -81,8 +81,8 @@ // Focus Change Events. // **************************************************************** - public void keyPressed(PInputEvent e) { - PNode oldLocation = focusNode; + public void keyPressed(final PInputEvent e) { + final PNode oldLocation = focusNode; switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: @@ -119,7 +119,7 @@ } } - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { moveFocusToMouseOver(aEvent); if (focusNode != null) { @@ -136,60 +136,61 @@ // move the focus to the parent of the current focus. // **************************************************************** - public void moveFocusDown(PInputEvent e) { + public void moveFocusDown(final PInputEvent e) { moveFocusInDirection(SOUTH); } - public void moveFocusIn(PInputEvent e) { + public void moveFocusIn(final PInputEvent e) { moveFocusInDirection(IN); } - public void moveFocusLeft(PInputEvent e) { + public void moveFocusLeft(final PInputEvent e) { moveFocusInDirection(WEST); } - public void moveFocusOut(PInputEvent e) { + public void moveFocusOut(final PInputEvent e) { moveFocusInDirection(OUT); } - public void moveFocusRight(PInputEvent e) { + public void moveFocusRight(final PInputEvent e) { moveFocusInDirection(EAST); } - public void moveFocusUp(PInputEvent e) { + public void moveFocusUp(final PInputEvent e) { moveFocusInDirection(NORTH); } - private void moveFocusInDirection(int direction) { - PNode n = getNeighborInDirection(direction); + private void moveFocusInDirection(final int direction) { + final PNode n = getNeighborInDirection(direction); if (n != null) { focusNode = n; } } - public void moveFocusToMouseOver(PInputEvent e) { - PNode focus = e.getPickedNode(); + public void moveFocusToMouseOver(final PInputEvent e) { + final PNode focus = e.getPickedNode(); if (!(focus instanceof PCamera)) { focusNode = focus; } } - public PNode getNeighborInDirection(int aDirection) { - if (focusNode == null) + public PNode getNeighborInDirection(final int aDirection) { + if (focusNode == null) { return null; + } NODE_TO_GLOBAL_NODE_CENTER_MAPPING.clear(); - Point2D highlightCenter = focusNode.getGlobalFullBounds().getCenter2D(); + final Point2D highlightCenter = focusNode.getGlobalFullBounds().getCenter2D(); NODE_TO_GLOBAL_NODE_CENTER_MAPPING.put(focusNode, highlightCenter); - List l = getNeighbors(); + final List l = getNeighbors(); sortNodesByDistanceFromPoint(l, highlightCenter); - Iterator i = l.iterator(); + final Iterator i = l.iterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); if (nodeIsNeighborInDirection(each, aDirection)) { return each; } @@ -199,16 +200,17 @@ } public List getNeighbors() { - ArrayList result = new ArrayList(); - if (focusNode == null || focusNode.getParent() == null) + final ArrayList result = new ArrayList(); + if (focusNode == null || focusNode.getParent() == null) { return result; + } - PNode focusParent = focusNode.getParent(); + final PNode focusParent = focusNode.getParent(); - Iterator i = focusParent.getChildrenIterator(); + final Iterator i = focusParent.getChildrenIterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); if (each != focusNode && each.getPickable()) { result.add(each); } @@ -219,7 +221,7 @@ return result; } - public boolean nodeIsNeighborInDirection(PNode aNode, int aDirection) { + public boolean nodeIsNeighborInDirection(final PNode aNode, final int aDirection) { switch (aDirection) { case IN: { return aNode.isDescendentOf(focusNode); @@ -236,44 +238,44 @@ } } - Point2D highlightCenter = (Point2D) NODE_TO_GLOBAL_NODE_CENTER_MAPPING.get(focusNode); - Point2D nodeCenter = (Point2D) NODE_TO_GLOBAL_NODE_CENTER_MAPPING.get(aNode); + final Point2D highlightCenter = (Point2D) NODE_TO_GLOBAL_NODE_CENTER_MAPPING.get(focusNode); + final Point2D nodeCenter = (Point2D) NODE_TO_GLOBAL_NODE_CENTER_MAPPING.get(aNode); - double ytest1 = nodeCenter.getX() - highlightCenter.getX() + highlightCenter.getY(); - double ytest2 = -nodeCenter.getX() + highlightCenter.getX() + highlightCenter.getY(); + final double ytest1 = nodeCenter.getX() - highlightCenter.getX() + highlightCenter.getY(); + final double ytest2 = -nodeCenter.getX() + highlightCenter.getX() + highlightCenter.getY(); switch (aDirection) { case NORTH: { - return (nodeCenter.getY() < highlightCenter.getY()) - && (nodeCenter.getY() < ytest1 && nodeCenter.getY() < ytest2); + return nodeCenter.getY() < highlightCenter.getY() && nodeCenter.getY() < ytest1 + && nodeCenter.getY() < ytest2; } case EAST: { - return (nodeCenter.getX() > highlightCenter.getX()) - && (nodeCenter.getY() < ytest1 && nodeCenter.getY() > ytest2); + return nodeCenter.getX() > highlightCenter.getX() && nodeCenter.getY() < ytest1 + && nodeCenter.getY() > ytest2; } case SOUTH: { - return (nodeCenter.getY() > highlightCenter.getY()) - && (nodeCenter.getY() > ytest1 && nodeCenter.getY() > ytest2); + return nodeCenter.getY() > highlightCenter.getY() && nodeCenter.getY() > ytest1 + && nodeCenter.getY() > ytest2; } case WEST: { - return (nodeCenter.getX() < highlightCenter.getX()) - && (nodeCenter.getY() > ytest1 && nodeCenter.getY() < ytest2); - } + return nodeCenter.getX() < highlightCenter.getX() && nodeCenter.getY() > ytest1 + && nodeCenter.getY() < ytest2; + } } return false; } - public void sortNodesByDistanceFromPoint(List aNodesList, final Point2D aPoint) { + public void sortNodesByDistanceFromPoint(final List aNodesList, final Point2D aPoint) { Collections.sort(aNodesList, new Comparator() { - public int compare(Object o1, Object o2) { + public int compare(final Object o1, final Object o2) { return compare((PNode) o1, (PNode) o2); } - private int compare(PNode each1, PNode each2) { - Point2D center1 = each1.getGlobalFullBounds().getCenter2D(); - Point2D center2 = each2.getGlobalFullBounds().getCenter2D(); + private int compare(final PNode each1, final PNode each2) { + final Point2D center1 = each1.getGlobalFullBounds().getCenter2D(); + final Point2D center2 = each2.getGlobalFullBounds().getCenter2D(); NODE_TO_GLOBAL_NODE_CENTER_MAPPING.put(each1, center1); NODE_TO_GLOBAL_NODE_CENTER_MAPPING.put(each2, center2); @@ -288,7 +290,8 @@ // focus remains visible on the screen at 100 percent scale. // **************************************************************** - protected PActivity animateCameraViewTransformTo(final PCamera aCamera, AffineTransform aTransform, int duration) { + protected PActivity animateCameraViewTransformTo(final PCamera aCamera, final AffineTransform aTransform, + final int duration) { boolean wasOldAnimation = false; // first stop any old animations. @@ -302,7 +305,7 @@ return null; } - AffineTransform source = aCamera.getViewTransformReference(); + final AffineTransform source = aCamera.getViewTransformReference(); if (source.equals(aTransform)) { return null; @@ -313,16 +316,16 @@ return navigationActivity; } - public PActivity directCameraViewToFocus(PCamera aCamera, PNode aFocusNode, int duration) { + public PActivity directCameraViewToFocus(final PCamera aCamera, final PNode aFocusNode, final int duration) { focusNode = aFocusNode; - AffineTransform originalViewTransform = aCamera.getViewTransform(); + final AffineTransform originalViewTransform = aCamera.getViewTransform(); // Scale the canvas to include - PDimension d = new PDimension(1, 0); + final PDimension d = new PDimension(1, 0); focusNode.globalToLocal(d); - double scaleFactor = d.getWidth() / aCamera.getViewScale(); - Point2D scalePoint = focusNode.getGlobalFullBounds().getCenter2D(); + final double scaleFactor = d.getWidth() / aCamera.getViewScale(); + final Point2D scalePoint = focusNode.getGlobalFullBounds().getCenter2D(); if (scaleFactor != 1) { aCamera.scaleViewAboutPoint(scaleFactor, scalePoint.getX(), scalePoint.getY()); } @@ -336,7 +339,7 @@ // magnification. // fillViewWhiteSpace(aCamera); - AffineTransform resultingTransform = aCamera.getViewTransform(); + final AffineTransform resultingTransform = aCamera.getViewTransform(); aCamera.setViewTransform(originalViewTransform); // Animate the canvas so that it ends up with the given @@ -344,8 +347,8 @@ return animateCameraViewTransformTo(aCamera, resultingTransform, duration); } - protected void fillViewWhiteSpace(PCamera aCamera) { - PBounds rootBounds = aCamera.getRoot().getFullBoundsReference(); + protected void fillViewWhiteSpace(final PCamera aCamera) { + final PBounds rootBounds = aCamera.getRoot().getFullBoundsReference(); PBounds viewBounds = aCamera.getViewBounds(); if (rootBounds.contains(aCamera.getViewBounds())) { diff --git a/extras/src/main/java/edu/umd/cs/piccolox/event/PNotification.java b/extras/src/main/java/edu/umd/cs/piccolox/event/PNotification.java index 456a5b1..93853d5 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/event/PNotification.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/event/PNotification.java @@ -59,7 +59,7 @@ protected Object source; protected Map properties; - public PNotification(String name, Object source, Map properties) { + public PNotification(final String name, final Object source, final Map properties) { this.name = name; this.source = source; this.properties = properties; @@ -84,7 +84,7 @@ /** * Return a property associated with the notfication. */ - public Object getProperty(Object key) { + public Object getProperty(final Object key) { if (properties != null) { return properties.get(key); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/event/PNotificationCenter.java b/extras/src/main/java/edu/umd/cs/piccolox/event/PNotificationCenter.java index 237411d..a71a6b6 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/event/PNotificationCenter.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/event/PNotificationCenter.java @@ -98,8 +98,8 @@ * @return whether or not the listener has been added * @throws SecurityException */ - public boolean addListener(Object listener, String callbackMethodName, String notificationName, Object object) - throws SecurityException { + public boolean addListener(final Object listener, final String callbackMethodName, final String notificationName, + Object object) throws SecurityException { processKeyQueue(); Object name = notificationName; @@ -108,11 +108,11 @@ try { method = listener.getClass().getMethod(callbackMethodName, new Class[] { PNotification.class }); } - catch (NoSuchMethodException e) { + catch (final NoSuchMethodException e) { return false; } - int modifiers = method.getModifiers(); + final int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { return false; @@ -126,8 +126,8 @@ object = NULL_MARKER; } - Object key = new NotificationKey(name, object); - Object notificationTarget = new NotificationTarget(listener, method); + final Object key = new NotificationKey(name, object); + final Object notificationTarget = new NotificationTarget(listener, method); List list = (List) listenersMap.get(key); if (list == null) { @@ -150,10 +150,10 @@ * Removes the listener so that it no longer recives notfications from this * notfication center. */ - public void removeListener(Object listener) { + public void removeListener(final Object listener) { processKeyQueue(); - Iterator i = new LinkedList(listenersMap.keySet()).iterator(); + final Iterator i = new LinkedList(listenersMap.keySet()).iterator(); while (i.hasNext()) { removeListener(listener, i.next()); } @@ -167,11 +167,11 @@ * the object is null then the listener will be removed from all * notifications matching notficationName. */ - public void removeListener(Object listener, String notificationName, Object object) { + public void removeListener(final Object listener, final String notificationName, final Object object) { processKeyQueue(); - List keys = matchingKeys(notificationName, object); - Iterator it = keys.iterator(); + final List keys = matchingKeys(notificationName, object); + final Iterator it = keys.iterator(); while (it.hasNext()) { removeListener(listener, it.next()); } @@ -185,7 +185,7 @@ * Post a new notfication with notificationName and object. The object is * typically the object posting the notification. The object may be null. */ - public void postNotification(String notificationName, Object object) { + public void postNotification(final String notificationName, final Object object) { postNotification(notificationName, object, null); } @@ -194,7 +194,7 @@ * the object, and posts it to this notification center. The object is * typically the object posting the notification. It may be nil. */ - public void postNotification(String notificationName, Object object, Map userInfo) { + public void postNotification(final String notificationName, final Object object, final Map userInfo) { postNotification(new PNotification(notificationName, object, userInfo)); } @@ -203,12 +203,12 @@ * will instead use one of this classes convenience postNotifcations * methods. */ - public void postNotification(PNotification aNotification) { - List mergedListeners = new LinkedList(); + public void postNotification(final PNotification aNotification) { + final List mergedListeners = new LinkedList(); List listenersList; - Object name = aNotification.getName(); - Object object = aNotification.getObject(); + final Object name = aNotification.getName(); + final Object object = aNotification.getObject(); if (name != null) { if (object == null) {// object is null @@ -239,7 +239,7 @@ } } - Object key = new NotificationKey(NULL_MARKER, NULL_MARKER); + final Object key = new NotificationKey(NULL_MARKER, NULL_MARKER); listenersList = (List) listenersMap.get(key); if (listenersList != null) { mergedListeners.addAll(listenersList); @@ -248,9 +248,9 @@ dispatchNotifications(aNotification, mergedListeners); } - private void dispatchNotifications(PNotification aNotification, List listeners) { + private void dispatchNotifications(final PNotification aNotification, final List listeners) { NotificationTarget listener; - Iterator it = listeners.iterator(); + final Iterator it = listeners.iterator(); while (it.hasNext()) { listener = (NotificationTarget) it.next(); @@ -261,10 +261,10 @@ try { listener.getMethod().invoke(listener.get(), new Object[] { aNotification }); } - catch (IllegalAccessException e) { + catch (final IllegalAccessException e) { // it's impossible add listeners that are not public } - catch (InvocationTargetException e) { + catch (final InvocationTargetException e) { // Since this is how Swing handles Exceptions that get // thrown on listeners, it's probably ok to do it here. e.printStackTrace(); @@ -277,13 +277,13 @@ // Implementation classes and methods // **************************************************************** - protected List matchingKeys(String name, Object object) { - List result = new LinkedList(); + protected List matchingKeys(final String name, final Object object) { + final List result = new LinkedList(); - NotificationKey searchKey = new NotificationKey(name, object); - Iterator it = listenersMap.keySet().iterator(); + final NotificationKey searchKey = new NotificationKey(name, object); + final Iterator it = listenersMap.keySet().iterator(); while (it.hasNext()) { - NotificationKey key = (NotificationKey) it.next(); + final NotificationKey key = (NotificationKey) it.next(); if (searchKey.equals(key)) { result.add(key); } @@ -292,20 +292,21 @@ return result; } - protected void removeListener(Object listener, Object key) { + protected void removeListener(final Object listener, final Object key) { if (listener == null) { listenersMap.remove(key); return; } - List list = (List) listenersMap.get(key); - if (list == null) + final List list = (List) listenersMap.get(key); + if (list == null) { return; + } - Iterator it = list.iterator(); + final Iterator it = list.iterator(); while (it.hasNext()) { - Object observer = ((NotificationTarget) it.next()).get(); - if ((observer == null) || (listener == observer)) { + final Object observer = ((NotificationTarget) it.next()).get(); + if (observer == null || listener == observer) { it.remove(); } } @@ -324,16 +325,16 @@ protected static class NotificationKey extends WeakReference { - private Object name; - private int hashCode; + private final Object name; + private final int hashCode; - public NotificationKey(Object aName, Object anObject) { + public NotificationKey(final Object aName, final Object anObject) { super(anObject); name = aName; hashCode = aName.hashCode() + anObject.hashCode(); } - public NotificationKey(Object aName, Object anObject, ReferenceQueue aQueue) { + public NotificationKey(final Object aName, final Object anObject, final ReferenceQueue aQueue) { super(anObject, aQueue); name = aName; hashCode = aName.hashCode() + anObject.hashCode(); @@ -347,19 +348,22 @@ return hashCode; } - public boolean equals(Object anObject) { - if (this == anObject) + public boolean equals(final Object anObject) { + if (this == anObject) { return true; + } - if (!(anObject instanceof NotificationKey)) + if (!(anObject instanceof NotificationKey)) { return false; + } - NotificationKey key = (NotificationKey) anObject; + final NotificationKey key = (NotificationKey) anObject; - if (name != key.name && (name == null || !name.equals(key.name))) + if (name != key.name && (name == null || !name.equals(key.name))) { return false; + } - Object object = get(); + final Object object = get(); return object != null && object == key.get(); } @@ -374,7 +378,7 @@ protected int hashCode; protected Method method; - public NotificationTarget(Object object, Method method) { + public NotificationTarget(final Object object, final Method method) { super(object); hashCode = object.hashCode(); this.method = method; @@ -388,20 +392,23 @@ return hashCode; } - public boolean equals(Object object) { - if (this == object) + public boolean equals(final Object object) { + if (this == object) { return true; + } - if (!(object instanceof NotificationTarget)) + if (!(object instanceof NotificationTarget)) { return false; + } - NotificationTarget target = (NotificationTarget) object; - if (method != target.method && (method == null || !method.equals(target.method))) + final NotificationTarget target = (NotificationTarget) object; + if (method != target.method && (method == null || !method.equals(target.method))) { return false; + } - Object o = get(); + final Object o = get(); - return (o != null) && (o == target.get()); + return o != null && o == target.get(); } public String toString() { diff --git a/extras/src/main/java/edu/umd/cs/piccolox/event/PSelectionEventHandler.java b/extras/src/main/java/edu/umd/cs/piccolox/event/PSelectionEventHandler.java index dea550b..0f720dd 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/event/PSelectionEventHandler.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/event/PSelectionEventHandler.java @@ -100,10 +100,10 @@ * @param selectableParent The node whose children will be selected by this * event handler. */ - public PSelectionEventHandler(PNode marqueeParent, PNode selectableParent) { + public PSelectionEventHandler(final PNode marqueeParent, final PNode selectableParent) { this.marqueeParent = marqueeParent; - this.selectableParents = new ArrayList(); - this.selectableParents.add(selectableParent); + selectableParents = new ArrayList(); + selectableParents.add(selectableParent); init(); } @@ -115,14 +115,14 @@ * @param selectableParents A list of nodes whose children will be selected * by this event handler. */ - public PSelectionEventHandler(PNode marqueeParent, List selectableParents) { + public PSelectionEventHandler(final PNode marqueeParent, final List selectableParents) { this.marqueeParent = marqueeParent; this.selectableParents = selectableParents; init(); } protected void init() { - float[] dash = { DASH_WIDTH, DASH_WIDTH }; + final float[] dash = { DASH_WIDTH, DASH_WIDTH }; strokes = new Stroke[NUM_STROKES]; for (int i = 0; i < NUM_STROKES; i++) { strokes[i] = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, i); @@ -138,11 +138,11 @@ // Public static methods for manipulating the selection // ///////////////////////////////////////////////////// - public void select(Collection items) { + public void select(final Collection items) { boolean changes = false; - Iterator itemIt = items.iterator(); + final Iterator itemIt = items.iterator(); while (itemIt.hasNext()) { - PNode node = (PNode) itemIt.next(); + final PNode node = (PNode) itemIt.next(); changes |= internalSelect(node); } if (changes) { @@ -150,11 +150,11 @@ } } - public void select(Map items) { + public void select(final Map items) { select(items.keySet()); } - private boolean internalSelect(PNode node) { + private boolean internalSelect(final PNode node) { if (isSelected(node)) { return false; } @@ -168,21 +168,21 @@ PNotificationCenter.defaultCenter().postNotification(SELECTION_CHANGED_NOTIFICATION, this); } - public void select(PNode node) { + public void select(final PNode node) { if (internalSelect(node)) { postSelectionChanged(); } } - public void decorateSelectedNode(PNode node) { + public void decorateSelectedNode(final PNode node) { PBoundsHandle.addBoundsHandlesTo(node); } - public void unselect(Collection items) { + public void unselect(final Collection items) { boolean changes = false; - Iterator itemIt = items.iterator(); + final Iterator itemIt = items.iterator(); while (itemIt.hasNext()) { - PNode node = (PNode) itemIt.next(); + final PNode node = (PNode) itemIt.next(); changes |= internalUnselect(node); } if (changes) { @@ -190,7 +190,7 @@ } } - private boolean internalUnselect(PNode node) { + private boolean internalUnselect(final PNode node) { if (!isSelected(node)) { return false; } @@ -200,25 +200,25 @@ return true; } - public void unselect(PNode node) { + public void unselect(final PNode node) { if (internalUnselect(node)) { postSelectionChanged(); } } - public void undecorateSelectedNode(PNode node) { + public void undecorateSelectedNode(final PNode node) { PBoundsHandle.removeBoundsHandlesFrom(node); } public void unselectAll() { // Because unselect() removes from selection, we need to // take a copy of it first so it isn't changed while we're iterating - ArrayList sel = new ArrayList(selection.keySet()); + final ArrayList sel = new ArrayList(selection.keySet()); unselect(sel); } - public boolean isSelected(PNode node) { - if ((node != null) && (selection.containsKey(node))) { + public boolean isSelected(final PNode node) { + if (node != null && selection.containsKey(node)) { return true; } else { @@ -230,7 +230,7 @@ * Returns a copy of the currently selected nodes. */ public Collection getSelection() { - ArrayList sel = new ArrayList(selection.keySet()); + final ArrayList sel = new ArrayList(selection.keySet()); return sel; } @@ -246,19 +246,19 @@ * Determine if the specified node is selectable (i.e., if it is a child of * the one the list of selectable parents. */ - protected boolean isSelectable(PNode node) { + protected boolean isSelectable(final PNode node) { boolean selectable = false; - Iterator parentsIt = selectableParents.iterator(); + final Iterator parentsIt = selectableParents.iterator(); while (parentsIt.hasNext()) { - PNode parent = (PNode) parentsIt.next(); + final PNode parent = (PNode) parentsIt.next(); if (parent.getChildrenReference().contains(node)) { selectable = true; break; } else if (parent instanceof PCamera) { for (int i = 0; i < ((PCamera) parent).getLayerCount(); i++) { - PLayer layer = ((PCamera) parent).getLayer(i); + final PLayer layer = ((PCamera) parent).getLayer(i); if (layer.getChildrenReference().contains(node)) { selectable = true; break; @@ -274,20 +274,20 @@ // Methods for modifying the set of selectable parents // //////////////////////////////////////////////////// - public void addSelectableParent(PNode node) { + public void addSelectableParent(final PNode node) { selectableParents.add(node); } - public void removeSelectableParent(PNode node) { + public void removeSelectableParent(final PNode node) { selectableParents.remove(node); } - public void setSelectableParent(PNode node) { + public void setSelectableParent(final PNode node) { selectableParents.clear(); selectableParents.add(node); } - public void setSelectableParents(Collection c) { + public void setSelectableParents(final Collection c) { selectableParents.clear(); selectableParents.addAll(c); } @@ -300,7 +300,7 @@ // The overridden methods from PDragSequenceEventHandler // ////////////////////////////////////////////////////// - protected void startDrag(PInputEvent e) { + protected void startDrag(final PInputEvent e) { super.startDrag(e); initializeSelection(e); @@ -325,7 +325,7 @@ } } - protected void drag(PInputEvent e) { + protected void drag(final PInputEvent e) { super.drag(e); if (isMarqueeSelection(e)) { @@ -343,7 +343,7 @@ } } - protected void endDrag(PInputEvent e) { + protected void endDrag(final PInputEvent e) { super.endDrag(e); if (isMarqueeSelection(e)) { @@ -358,15 +358,15 @@ // Additional methods // ////////////////////////// - public boolean isOptionSelection(PInputEvent pie) { + public boolean isOptionSelection(final PInputEvent pie) { return pie.isShiftDown(); } - protected boolean isMarqueeSelection(PInputEvent pie) { - return (pressNode == null); + protected boolean isMarqueeSelection(final PInputEvent pie) { + return pressNode == null; } - protected void initializeSelection(PInputEvent pie) { + protected void initializeSelection(final PInputEvent pie) { canvasPressPt = pie.getCanvasPosition(); presspt = pie.getPosition(); pressNode = pie.getPath().getPickedNode(); @@ -375,7 +375,7 @@ } } - protected void initializeMarquee(PInputEvent e) { + protected void initializeMarquee(final PInputEvent e) { marquee = PPath.createRectangle((float) presspt.getX(), (float) presspt.getY(), 0, 0); marquee.setPaint(marqueePaint); marquee.setTransparency(marqueePaintTransparency); @@ -386,14 +386,14 @@ marqueeMap.clear(); } - protected void startOptionMarqueeSelection(PInputEvent e) { + protected void startOptionMarqueeSelection(final PInputEvent e) { } - protected void startMarqueeSelection(PInputEvent e) { + protected void startMarqueeSelection(final PInputEvent e) { unselectAll(); } - protected void startStandardSelection(PInputEvent pie) { + protected void startStandardSelection(final PInputEvent pie) { // Option indicator not down - clear selection, and start fresh if (!isSelected(pressNode)) { unselectAll(); @@ -404,7 +404,7 @@ } } - protected void startStandardOptionSelection(PInputEvent pie) { + protected void startStandardOptionSelection(final PInputEvent pie) { // Option indicator is down, toggle selection if (isSelectable(pressNode)) { if (isSelected(pressNode)) { @@ -416,8 +416,8 @@ } } - protected void updateMarquee(PInputEvent pie) { - PBounds b = new PBounds(); + protected void updateMarquee(final PInputEvent pie) { + final PBounds b = new PBounds(); if (marqueeParent instanceof PCamera) { b.add(canvasPressPt); @@ -435,10 +435,10 @@ b.add(pie.getPosition()); allItems.clear(); - PNodeFilter filter = createNodeFilter(b); - Iterator parentsIt = selectableParents.iterator(); + final PNodeFilter filter = createNodeFilter(b); + final Iterator parentsIt = selectableParents.iterator(); while (parentsIt.hasNext()) { - PNode parent = (PNode) parentsIt.next(); + final PNode parent = (PNode) parentsIt.next(); Collection items; if (parent instanceof PCamera) { @@ -451,20 +451,20 @@ items = parent.getAllNodes(filter, null); } - Iterator itemsIt = items.iterator(); + final Iterator itemsIt = items.iterator(); while (itemsIt.hasNext()) { allItems.put(itemsIt.next(), Boolean.TRUE); } } } - protected void computeMarqueeSelection(PInputEvent pie) { + protected void computeMarqueeSelection(final PInputEvent pie) { unselectList.clear(); // Make just the items in the list selected // Do this efficiently by first unselecting things not in the list Iterator selectionEn = selection.keySet().iterator(); while (selectionEn.hasNext()) { - PNode node = (PNode) selectionEn.next(); + final PNode node = (PNode) selectionEn.next(); if (!allItems.containsKey(node)) { unselectList.add(node); } @@ -474,7 +474,7 @@ // Then select the rest selectionEn = allItems.keySet().iterator(); while (selectionEn.hasNext()) { - PNode node = (PNode) selectionEn.next(); + final PNode node = (PNode) selectionEn.next(); if (!selection.containsKey(node) && !marqueeMap.containsKey(node) && isSelectable(node)) { marqueeMap.put(node, Boolean.TRUE); } @@ -486,11 +486,11 @@ select(allItems); } - protected void computeOptionMarqueeSelection(PInputEvent pie) { + protected void computeOptionMarqueeSelection(final PInputEvent pie) { unselectList.clear(); Iterator selectionEn = selection.keySet().iterator(); while (selectionEn.hasNext()) { - PNode node = (PNode) selectionEn.next(); + final PNode node = (PNode) selectionEn.next(); if (!allItems.containsKey(node) && marqueeMap.containsKey(node)) { marqueeMap.remove(node); unselectList.add(node); @@ -501,7 +501,7 @@ // Then select the rest selectionEn = allItems.keySet().iterator(); while (selectionEn.hasNext()) { - PNode node = (PNode) selectionEn.next(); + final PNode node = (PNode) selectionEn.next(); if (!selection.containsKey(node) && !marqueeMap.containsKey(node) && isSelectable(node)) { marqueeMap.put(node, Boolean.TRUE); } @@ -513,7 +513,7 @@ select(allItems); } - protected PNodeFilter createNodeFilter(PBounds bounds) { + protected PNodeFilter createNodeFilter(final PBounds bounds) { return new BoundsFilter(bounds); } @@ -524,15 +524,15 @@ return new PBounds(); } - protected void dragStandardSelection(PInputEvent e) { + protected void dragStandardSelection(final PInputEvent e) { // There was a press node, so drag selection - PDimension d = e.getCanvasDelta(); + final PDimension d = e.getCanvasDelta(); e.getTopCamera().localToView(d); - PDimension gDist = new PDimension(); - Iterator selectionEn = getSelection().iterator(); + final PDimension gDist = new PDimension(); + final Iterator selectionEn = getSelection().iterator(); while (selectionEn.hasNext()) { - PNode node = (PNode) selectionEn.next(); + final PNode node = (PNode) selectionEn.next(); gDist.setSize(d); node.getParent().globalToLocal(gDist); @@ -540,7 +540,7 @@ } } - protected void endMarqueeSelection(PInputEvent e) { + protected void endMarqueeSelection(final PInputEvent e) { // Remove marquee allItems.clear(); marqueeMap.clear(); @@ -548,7 +548,7 @@ marquee = null; } - protected void endStandardSelection(PInputEvent e) { + protected void endStandardSelection(final PInputEvent e) { pressNode = null; } @@ -556,9 +556,9 @@ * This gets called continuously during the drag, and is used to animate the * marquee */ - protected void dragActivityStep(PInputEvent aEvent) { + protected void dragActivityStep(final PInputEvent aEvent) { if (marquee != null) { - float origStrokeNum = strokeNum; + final float origStrokeNum = strokeNum; strokeNum = (strokeNum + 0.5f) % NUM_STROKES; // Increment by // partial steps to // slow down animation @@ -571,13 +571,13 @@ /** * Delete selection when delete key is pressed (if enabled) */ - public void keyPressed(PInputEvent e) { + public void keyPressed(final PInputEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_DELETE: if (deleteKeyActive) { - Iterator selectionEn = selection.keySet().iterator(); + final Iterator selectionEn = selection.keySet().iterator(); while (selectionEn.hasNext()) { - PNode node = (PNode) selectionEn.next(); + final PNode node = (PNode) selectionEn.next(); node.removeFromParent(); } selection.clear(); @@ -596,7 +596,7 @@ /** * Specifies if the DELETE key should delete the selection */ - public void setDeleteKeyActive(boolean deleteKeyActive) { + public void setDeleteKeyActive(final boolean deleteKeyActive) { this.deleteKeyActive = deleteKeyActive; } @@ -608,27 +608,28 @@ PBounds localBounds = new PBounds(); PBounds bounds; - protected BoundsFilter(PBounds bounds) { + protected BoundsFilter(final PBounds bounds) { this.bounds = bounds; } - public boolean accept(PNode node) { + public boolean accept(final PNode node) { localBounds.setRect(bounds); node.globalToLocal(localBounds); - boolean boundsIntersects = node.intersects(localBounds); - boolean isMarquee = (node == marquee); - return (node.getPickable() && boundsIntersects && !isMarquee && !selectableParents.contains(node) && !isCameraLayer(node)); + final boolean boundsIntersects = node.intersects(localBounds); + final boolean isMarquee = node == marquee; + return node.getPickable() && boundsIntersects && !isMarquee && !selectableParents.contains(node) + && !isCameraLayer(node); } - public boolean acceptChildrenOf(PNode node) { + public boolean acceptChildrenOf(final PNode node) { return selectableParents.contains(node) || isCameraLayer(node); } - public boolean isCameraLayer(PNode node) { + public boolean isCameraLayer(final PNode node) { if (node instanceof PLayer) { - for (Iterator i = selectableParents.iterator(); i.hasNext();) { - PNode parent = (PNode) i.next(); + for (final Iterator i = selectableParents.iterator(); i.hasNext();) { + final PNode parent = (PNode) i.next(); if (parent instanceof PCamera && ((PCamera) parent).indexOfLayer((PLayer) node) != -1) { return true; } @@ -652,8 +653,8 @@ * * @param paint the paint color */ - public void setMarqueePaint(Paint paint) { - this.marqueePaint = paint; + public void setMarqueePaint(final Paint paint) { + marqueePaint = paint; } /** @@ -670,7 +671,7 @@ * * @param marqueePaintTransparency The marquee paint transparency to set. */ - public void setMarqueePaintTransparency(float marqueePaintTransparency) { + public void setMarqueePaintTransparency(final float marqueePaintTransparency) { this.marqueePaintTransparency = marqueePaintTransparency; } } \ No newline at end of file diff --git a/extras/src/main/java/edu/umd/cs/piccolox/event/PStyledTextEventHandler.java b/extras/src/main/java/edu/umd/cs/piccolox/event/PStyledTextEventHandler.java index 14845ae..a194d70 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/event/PStyledTextEventHandler.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/event/PStyledTextEventHandler.java @@ -76,12 +76,12 @@ /** * Basic constructor for PStyledTextEventHandler */ - public PStyledTextEventHandler(PCanvas canvas) { + public PStyledTextEventHandler(final PCanvas canvas) { super(); - PInputEventFilter filter = new PInputEventFilter(); + final PInputEventFilter filter = new PInputEventFilter(); filter.setOrMask(InputEvent.BUTTON1_MASK | InputEvent.BUTTON3_MASK); - this.setEventFilter(filter); + setEventFilter(filter); this.canvas = canvas; initEditor(createDefaultEditor()); } @@ -90,14 +90,14 @@ * Constructor for PStyledTextEventHandler that allows an editor to be * specified */ - public PStyledTextEventHandler(PCanvas canvas, JTextComponent editor) { + public PStyledTextEventHandler(final PCanvas canvas, final JTextComponent editor) { super(); this.canvas = canvas; initEditor(editor); } - protected void initEditor(JTextComponent newEditor) { + protected void initEditor(final JTextComponent newEditor) { editor = newEditor; canvas.setLayout(null); @@ -108,15 +108,20 @@ } protected JTextComponent createDefaultEditor() { - JTextPane tComp = new JTextPane() { + final JTextPane tComp = new JTextPane() { + + /** + * + */ + private static final long serialVersionUID = 1L; /** * Set some rendering hints - if we don't then the rendering can be * inconsistent. Also, Swing doesn't work correctly with fractional * metrics. */ - public void paint(Graphics g) { - Graphics2D g2 = (Graphics2D) g; + public void paint(final Graphics g) { + final Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); @@ -132,44 +137,44 @@ protected DocumentListener createDocumentListener() { return new DocumentListener() { - public void removeUpdate(DocumentEvent e) { + public void removeUpdate(final DocumentEvent e) { reshapeEditorLater(); } - public void insertUpdate(DocumentEvent e) { + public void insertUpdate(final DocumentEvent e) { reshapeEditorLater(); } - public void changedUpdate(DocumentEvent e) { + public void changedUpdate(final DocumentEvent e) { reshapeEditorLater(); } }; } public PStyledText createText() { - PStyledText newText = new PStyledText(); + final PStyledText newText = new PStyledText(); - Document doc = editor.getUI().getEditorKit(editor).createDefaultDocument(); + final Document doc = editor.getUI().getEditorKit(editor).createDefaultDocument(); if (doc instanceof StyledDocument && missingFontFamilyOrSize(doc)) { - Font eFont = editor.getFont(); - SimpleAttributeSet sas = new SimpleAttributeSet(); + final Font eFont = editor.getFont(); + final SimpleAttributeSet sas = new SimpleAttributeSet(); sas.addAttribute(StyleConstants.FontFamily, eFont.getFamily()); sas.addAttribute(StyleConstants.FontSize, new Integer(eFont.getSize())); - ((StyledDocument) doc).setParagraphAttributes(0, doc.getLength(), sas, false); + ((StyledDocument) doc).setParagraphAttributes(0, doc.getLength(), sas, false); } newText.setDocument(doc); return newText; } - private boolean missingFontFamilyOrSize(Document doc) { + private boolean missingFontFamilyOrSize(final Document doc) { return !doc.getDefaultRootElement().getAttributes().isDefined(StyleConstants.FontFamily) || !doc.getDefaultRootElement().getAttributes().isDefined(StyleConstants.FontSize); } - public void mousePressed(PInputEvent inputEvent) { - PNode pickedNode = inputEvent.getPickedNode(); + public void mousePressed(final PInputEvent inputEvent) { + final PNode pickedNode = inputEvent.getPickedNode(); stopEditing(inputEvent); @@ -181,8 +186,8 @@ startEditing(inputEvent, (PStyledText) pickedNode); } else if (pickedNode instanceof PCamera) { - PStyledText newText = createText(); - Insets pInsets = newText.getInsets(); + final PStyledText newText = createText(); + final Insets pInsets = newText.getInsets(); canvas.getLayer().addChild(newText); newText.translate(inputEvent.getPosition().getX() - pInsets.left, inputEvent.getPosition().getY() - pInsets.top); @@ -190,10 +195,10 @@ } } - public void startEditing(PInputEvent event, PStyledText text) { + public void startEditing(final PInputEvent event, final PStyledText text) { // Get the node's top right hand corner - Insets pInsets = text.getInsets(); - Point2D nodePt = new Point2D.Double(text.getX() + pInsets.left, text.getY() + pInsets.top); + final Insets pInsets = text.getInsets(); + final Point2D nodePt = new Point2D.Double(text.getX() + pInsets.left, text.getY() + pInsets.top); text.localToGlobal(nodePt); event.getTopCamera().viewToLocal(nodePt); @@ -201,7 +206,7 @@ editor.setDocument(text.getDocument()); editor.setVisible(true); - Insets bInsets = editor.getBorder().getBorderInsets(editor); + final Insets bInsets = editor.getBorder().getBorderInsets(editor); editor.setLocation((int) nodePt.getX() - bInsets.left, (int) nodePt.getY() - bInsets.top); reshapeEditorLater(); @@ -213,7 +218,7 @@ editedText = text; } - public void stopEditing(PInputEvent event) { + public void stopEditing(final PInputEvent event) { if (editedText == null) { return; } @@ -243,7 +248,8 @@ public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() { - MouseEvent me = new MouseEvent(editor, MouseEvent.MOUSE_PRESSED, e.getWhen(), e.getModifiers() + final MouseEvent me = new MouseEvent(editor, MouseEvent.MOUSE_PRESSED, e.getWhen(), e + .getModifiers() | InputEvent.BUTTON1_MASK, (int) (e.getCanvasPosition().getX() - editor.getX()), (int) (e.getCanvasPosition().getY() - editor.getY()), 1, false); editor.dispatchEvent(me); @@ -259,19 +265,18 @@ // stage process Dimension prefSize = editor.getPreferredSize(); - Insets pInsets = editedText.getInsets(); - Insets jInsets = editor.getInsets(); + final Insets pInsets = editedText.getInsets(); + final Insets jInsets = editor.getInsets(); - int width = (editedText.getConstrainWidthToTextWidth()) ? (int) prefSize.getWidth() : (int) (editedText + final int width = editedText.getConstrainWidthToTextWidth() ? (int) prefSize.getWidth() : (int) (editedText .getWidth() - pInsets.left - pInsets.right + jInsets.left + jInsets.right + 3.0); prefSize.setSize(width, prefSize.getHeight()); editor.setSize(prefSize); prefSize = editor.getPreferredSize(); - int height = (editedText.getConstrainHeightToTextHeight()) ? (int) prefSize.getHeight() : (int) (editedText - .getHeight() - - pInsets.top - pInsets.bottom + jInsets.top + jInsets.bottom + 3.0); + final int height = editedText.getConstrainHeightToTextHeight() ? (int) prefSize.getHeight() + : (int) (editedText.getHeight() - pInsets.top - pInsets.bottom + jInsets.top + jInsets.bottom + 3.0); prefSize.setSize(width, height); editor.setSize(prefSize); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/event/PZoomToEventHandler.java b/extras/src/main/java/edu/umd/cs/piccolox/event/PZoomToEventHandler.java index 270714e..6b86b56 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/event/PZoomToEventHandler.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/event/PZoomToEventHandler.java @@ -50,16 +50,16 @@ setEventFilter(new PInputEventFilter(InputEvent.BUTTON1_MASK)); } - public void mousePressed(PInputEvent aEvent) { + public void mousePressed(final PInputEvent aEvent) { zoomTo(aEvent); } protected void zoomTo(final PInputEvent aEvent) { PBounds zoomToBounds; - PNode picked = aEvent.getPickedNode(); + final PNode picked = aEvent.getPickedNode(); if (picked instanceof PCamera) { - PCamera c = (PCamera) picked; + final PCamera c = (PCamera) picked; zoomToBounds = c.getUnionOfLayerFullBounds(); } else { diff --git a/extras/src/main/java/edu/umd/cs/piccolox/handles/PBoundsHandle.java b/extras/src/main/java/edu/umd/cs/piccolox/handles/PBoundsHandle.java index 9092408..bdf0781 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/handles/PBoundsHandle.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/handles/PBoundsHandle.java @@ -56,9 +56,13 @@ */ public class PBoundsHandle extends PHandle { + /** + * + */ + private static final long serialVersionUID = 1L; private transient PBasicInputEventHandler handleCursorHandler; - public static void addBoundsHandlesTo(PNode aNode) { + public static void addBoundsHandlesTo(final PNode aNode) { aNode.addChild(new PBoundsHandle(PBoundsLocator.createEastLocator(aNode))); aNode.addChild(new PBoundsHandle(PBoundsLocator.createWestLocator(aNode))); aNode.addChild(new PBoundsHandle(PBoundsLocator.createNorthLocator(aNode))); @@ -69,7 +73,7 @@ aNode.addChild(new PBoundsHandle(PBoundsLocator.createSouthWestLocator(aNode))); } - public static void addStickyBoundsHandlesTo(PNode aNode, PCamera camera) { + public static void addStickyBoundsHandlesTo(final PNode aNode, final PCamera camera) { camera.addChild(new PBoundsHandle(PBoundsLocator.createEastLocator(aNode))); camera.addChild(new PBoundsHandle(PBoundsLocator.createWestLocator(aNode))); camera.addChild(new PBoundsHandle(PBoundsLocator.createNorthLocator(aNode))); @@ -80,12 +84,12 @@ camera.addChild(new PBoundsHandle(PBoundsLocator.createSouthWestLocator(aNode))); } - public static void removeBoundsHandlesFrom(PNode aNode) { - ArrayList handles = new ArrayList(); + public static void removeBoundsHandlesFrom(final PNode aNode) { + final ArrayList handles = new ArrayList(); - Iterator i = aNode.getChildrenIterator(); + final Iterator i = aNode.getChildrenIterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); if (each instanceof PBoundsHandle) { handles.add(each); } @@ -93,7 +97,7 @@ aNode.removeChildren(handles); } - public PBoundsHandle(PBoundsLocator aLocator) { + public PBoundsHandle(final PBoundsLocator aLocator) { super(aLocator); } @@ -102,16 +106,16 @@ handleCursorHandler = new PBasicInputEventHandler() { boolean cursorPushed = false; - public void mouseEntered(PInputEvent aEvent) { + public void mouseEntered(final PInputEvent aEvent) { if (!cursorPushed) { aEvent.pushCursor(getCursorFor(((PBoundsLocator) getLocator()).getSide())); cursorPushed = true; } } - public void mouseExited(PInputEvent aEvent) { + public void mouseExited(final PInputEvent aEvent) { if (cursorPushed) { - PPickPath focus = aEvent.getInputManager().getMouseFocus(); + final PPickPath focus = aEvent.getInputManager().getMouseFocus(); if (focus == null || focus.getPickedNode() != PBoundsHandle.this) { aEvent.popCursor(); @@ -120,7 +124,7 @@ } } - public void mouseReleased(PInputEvent event) { + public void mouseReleased(final PInputEvent event) { if (cursorPushed) { event.popCursor(); cursorPushed = false; @@ -138,18 +142,18 @@ return handleCursorHandler; } - public void startHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void startHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); l.getNode().startResizeBounds(); } - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); - PNode n = l.getNode(); - PBounds b = n.getBounds(); + final PNode n = l.getNode(); + final PBounds b = n.getBounds(); - PNode parent = getParent(); + final PNode parent = getParent(); if (parent != n && parent instanceof PCamera) { ((PCamera) parent).localToView(aLocalDimension); } @@ -157,8 +161,8 @@ localToGlobal(aLocalDimension); n.globalToLocal(aLocalDimension); - double dx = aLocalDimension.getWidth(); - double dy = aLocalDimension.getHeight(); + final double dx = aLocalDimension.getWidth(); + final double dy = aLocalDimension.getHeight(); switch (l.getSide()) { case SwingConstants.NORTH: @@ -216,23 +220,23 @@ n.setBounds(b); } - public void endHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void endHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); l.getNode().endResizeBounds(); } - public void flipSiblingBoundsHandles(boolean flipX, boolean flipY) { - Iterator i = getParent().getChildrenIterator(); + public void flipSiblingBoundsHandles(final boolean flipX, final boolean flipY) { + final Iterator i = getParent().getChildrenIterator(); while (i.hasNext()) { - Object each = i.next(); + final Object each = i.next(); if (each instanceof PBoundsHandle) { ((PBoundsHandle) each).flipHandleIfNeeded(flipX, flipY); } } } - public void flipHandleIfNeeded(boolean flipX, boolean flipY) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void flipHandleIfNeeded(final boolean flipX, final boolean flipY) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); if (flipX || flipY) { switch (l.getSide()) { @@ -323,7 +327,7 @@ setLocator(l); } - public Cursor getCursorFor(int side) { + public Cursor getCursorFor(final int side) { switch (side) { case SwingConstants.NORTH: return new Cursor(Cursor.N_RESIZE_CURSOR); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/handles/PHandle.java b/extras/src/main/java/edu/umd/cs/piccolox/handles/PHandle.java index 9026b80..2a138cc 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/handles/PHandle.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/handles/PHandle.java @@ -60,6 +60,10 @@ */ public class PHandle extends PPath { + /** + * + */ + private static final long serialVersionUID = 1L; public static float DEFAULT_HANDLE_SIZE = 8; public static Shape DEFAULT_HANDLE_SHAPE = new Ellipse2D.Float(0f, 0f, DEFAULT_HANDLE_SIZE, DEFAULT_HANDLE_SIZE); public static Color DEFAULT_COLOR = Color.white; @@ -71,7 +75,7 @@ * Construct a new handle that will use the given locator to locate itself * on its parent node. */ - public PHandle(PLocator aLocator) { + public PHandle(final PLocator aLocator) { super(DEFAULT_HANDLE_SHAPE); locator = aLocator; setPaint(DEFAULT_COLOR); @@ -80,27 +84,27 @@ protected void installHandleEventHandlers() { handleDragger = new PDragSequenceEventHandler() { - protected void startDrag(PInputEvent event) { + protected void startDrag(final PInputEvent event) { super.startDrag(event); startHandleDrag(event.getPositionRelativeTo(PHandle.this), event); } - protected void drag(PInputEvent event) { + protected void drag(final PInputEvent event) { super.drag(event); - PDimension aDelta = event.getDeltaRelativeTo(PHandle.this); + final PDimension aDelta = event.getDeltaRelativeTo(PHandle.this); if (aDelta.getWidth() != 0 || aDelta.getHeight() != 0) { dragHandle(aDelta, event); } } - protected void endDrag(PInputEvent event) { + protected void endDrag(final PInputEvent event) { super.endDrag(event); endHandleDrag(event.getPositionRelativeTo(PHandle.this), event); } }; addPropertyChangeListener(PNode.PROPERTY_TRANSFORM, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { relocateHandle(); } }); @@ -135,7 +139,7 @@ * Set the locator that this handle uses to position itself on its parent * node. */ - public void setLocator(PLocator aLocator) { + public void setLocator(final PLocator aLocator) { locator = aLocator; invalidatePaint(); relocateHandle(); @@ -150,20 +154,20 @@ * Override this method to get notified when the handle starts to get * dragged. */ - public void startHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { + public void startHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { } /** * Override this method to get notified as the handle is dragged. */ - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { } /** * Override this method to get notified when the handle stops getting * dragged. */ - public void endHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { + public void endHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { } // **************************************************************** @@ -173,7 +177,7 @@ // position. // **************************************************************** - public void setParent(PNode newParent) { + public void setParent(final PNode newParent) { super.setParent(newParent); relocateHandle(); } @@ -187,12 +191,12 @@ */ public void relocateHandle() { if (locator != null) { - PBounds b = getBoundsReference(); - Point2D aPoint = locator.locatePoint(null); + final PBounds b = getBoundsReference(); + final Point2D aPoint = locator.locatePoint(null); if (locator instanceof PNodeLocator) { - PNode located = ((PNodeLocator) locator).getNode(); - PNode parent = getParent(); + final PNode located = ((PNodeLocator) locator).getNode(); + final PNode parent = getParent(); located.localToGlobal(aPoint); globalToLocal(aPoint); @@ -202,8 +206,8 @@ } } - double newCenterX = aPoint.getX(); - double newCenterY = aPoint.getY(); + final double newCenterX = aPoint.getX(); + final double newCenterY = aPoint.getY(); if (newCenterX != b.getCenterX() || newCenterY != b.getCenterY()) { @@ -216,7 +220,7 @@ // Serialization // **************************************************************** - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); installHandleEventHandlers(); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/handles/PStickyHandleManager.java b/extras/src/main/java/edu/umd/cs/piccolox/handles/PStickyHandleManager.java index 9272a2f..0db22d0 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/handles/PStickyHandleManager.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/handles/PStickyHandleManager.java @@ -35,22 +35,26 @@ public class PStickyHandleManager extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; private PNode target; private PCamera camera; - public PStickyHandleManager(PCamera newCamera, PNode newTarget) { + public PStickyHandleManager(final PCamera newCamera, final PNode newTarget) { setCameraTarget(newCamera, newTarget); PBoundsHandle.addBoundsHandlesTo(this); } - public void setCameraTarget(PCamera newCamera, PNode newTarget) { + public void setCameraTarget(final PCamera newCamera, final PNode newTarget) { camera = newCamera; camera.addChild(this); target = newTarget; } - public boolean setBounds(double x, double y, double width, double height) { - PBounds b = new PBounds(x, y, width, height); + public boolean setBounds(final double x, final double y, final double width, final double height) { + final PBounds b = new PBounds(x, y, width, height); camera.localToGlobal(b); camera.localToView(b); target.globalToLocal(b); @@ -63,10 +67,10 @@ } public PBounds getBoundsReference() { - PBounds targetBounds = target.getFullBounds(); + final PBounds targetBounds = target.getFullBounds(); camera.viewToLocal(targetBounds); camera.globalToLocal(targetBounds); - PBounds bounds = super.getBoundsReference(); + final PBounds bounds = super.getBoundsReference(); bounds.setRect(targetBounds); return super.getBoundsReference(); } @@ -81,7 +85,7 @@ target.endResizeBounds(); } - public boolean pickAfterChildren(PPickPath pickPath) { + public boolean pickAfterChildren(final PPickPath pickPath) { return false; } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/P3DRect.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/P3DRect.java index 57a882c..a2d502c 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/P3DRect.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/P3DRect.java @@ -28,11 +28,18 @@ */ package edu.umd.cs.piccolox.nodes; -import java.awt.*; -import java.awt.geom.*; -import edu.umd.cs.piccolo.*; -import edu.umd.cs.piccolo.util.*; -import edu.umd.cs.piccolox.*; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Paint; +import java.awt.Stroke; +import java.awt.geom.GeneralPath; +import java.awt.geom.Rectangle2D; + +import edu.umd.cs.piccolo.PNode; +import edu.umd.cs.piccolo.util.PBounds; +import edu.umd.cs.piccolo.util.PPaintContext; +import edu.umd.cs.piccolox.PFrame; /** * This is a simple node that draws a "3D" rectangle within the bounds of the @@ -45,12 +52,16 @@ */ public class P3DRect extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; private Color topLeftOuterColor; private Color topLeftInnerColor; private Color bottomRightInnerColor; private Color bottomRightOuterColor; - private GeneralPath path; - private Stroke stroke; + private final GeneralPath path; + private final Stroke stroke; private boolean raised; public P3DRect() { @@ -59,16 +70,16 @@ path = new GeneralPath(); } - public P3DRect(Rectangle2D bounds) { + public P3DRect(final Rectangle2D bounds) { this(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); } - public P3DRect(double x, double y, double width, double height) { + public P3DRect(final double x, final double y, final double width, final double height) { this(); setBounds(x, y, width, height); } - public void setRaised(boolean raised) { + public void setRaised(final boolean raised) { this.raised = raised; setPaint(getPaint()); } @@ -77,18 +88,18 @@ return raised; } - protected void paint(PPaintContext paintContext) { - Graphics2D g2 = paintContext.getGraphics(); + protected void paint(final PPaintContext paintContext) { + final Graphics2D g2 = paintContext.getGraphics(); - double x = getX(); - double y = getY(); - double width = getWidth(); - double height = getHeight(); - double magX = g2.getTransform().getScaleX(); - double magY = g2.getTransform().getScaleY(); - double dx = (float) (1.0 / magX); - double dy = (float) (1.0 / magY); - PBounds bounds = getBounds(); + final double x = getX(); + final double y = getY(); + final double width = getWidth(); + final double height = getHeight(); + final double magX = g2.getTransform().getScaleX(); + final double magY = g2.getTransform().getScaleY(); + final double dx = (float) (1.0 / magX); + final double dy = (float) (1.0 / magY); + final PBounds bounds = getBounds(); g2.setPaint(getPaint()); g2.fill(bounds); @@ -109,25 +120,25 @@ g2.draw(path); path.reset(); - path.moveTo((float) (x + width), (float) (y)); + path.moveTo((float) (x + width), (float) y); path.lineTo((float) (x + width), (float) (y + height)); - path.lineTo((float) (x), (float) (y + height)); + path.lineTo((float) x, (float) (y + height)); g2.setPaint(bottomRightOuterColor); g2.draw(path); path.reset(); path.moveTo((float) (x + width - dx), (float) (y + dy)); path.lineTo((float) (x + width - dx), (float) (y + height - dy)); - path.lineTo((float) (x), (float) (y + height - dy)); + path.lineTo((float) x, (float) (y + height - dy)); g2.setPaint(bottomRightInnerColor); g2.draw(path); } - public void setPaint(Paint newPaint) { + public void setPaint(final Paint newPaint) { super.setPaint(newPaint); if (newPaint instanceof Color) { - Color color = (Color) newPaint; + final Color color = (Color) newPaint; if (raised) { topLeftOuterColor = color.brighter(); @@ -150,15 +161,20 @@ } } - public static void main(String[] args) { + public static void main(final String[] args) { new PFrame() { + /** + * + */ + private static final long serialVersionUID = 1L; + public void initialize() { getCanvas().setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); - P3DRect rect1 = new P3DRect(50, 50, 100, 100); + final P3DRect rect1 = new P3DRect(50, 50, 100, 100); rect1.setPaint(new Color(239, 235, 222)); - P3DRect rect2 = new P3DRect(50, 50, 100, 100); + final P3DRect rect2 = new P3DRect(50, 50, 100, 100); rect2.setPaint(new Color(239, 235, 222)); rect2.translate(110, 0); rect2.setRaised(false); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PCacheCamera.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PCacheCamera.java index f056c33..dadeac5 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PCacheCamera.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PCacheCamera.java @@ -52,6 +52,10 @@ */ public class PCacheCamera extends PCamera { + /** + * + */ + private static final long serialVersionUID = 1L; private BufferedImage paintBuffer; private boolean imageAnimate; private PBounds imageAnimateBounds; @@ -60,7 +64,7 @@ * Get the buffer used to provide fast image based animation */ protected BufferedImage getPaintBuffer() { - PBounds fRef = getFullBoundsReference(); + final PBounds fRef = getFullBoundsReference(); // TODO eclipse formatting made this ugly if (paintBuffer == null || paintBuffer.getWidth() < fRef.getWidth() || paintBuffer.getHeight() < fRef.getHeight()) { @@ -75,12 +79,12 @@ * Caches the information necessary to animate from the current view bounds * to the specified centerBounds */ - private AffineTransform cacheViewBounds(Rectangle2D centerBounds, boolean scaleToFit) { - PBounds viewBounds = getViewBounds(); + private AffineTransform cacheViewBounds(final Rectangle2D centerBounds, final boolean scaleToFit) { + final PBounds viewBounds = getViewBounds(); // Initialize the image to the union of the current and destination // bounds - PBounds imageBounds = new PBounds(viewBounds); + final PBounds imageBounds = new PBounds(viewBounds); imageBounds.add(centerBounds); animateViewToCenterBounds(imageBounds, scaleToFit, 0); @@ -89,7 +93,7 @@ // Now create the actual cache image that we will use to animate fast - BufferedImage buffer = getPaintBuffer(); + final BufferedImage buffer = getPaintBuffer(); Paint fPaint = Color.white; if (getPaint() != null) { fPaint = getPaint(); @@ -105,12 +109,12 @@ // The code below is just copied from animateViewToCenterBounds to // create the correct transform to center the specified bounds - PDimension delta = viewBounds.deltaRequiredToCenter(centerBounds); - PAffineTransform newTransform = getViewTransform(); + final PDimension delta = viewBounds.deltaRequiredToCenter(centerBounds); + final PAffineTransform newTransform = getViewTransform(); newTransform.translate(delta.width, delta.height); if (scaleToFit) { - double s = Math.min(viewBounds.getWidth() / centerBounds.getWidth(), viewBounds.getHeight() + final double s = Math.min(viewBounds.getWidth() / centerBounds.getWidth(), viewBounds.getHeight() / centerBounds.getHeight()); newTransform.scaleAboutPoint(s, centerBounds.getCenterX(), centerBounds.getCenterY()); } @@ -130,13 +134,13 @@ * Mimics the standard animateViewToCenterBounds but uses a cached image for * performance rather than re-rendering the scene at each step */ - public PTransformActivity animateStaticViewToCenterBoundsFast(Rectangle2D centerBounds, boolean shouldScaleToFit, - long duration) { + public PTransformActivity animateStaticViewToCenterBoundsFast(final Rectangle2D centerBounds, + final boolean shouldScaleToFit, final long duration) { if (duration == 0) { return animateViewToCenterBounds(centerBounds, shouldScaleToFit, duration); } - AffineTransform newViewTransform = cacheViewBounds(centerBounds, shouldScaleToFit); + final AffineTransform newViewTransform = cacheViewBounds(centerBounds, shouldScaleToFit); return animateStaticViewToTransformFast(newViewTransform, duration); } @@ -145,23 +149,23 @@ * This copies the behavior of the standard animateViewToTransform but * clears the cache when it is done */ - protected PTransformActivity animateStaticViewToTransformFast(AffineTransform destination, long duration) { + protected PTransformActivity animateStaticViewToTransformFast(final AffineTransform destination, final long duration) { if (duration == 0) { setViewTransform(destination); return null; } - PTransformActivity.Target t = new PTransformActivity.Target() { - public void setTransform(AffineTransform aTransform) { + final PTransformActivity.Target t = new PTransformActivity.Target() { + public void setTransform(final AffineTransform aTransform) { PCacheCamera.this.setViewTransform(aTransform); } - public void getSourceMatrix(double[] aSource) { + public void getSourceMatrix(final double[] aSource) { getViewTransformReference().getMatrix(aSource); } }; - PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destination) { + final PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destination) { protected void activityFinished() { clearViewCache(); repaint(); @@ -169,7 +173,7 @@ } }; - PRoot r = getRoot(); + final PRoot r = getRoot(); if (r != null) { r.getActivityScheduler().addActivity(ta); } @@ -181,15 +185,15 @@ * Overrides the camera's full paint method to do the fast rendering when * possible */ - public void fullPaint(PPaintContext paintContext) { + public void fullPaint(final PPaintContext paintContext) { if (imageAnimate) { - PBounds fRef = getFullBoundsReference(); - PBounds viewBounds = getViewBounds(); - double scale = getFullBoundsReference().getWidth() / imageAnimateBounds.getWidth(); - double xOffset = (viewBounds.getX() - imageAnimateBounds.getX()) * scale; - double yOffset = (viewBounds.getY() - imageAnimateBounds.getY()) * scale; - double scaleW = viewBounds.getWidth() * scale; - double scaleH = viewBounds.getHeight() * scale; + final PBounds fRef = getFullBoundsReference(); + final PBounds viewBounds = getViewBounds(); + final double scale = getFullBoundsReference().getWidth() / imageAnimateBounds.getWidth(); + final double xOffset = (viewBounds.getX() - imageAnimateBounds.getX()) * scale; + final double yOffset = (viewBounds.getY() - imageAnimateBounds.getY()) * scale; + final double scaleW = viewBounds.getWidth() * scale; + final double scaleH = viewBounds.getHeight() * scale; paintContext.getGraphics().drawImage(paintBuffer, 0, 0, (int) Math.ceil(fRef.getWidth()), (int) Math.ceil(fRef.getHeight()), (int) Math.floor(xOffset), (int) Math.floor(yOffset), (int) Math.ceil(xOffset + scaleW), (int) Math.ceil(yOffset + scaleH), null); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PClip.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PClip.java index 87b6733..6d352c8 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PClip.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PClip.java @@ -48,16 +48,22 @@ */ public class PClip extends PPath { + /** + * + */ + private static final long serialVersionUID = 1L; + public PBounds computeFullBounds(PBounds dstBounds) { - if (dstBounds == null) + if (dstBounds == null) { dstBounds = new PBounds(); + } dstBounds.reset(); dstBounds.add(getBoundsReference()); localToParent(dstBounds); return dstBounds; } - public void repaintFrom(PBounds localBounds, PNode childOrThis) { + public void repaintFrom(final PBounds localBounds, final PNode childOrThis) { if (childOrThis != this) { Rectangle2D.intersect(getBoundsReference(), localBounds, localBounds); super.repaintFrom(localBounds, childOrThis); @@ -67,27 +73,27 @@ } } - protected void paint(PPaintContext paintContext) { - Paint p = getPaint(); + protected void paint(final PPaintContext paintContext) { + final Paint p = getPaint(); if (p != null) { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); g2.setPaint(p); g2.fill(getPathReference()); } paintContext.pushClip(getPathReference()); } - protected void paintAfterChildren(PPaintContext paintContext) { + protected void paintAfterChildren(final PPaintContext paintContext) { paintContext.popClip(getPathReference()); if (getStroke() != null && getStrokePaint() != null) { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); g2.setPaint(getStrokePaint()); g2.setStroke(getStroke()); g2.draw(getPathReference()); } } - public boolean fullPick(PPickPath pickPath) { + public boolean fullPick(final PPickPath pickPath) { if (getPickable() && fullIntersects(pickPath.getPickBounds())) { pickPath.pushNode(this); pickPath.pushTransform(getTransformReference(false)); @@ -97,11 +103,12 @@ } if (getChildrenPickable() && getPathReference().intersects(pickPath.getPickBounds())) { - int count = getChildrenCount(); + final int count = getChildrenCount(); for (int i = count - 1; i >= 0; i--) { - PNode each = getChild(i); - if (each.fullPick(pickPath)) + final PNode each = getChild(i); + if (each.fullPick(pickPath)) { return true; + } } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PComposite.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PComposite.java index 39e07b2..988de0c 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PComposite.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PComposite.java @@ -61,12 +61,17 @@ */ /** + * + */ + private static final long serialVersionUID = 1L; + + /** * Return true if this node or any pickable descendends are picked. If a * pick occurs the pickPath is modified so that this node is always returned * as the picked node, event if it was a decendent node that initialy * reported the pick. */ - public boolean fullPick(PPickPath pickPath) { + public boolean fullPick(final PPickPath pickPath) { if (super.fullPick(pickPath)) { PNode picked = pickPath.getPickedNode(); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLens.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLens.java index 8c44434..bccb3b1 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLens.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLens.java @@ -63,13 +63,17 @@ */ public class PLens extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; public static double LENS_DRAGBAR_HEIGHT = 20; public static Paint DEFAULT_DRAGBAR_PAINT = Color.DARK_GRAY; public static Paint DEFAULT_LENS_PAINT = Color.LIGHT_GRAY; - private PPath dragBar; - private PCamera camera; - private PDragEventHandler lensDragger; + private final PPath dragBar; + private final PCamera camera; + private final PDragEventHandler lensDragger; public PLens() { // Drag bar gets resized to fit the available space, so any rectangle @@ -93,13 +97,13 @@ // When this PLens is dragged around adjust the cameras view transform. addPropertyChangeListener(PNode.PROPERTY_TRANSFORM, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { camera.setViewTransform(getInverseTransform()); } }); } - public PLens(PLayer layer) { + public PLens(final PLayer layer) { this(); addLayer(0, layer); } @@ -116,11 +120,11 @@ return lensDragger; } - public void addLayer(int index, PLayer layer) { + public void addLayer(final int index, final PLayer layer) { camera.addLayer(index, layer); } - public void removeLayer(PLayer layer) { + public void removeLayer(final PLayer layer) { camera.removeLayer(layer); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLine.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLine.java index d996264..3ef4468 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLine.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PLine.java @@ -52,11 +52,15 @@ */ public class PLine extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; private static final PAffineTransform TEMP_TRANSFORM = new PAffineTransform(); private static final BasicStroke DEFAULT_STROKE = new BasicStroke(1.0f); private static final Color DEFAULT_STROKE_PAINT = Color.black; - private transient LineShape line; + private transient final LineShape line; private transient Stroke stroke; private Paint strokePaint; @@ -73,7 +77,7 @@ this(null); } - public PLine(LineShape line, Stroke aStroke) { + public PLine(final LineShape line, final Stroke aStroke) { this(line); stroke = aStroke; } @@ -86,8 +90,8 @@ return strokePaint; } - public void setStrokePaint(Paint aPaint) { - Paint old = strokePaint; + public void setStrokePaint(final Paint aPaint) { + final Paint old = strokePaint; strokePaint = aPaint; invalidatePaint(); firePropertyChange(PPath.PROPERTY_CODE_STROKE_PAINT, PPath.PROPERTY_STROKE_PAINT, old, strokePaint); @@ -97,8 +101,8 @@ return stroke; } - public void setStroke(Stroke aStroke) { - Stroke old = stroke; + public void setStroke(final Stroke aStroke) { + final Stroke old = stroke; stroke = aStroke; updateBoundsFromLine(); invalidatePaint(); @@ -114,9 +118,9 @@ return false; } - Rectangle2D lineBounds = line.getBounds2D(); - Rectangle2D lineStrokeBounds = getLineBoundsWithStroke(); - double strokeOutset = Math.max(lineStrokeBounds.getWidth() - lineBounds.getWidth(), lineStrokeBounds + final Rectangle2D lineBounds = line.getBounds2D(); + final Rectangle2D lineStrokeBounds = getLineBoundsWithStroke(); + final double strokeOutset = Math.max(lineStrokeBounds.getWidth() - lineBounds.getWidth(), lineStrokeBounds .getHeight() - lineBounds.getHeight()); @@ -134,7 +138,7 @@ return true; } - public boolean intersects(Rectangle2D aBounds) { + public boolean intersects(final Rectangle2D aBounds) { if (super.intersects(aBounds)) { if (line.intersects(aBounds)) { return true; @@ -160,7 +164,7 @@ resetBounds(); } else { - Rectangle2D b = getLineBoundsWithStroke(); + final Rectangle2D b = getLineBoundsWithStroke(); super.setBounds(b.getX(), b.getY(), b.getWidth(), b.getHeight()); } } @@ -169,8 +173,8 @@ // Painting // **************************************************************** - protected void paint(PPaintContext paintContext) { - Graphics2D g2 = paintContext.getGraphics(); + protected void paint(final PPaintContext paintContext) { + final Graphics2D g2 = paintContext.getGraphics(); if (stroke != null && strokePaint != null) { g2.setPaint(strokePaint); @@ -187,7 +191,7 @@ return line.getPointCount(); } - public Point2D getPoint(int i, Point2D dst) { + public Point2D getPoint(final int i, Point2D dst) { if (dst == null) { dst = new Point2D.Double(); } @@ -200,17 +204,17 @@ invalidatePaint(); } - public void setPoint(int i, double x, double y) { + public void setPoint(final int i, final double x, final double y) { line.setPoint(i, x, y); lineChanged(); } - public void addPoint(int i, double x, double y) { + public void addPoint(final int i, final double x, final double y) { line.addPoint(i, x, y); lineChanged(); } - public void removePoints(int i, int n) { + public void removePoints(final int i, final int n) { line.removePoints(i, n); lineChanged(); } @@ -224,12 +228,12 @@ // Serialization // **************************************************************** - private void writeObject(ObjectOutputStream out) throws IOException { + private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); PUtil.writeStroke(stroke, out); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); stroke = PUtil.readStroke(in); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PNodeCache.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PNodeCache.java index 4710fff..af4bf42 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PNodeCache.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PNodeCache.java @@ -59,6 +59,10 @@ */ public class PNodeCache extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; private transient Image imageCache; private boolean validatingCache; @@ -68,17 +72,17 @@ * Fill in the cacheOffsetRef if needed to make your image cache line up * with the nodes children. */ - public Image createImageCache(Dimension2D cacheOffsetRef) { + public Image createImageCache(final Dimension2D cacheOffsetRef) { return toImage(); } public Image getImageCache() { if (imageCache == null) { - PDimension cacheOffsetRef = new PDimension(); + final PDimension cacheOffsetRef = new PDimension(); validatingCache = true; resetBounds(); imageCache = createImageCache(cacheOffsetRef); - PBounds b = getFullBoundsReference(); + final PBounds b = getFullBoundsReference(); setBounds(b.getX() + cacheOffsetRef.getWidth(), b.getY() + cacheOffsetRef.getHeight(), imageCache .getWidth(null), imageCache.getHeight(null)); validatingCache = false; @@ -96,24 +100,24 @@ } } - public void repaintFrom(PBounds localBounds, PNode childOrThis) { + public void repaintFrom(final PBounds localBounds, final PNode childOrThis) { if (!validatingCache) { super.repaintFrom(localBounds, childOrThis); invalidateCache(); } } - public void fullPaint(PPaintContext paintContext) { + public void fullPaint(final PPaintContext paintContext) { if (validatingCache) { super.fullPaint(paintContext); } else { - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); g2.drawImage(getImageCache(), (int) getX(), (int) getY(), null); } } - protected boolean pickAfterChildren(PPickPath pickPath) { + protected boolean pickAfterChildren(final PPickPath pickPath) { return false; } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PStyledText.java b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PStyledText.java index c4d7cd1..fc4123c 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/nodes/PStyledText.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/nodes/PStyledText.java @@ -62,6 +62,10 @@ */ public class PStyledText extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; protected static FontRenderContext SWING_FRC = new FontRenderContext(null, true, false); protected static Line2D paintLine = new Line2D.Double(); @@ -85,7 +89,7 @@ * Controls whether this node changes its width to fit the width of its * text. If flag is true it does; if flag is false it doesn't */ - public void setConstrainWidthToTextWidth(boolean constrainWidthToTextWidth) { + public void setConstrainWidthToTextWidth(final boolean constrainWidthToTextWidth) { this.constrainWidthToTextWidth = constrainWidthToTextWidth; recomputeLayout(); } @@ -94,7 +98,7 @@ * Controls whether this node changes its height to fit the height of its * text. If flag is true it does; if flag is false it doesn't */ - public void setConstrainHeightToTextHeight(boolean constrainHeightToTextHeight) { + public void setConstrainHeightToTextHeight(final boolean constrainHeightToTextHeight) { this.constrainHeightToTextHeight = constrainHeightToTextHeight; recomputeLayout(); } @@ -125,7 +129,7 @@ /** * Set the document on this PStyledText */ - public void setDocument(Document document) { + public void setDocument(final Document document) { // Save the document this.document = document; @@ -140,7 +144,7 @@ try { documentString = document.getText(0, document.getLength()); } - catch (BadLocationException e) { + catch (final BadLocationException e) { // Since this the location we're providing comes from directly // querying the document, this is impossible in a single threaded // model @@ -148,18 +152,18 @@ } // The paragraph start and end indices - ArrayList pEnds = extractParagraphRanges(documentString); + final ArrayList pEnds = extractParagraphRanges(documentString); // The default style context - which will be reused - StyleContext styleContext = StyleContext.getDefaultStyleContext(); + final StyleContext styleContext = StyleContext.getDefaultStyleContext(); int pos; RunInfo paragraphRange = null; AttributedString attributedString; - Iterator contentIterator = stringContents.iterator(); - Iterator paragraphIterator = pEnds.iterator(); + final Iterator contentIterator = stringContents.iterator(); + final Iterator paragraphIterator = pEnds.iterator(); while (contentIterator.hasNext() && paragraphIterator.hasNext()) { paragraphRange = (RunInfo) paragraphIterator.next(); attributedString = (AttributedString) contentIterator.next(); @@ -171,7 +175,7 @@ // Small assumption here that there is one root element - can fix // for more general support later - Element rootElement = document.getDefaultRootElement(); + final Element rootElement = document.getDefaultRootElement(); // If the string is length 0 then we just need to add the attributes // once @@ -179,16 +183,16 @@ curElement = drillDownFromRoot(pos, rootElement); // These are the mandatory attributes - AttributeSet attributes = curElement.getAttributes(); - Color foreground = styleContext.getForeground(attributes); + final AttributeSet attributes = curElement.getAttributes(); + final Color foreground = styleContext.getForeground(attributes); - attributedString.addAttribute(TextAttribute.FOREGROUND, foreground, (int) Math.max(0, curElement + attributedString.addAttribute(TextAttribute.FOREGROUND, foreground, Math.max(0, curElement .getStartOffset() - - paragraphRange.startIndex), (int) Math.min(paragraphRange.length(), curElement.getEndOffset() + - paragraphRange.startIndex), Math.min(paragraphRange.length(), curElement.getEndOffset() - paragraphRange.startIndex)); // These are the optional attributes - Font font = extractFont(styleContext, pos, rootElement, attributes); + final Font font = extractFont(styleContext, pos, rootElement, attributes); applyFontAttribute(paragraphRange, attributedString, curElement, font); applyBackgroundAttribute(styleContext, paragraphRange, attributedString, curElement, attributes); applyUnderlineAttribute(paragraphRange, attributedString, curElement, attributes); @@ -201,16 +205,15 @@ curElement = drillDownFromRoot(pos, rootElement); // These are the mandatory attributes - AttributeSet attributes = curElement.getAttributes(); - Color foreground = styleContext.getForeground(attributes); + final AttributeSet attributes = curElement.getAttributes(); + final Color foreground = styleContext.getForeground(attributes); - attributedString.addAttribute(TextAttribute.FOREGROUND, foreground, (int) Math.max(0, curElement + attributedString.addAttribute(TextAttribute.FOREGROUND, foreground, Math.max(0, curElement .getStartOffset() - - paragraphRange.startIndex), (int) Math.min(paragraphRange.length(), curElement - .getEndOffset() + - paragraphRange.startIndex), Math.min(paragraphRange.length(), curElement.getEndOffset() - paragraphRange.startIndex)); - Font font = extractFont(styleContext, pos, rootElement, attributes); + final Font font = extractFont(styleContext, pos, rootElement, attributes); applyFontAttribute(paragraphRange, attributedString, curElement, font); // These are the optional attributes @@ -230,7 +233,7 @@ recomputeLayout(); } - private Element drillDownFromRoot(int pos, Element rootElement) { + private Element drillDownFromRoot(final int pos, final Element rootElement) { Element curElement; // Before each pass, start at the root curElement = rootElement; @@ -242,50 +245,51 @@ return curElement; } - private void applyFontAttribute(RunInfo paragraphRange, AttributedString attributedString, Element curElement, - Font font) { + private void applyFontAttribute(final RunInfo paragraphRange, final AttributedString attributedString, + final Element curElement, final Font font) { if (font != null) { - attributedString.addAttribute(TextAttribute.FONT, font, (int) Math.max(0, curElement.getStartOffset() - - paragraphRange.startIndex), (int) Math.min(paragraphRange.endIndex - paragraphRange.startIndex, + attributedString.addAttribute(TextAttribute.FONT, font, Math.max(0, curElement.getStartOffset() + - paragraphRange.startIndex), Math.min(paragraphRange.endIndex - paragraphRange.startIndex, curElement.getEndOffset() - paragraphRange.startIndex)); } } - private void applyStrikeThroughAttribute(RunInfo paragraphRange, AttributedString attributedString, - Element curElement, AttributeSet attributes) { - boolean strikethrough = StyleConstants.isStrikeThrough(attributes); + private void applyStrikeThroughAttribute(final RunInfo paragraphRange, final AttributedString attributedString, + final Element curElement, final AttributeSet attributes) { + final boolean strikethrough = StyleConstants.isStrikeThrough(attributes); if (strikethrough) { - attributedString.addAttribute(TextAttribute.STRIKETHROUGH, Boolean.TRUE, (int) Math.max(0, curElement + attributedString.addAttribute(TextAttribute.STRIKETHROUGH, Boolean.TRUE, Math.max(0, curElement .getStartOffset() - - paragraphRange.startIndex), (int) Math.min(paragraphRange.endIndex - paragraphRange.startIndex, + - paragraphRange.startIndex), Math.min(paragraphRange.endIndex - paragraphRange.startIndex, curElement.getEndOffset() - paragraphRange.startIndex)); } } - private void applyUnderlineAttribute(RunInfo paragraphRange, AttributedString attributedString, Element curElement, - AttributeSet attributes) { - boolean underline = StyleConstants.isUnderline(attributes); + private void applyUnderlineAttribute(final RunInfo paragraphRange, final AttributedString attributedString, + final Element curElement, final AttributeSet attributes) { + final boolean underline = StyleConstants.isUnderline(attributes); if (underline) { - attributedString.addAttribute(TextAttribute.UNDERLINE, Boolean.TRUE, (int) Math.max(0, curElement + attributedString.addAttribute(TextAttribute.UNDERLINE, Boolean.TRUE, Math.max(0, curElement .getStartOffset() - - paragraphRange.startIndex), (int) Math.min(paragraphRange.endIndex - paragraphRange.startIndex, + - paragraphRange.startIndex), Math.min(paragraphRange.endIndex - paragraphRange.startIndex, curElement.getEndOffset() - paragraphRange.startIndex)); } } - private void applyBackgroundAttribute(StyleContext style, RunInfo paragraphRange, - AttributedString attributedString, Element curElement, AttributeSet attributes) { - Color background = (attributes.isDefined(StyleConstants.Background)) ? style.getBackground(attributes) : null; + private void applyBackgroundAttribute(final StyleContext style, final RunInfo paragraphRange, + final AttributedString attributedString, final Element curElement, final AttributeSet attributes) { + final Color background = attributes.isDefined(StyleConstants.Background) ? style.getBackground(attributes) + : null; if (background != null) { - attributedString.addAttribute(TextAttribute.BACKGROUND, background, (int) Math.max(0, curElement - .getStartOffset() - - paragraphRange.startIndex), (int) Math.min(paragraphRange.endIndex - paragraphRange.startIndex, + attributedString.addAttribute(TextAttribute.BACKGROUND, background, Math.max(0, curElement.getStartOffset() + - paragraphRange.startIndex), Math.min(paragraphRange.endIndex - paragraphRange.startIndex, curElement.getEndOffset() - paragraphRange.startIndex)); } } - private Font extractFont(StyleContext style, int pos, Element rootElement, AttributeSet attributes) { - Font font = (attributes.isDefined(StyleConstants.FontSize) || attributes.isDefined(StyleConstants.FontFamily)) ? style + private Font extractFont(final StyleContext style, final int pos, final Element rootElement, + final AttributeSet attributes) { + Font font = attributes.isDefined(StyleConstants.FontSize) || attributes.isDefined(StyleConstants.FontFamily) ? style .getFont(attributes) : null; if (font == null) { @@ -305,14 +309,14 @@ return font; } - private ArrayList extractParagraphRanges(String documentString) { + private ArrayList extractParagraphRanges(final String documentString) { // The paragraph start and end indices - ArrayList paragraphRanges = new ArrayList(); + final ArrayList paragraphRanges = new ArrayList(); // The current position in the specified range int pos = 0; - StringTokenizer tokenizer = new StringTokenizer(documentString, "\n", true); + final StringTokenizer tokenizer = new StringTokenizer(documentString, "\n", true); // lastNewLine is used to detect the case when two newlines follow // in direct succession @@ -321,7 +325,7 @@ boolean lastNewLine = true; for (int i = 0; tokenizer.hasMoreTokens(); i++) { - String token = tokenizer.nextToken(); + final String token = tokenizer.nextToken(); // If the token if (token.equals("\n")) { @@ -372,19 +376,20 @@ * this node are shrunk to fit around those text bounds. */ public void recomputeLayout() { - if (stringContents == null) + if (stringContents == null) { return; + } - ArrayList linesList = new ArrayList(); + final ArrayList linesList = new ArrayList(); double textWidth = 0; double textHeight = 0; - Iterator contentIterator = stringContents.iterator(); + final Iterator contentIterator = stringContents.iterator(); while (contentIterator.hasNext()) { - AttributedString ats = (AttributedString) contentIterator.next(); - AttributedCharacterIterator itr = ats.getIterator(); + final AttributedString ats = (AttributedString) contentIterator.next(); + final AttributedCharacterIterator itr = ats.getIterator(); LineBreakMeasurer measurer; ArrayList breakList = null; @@ -407,7 +412,7 @@ newLine = false; // Add in the old line dimensions - double lineHeight = (lineInfo == null) ? 0 : lineInfo.maxAscent + lineInfo.maxDescent + final double lineHeight = lineInfo == null ? 0 : lineInfo.maxAscent + lineInfo.maxDescent + lineInfo.leading; textHeight = textHeight + lineHeight; textWidth = Math.max(textWidth, lineWidth); @@ -417,7 +422,7 @@ linesList.add(lineInfo); } - int lineEnd = ((Integer) breakList.get(0)).intValue(); + final int lineEnd = ((Integer) breakList.get(0)).intValue(); if (lineEnd <= itr.getRunLimit()) { breakList.remove(0); newLine = true; @@ -425,14 +430,14 @@ aTextLayout = measurer.nextLayout(Float.MAX_VALUE, Math.min(lineEnd, itr.getRunLimit()), false); - SegmentInfo sInfo = new SegmentInfo(); + final SegmentInfo sInfo = new SegmentInfo(); sInfo.font = (Font) itr.getAttribute(TextAttribute.FONT); sInfo.foreground = (Color) itr.getAttribute(TextAttribute.FOREGROUND); sInfo.background = (Color) itr.getAttribute(TextAttribute.BACKGROUND); sInfo.underline = (Boolean) itr.getAttribute(TextAttribute.UNDERLINE); sInfo.layout = aTextLayout; - FontMetrics metrics = StyleContext.getDefaultStyleContext().getFontMetrics( + final FontMetrics metrics = StyleContext.getDefaultStyleContext().getFontMetrics( (Font) itr.getAttribute(TextAttribute.FONT)); lineInfo.maxAscent = Math.max(lineInfo.maxAscent, metrics.getMaxAscent()); lineInfo.maxDescent = Math.max(lineInfo.maxDescent, metrics.getMaxDescent()); @@ -444,7 +449,8 @@ lineWidth = lineWidth + aTextLayout.getAdvance(); } - double lineHeight = (lineInfo == null) ? 0 : lineInfo.maxAscent + lineInfo.maxDescent + lineInfo.leading; + final double lineHeight = lineInfo == null ? 0 : lineInfo.maxAscent + lineInfo.maxDescent + + lineInfo.leading; textHeight = textHeight + lineHeight; textWidth = Math.max(textWidth, lineWidth); } @@ -454,9 +460,10 @@ constrainDimensionsIfNeeded(textWidth, textHeight); } - private void constrainDimensionsIfNeeded(double textWidth, double textHeight) { - if (!constrainWidthToTextWidth && !constrainHeightToTextHeight) + private void constrainDimensionsIfNeeded(final double textWidth, final double textHeight) { + if (!constrainWidthToTextWidth && !constrainHeightToTextHeight) { return; + } double newWidth = getWidth(); double newHeight = getHeight(); @@ -474,7 +481,7 @@ // Because swing doesn't use fractional font metrics by default, we use // LineBreakMeasurer to find out where Swing is going to break them - private ArrayList extractLineBreaks(AttributedCharacterIterator itr, LineBreakMeasurer measurer) { + private ArrayList extractLineBreaks(final AttributedCharacterIterator itr, final LineBreakMeasurer measurer) { ArrayList breakList; breakList = new ArrayList(); while (measurer.getPosition() < itr.getEndIndex()) { @@ -497,7 +504,7 @@ // Small assumption here that there is one root element - can fix // for more general support later - Element rootElement = document.getDefaultRootElement(); + final Element rootElement = document.getDefaultRootElement(); // The current element will be used as a temp variable while searching // for the leaf element at the current position @@ -508,25 +515,24 @@ curElement = curElement.getElement(curElement.getElementIndex(0)); } - StyleContext context = StyleContext.getDefaultStyleContext(); - Font font = context.getFont(curElement.getAttributes()); + final StyleContext context = StyleContext.getDefaultStyleContext(); + final Font font = context.getFont(curElement.getAttributes()); - FontMetrics curFM = context.getFontMetrics(font); + final FontMetrics curFM = context.getFontMetrics(font); return curFM.getMaxAscent() + curFM.getMaxDescent() + curFM.getLeading(); } - protected void paint(PPaintContext paintContext) { - if (lines == null || lines.length == 0) - return; - - float x = (float) (getX() + insets.left); + protected void paint(final PPaintContext paintContext) { + if (lines == null || lines.length == 0) { + return; + } + + final float x = (float) (getX() + insets.left); float y = (float) (getY() + insets.top); - float bottomY = (float) (getY() + getHeight() - insets.bottom); + final float bottomY = (float) (getY() + getHeight() - insets.bottom); - - - Graphics2D g2 = paintContext.getGraphics(); + final Graphics2D g2 = paintContext.getGraphics(); if (getPaint() != null) { g2.setPaint(getPaint()); @@ -545,9 +551,9 @@ } for (int j = 0; j < lineInfo.segments.size(); j++) { - SegmentInfo sInfo = (SegmentInfo) lineInfo.segments.get(j); - float width = sInfo.layout.getAdvance(); - + final SegmentInfo sInfo = (SegmentInfo) lineInfo.segments.get(j); + final float width = sInfo.layout.getAdvance(); + if (sInfo.background != null) { g2.setPaint(sInfo.background); g2.fill(new Rectangle2D.Double(curX, y - lineInfo.maxAscent, width, lineInfo.maxAscent @@ -575,9 +581,9 @@ y += lineInfo.maxDescent + lineInfo.leading; } - } + } - public void fullPaint(PPaintContext paintContext) { + public void fullPaint(final PPaintContext paintContext) { if (!editing) { super.fullPaint(paintContext); } @@ -586,7 +592,7 @@ /** * Set whether this text is editing */ - public void setEditing(boolean editing) { + public void setEditing(final boolean editing) { this.editing = editing; } @@ -600,7 +606,7 @@ /** * Set the insets of the text */ - public void setInsets(Insets insets) { + public void setInsets(final Insets insets) { if (insets != null) { this.insets.left = insets.left; this.insets.right = insets.right; @@ -621,7 +627,7 @@ /** * Add a call to recompute the layout after each bounds change */ - public boolean setBounds(double x, double y, double w, double h) { + public boolean setBounds(final double x, final double y, final double w, final double h) { if (document == null || !super.setBounds(x, y, w, h)) { return false; } @@ -640,9 +646,9 @@ public RunInfo() { } - public RunInfo(int runStart, int runLimit) { - this.startIndex = runStart; - this.endIndex = runLimit; + public RunInfo(final int runStart, final int runLimit) { + startIndex = runStart; + endIndex = runLimit; } public boolean isEmpty() { @@ -688,8 +694,8 @@ public SegmentInfo() { } - - public void applyFont(Graphics2D g2) { + + public void applyFont(final Graphics2D g2) { if (font != null) { g2.setFont(font); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PComboBox.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PComboBox.java index 5e41e3a..c65433b 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PComboBox.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PComboBox.java @@ -72,6 +72,10 @@ */ public class PComboBox extends JComboBox implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; private PSwing pSwing; private PSwingCanvas canvas; @@ -80,7 +84,7 @@ * * @param model The ComboBoxModel from which the list will be created */ - public PComboBox(ComboBoxModel model) { + public PComboBox(final ComboBoxModel model) { super(model); init(); } @@ -100,7 +104,7 @@ * * @param items The items to populate the PComboBox list */ - public PComboBox(Vector items) { + public PComboBox(final Vector items) { super(items); init(); } @@ -127,7 +131,7 @@ * @param pSwing * @param canvas */ - public void setEnvironment(PSwing pSwing, PSwingCanvas canvas) { + public void setEnvironment(final PSwing pSwing, final PSwingCanvas canvas) { this.pSwing = pSwing; this.canvas = canvas; } @@ -143,7 +147,7 @@ * Create our Popup instead of theirs */ protected ComboPopup createPopup() { - PBasicComboPopup popup = new PBasicComboPopup(comboBox); + final PBasicComboPopup popup = new PBasicComboPopup(comboBox); popup.getAccessibleContext().setAccessibleParent(comboBox); return popup; } @@ -155,9 +159,14 @@ protected class PBasicComboPopup extends BasicComboPopup { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * @param combo The parent ComboBox */ - public PBasicComboPopup(JComboBox combo) { + public PBasicComboPopup(final JComboBox combo) { super(combo); } @@ -172,9 +181,9 @@ * @param ph corresponds to the height of the popup * @return The bounds for the PopupMenu */ - protected Rectangle computePopupBounds(int px, int py, int pw, int ph) { - Rectangle2D r = getNodeBoundsInCanvas(); - Rectangle sup = super.computePopupBounds(px, py, pw, ph); + protected Rectangle computePopupBounds(final int px, final int py, final int pw, final int ph) { + final Rectangle2D r = getNodeBoundsInCanvas(); + final Rectangle sup = super.computePopupBounds(px, py, pw, ph); return new Rectangle((int) r.getX(), (int) r.getMaxY(), (int) sup.getWidth(), (int) sup.getHeight()); } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwing.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwing.java index 8304efd..13c1584 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwing.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwing.java @@ -206,6 +206,10 @@ public class PSwing extends PNode implements Serializable, PropertyChangeListener { /** + * + */ + private static final long serialVersionUID = 1L; + /** * Used as a hashtable key for this object in the Swing component's client * properties. */ @@ -215,7 +219,7 @@ /** * The cutoff at which the Swing component is rendered greek */ - private double renderCutoff = 0.3; + private final double renderCutoff = 0.3; private JComponent component = null; private double minFontSize = Double.MAX_VALUE; private Stroke defaultStroke = new BasicStroke(); @@ -229,12 +233,12 @@ * Keep track of which nodes we've attached listeners to since no built in * support in PNode */ - private ArrayList listeningTo = new ArrayList(); + private final ArrayList listeningTo = new ArrayList(); /* The parent listener for camera/canvas changes */ - private PropertyChangeListener parentListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - PNode parent = (PNode) evt.getNewValue(); + private final PropertyChangeListener parentListener = new PropertyChangeListener() { + public void propertyChange(final PropertyChangeEvent evt) { + final PNode parent = (PNode) evt.getNewValue(); clearListeners((PNode) evt.getOldValue()); if (parent != null) { listenForCanvas(parent); @@ -251,24 +255,24 @@ * * @param component The swing component to be wrapped */ - public PSwing(JComponent component) { + public PSwing(final JComponent component) { this.component = component; component.putClientProperty(PSWING_PROPERTY, this); init(component); component.revalidate(); component.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { reshape(); } }); component.addComponentListener(new ComponentAdapter() { - public void componentHidden(ComponentEvent e) { + public void componentHidden(final ComponentEvent e) { setVisible(false); } - public void componentShown(ComponentEvent e) { + public void componentShown(final ComponentEvent e) { setVisible(true); } }); @@ -285,7 +289,7 @@ * @param component * @deprecated */ - public PSwing(PSwingCanvas pSwingCanvas, JComponent component) { + public PSwing(final PSwingCanvas pSwingCanvas, final JComponent component) { this(component); } @@ -294,16 +298,16 @@ * bounds of this PNode. */ void reshape() { - Border border = component.getBorder(); - - int width = (int) Math.max(component.getMinimumSize().width, component.getPreferredSize().width); - int height = (int) component.getPreferredSize().height; - + final Border border = component.getBorder(); + + int width = Math.max(component.getMinimumSize().width, component.getPreferredSize().width); + final int height = component.getPreferredSize().height; + if (border != null) { - Insets borderInsets = border.getBorderInsets(component); - width += borderInsets.left + borderInsets.right; - } - + final Insets borderInsets = border.getBorderInsets(component); + width += borderInsets.left + borderInsets.right; + } + component.setBounds(0, 0, width, height); setBounds(0, 0, width, height); } @@ -321,8 +325,8 @@ * * @param renderContext Contains information about current render. */ - public void paint(PPaintContext renderContext) { - Graphics2D g2 = renderContext.getGraphics(); + public void paint(final PPaintContext renderContext) { + final Graphics2D g2 = renderContext.getGraphics(); if (defaultStroke == null) { defaultStroke = new BasicStroke(); @@ -340,12 +344,12 @@ component.revalidate(); } - if (component instanceof JLabel) { - JLabel label = (JLabel)component; - enforceNoEllipsis(label.getText(), label.getIcon(), label.getIconTextGap(), g2); - } + if (component instanceof JLabel) { + final JLabel label = (JLabel) component; + enforceNoEllipsis(label.getText(), label.getIcon(), label.getIconTextGap(), g2); + } else if (component instanceof JButton) { - JButton button = (JButton)component; + final JButton button = (JButton) component; enforceNoEllipsis(button.getText(), button.getIcon(), button.getIconTextGap(), g2); } @@ -357,28 +361,28 @@ } } - private void enforceNoEllipsis(String text, Icon icon, int iconGap, Graphics2D g2) { - Rectangle2D textBounds = component.getFontMetrics(component.getFont()).getStringBounds(text, g2); + private void enforceNoEllipsis(final String text, final Icon icon, final int iconGap, final Graphics2D g2) { + final Rectangle2D textBounds = component.getFontMetrics(component.getFont()).getStringBounds(text, g2); double minAcceptableWidth = textBounds.getWidth(); double minAcceptableHeight = textBounds.getHeight(); - - if (icon != null) { + + if (icon != null) { minAcceptableWidth += icon.getIconWidth(); minAcceptableWidth += iconGap; minAcceptableHeight = Math.max(icon.getIconHeight(), minAcceptableHeight); } - - if (component.getMinimumSize().getWidth() < minAcceptableWidth ) { - Dimension newMinimumSize = new Dimension((int)Math.ceil(minAcceptableWidth), (int)Math.ceil(minAcceptableHeight)); + + if (component.getMinimumSize().getWidth() < minAcceptableWidth) { + final Dimension newMinimumSize = new Dimension((int) Math.ceil(minAcceptableWidth), (int) Math + .ceil(minAcceptableHeight)); component.setMinimumSize(newMinimumSize); - reshape(); + reshape(); } } - protected boolean shouldRenderGreek(PPaintContext renderContext) { - return (renderContext.getScale() < renderCutoff + protected boolean shouldRenderGreek(final PPaintContext renderContext) { + return renderContext.getScale() < renderCutoff // && pSwingCanvas.getInteracting() - ) || minFontSize * renderContext.getScale() < 0.5; } @@ -387,10 +391,10 @@ * * @param g2 The graphics used to render the filled rectangle */ - public void paintAsGreek(Graphics2D g2) { - Color background = component.getBackground(); - Color foreground = component.getForeground(); - Rectangle2D rect = getBounds(); + public void paintAsGreek(final Graphics2D g2) { + final Color background = component.getBackground(); + final Color foreground = component.getForeground(); + final Rectangle2D rect = getBounds(); if (background != null) { g2.setColor(background); @@ -408,8 +412,8 @@ * associated with this PSwing. */ public void removeFromSwingWrapper() { - if (canvas != null && Arrays.asList(this.canvas.getSwingWrapper().getComponents()).contains(component)) { - this.canvas.getSwingWrapper().remove(component); + if (canvas != null && Arrays.asList(canvas.getSwingWrapper().getComponents()).contains(component)) { + canvas.getSwingWrapper().remove(component); } } @@ -419,20 +423,20 @@ * * @param g2 graphics context for rendering the JComponent */ - public void paint(Graphics2D g2) { + public void paint(final Graphics2D g2) { if (component.getBounds().isEmpty()) { // The component has not been initialized yet. return; } - PSwingRepaintManager manager = (PSwingRepaintManager) RepaintManager.currentManager(component); + final PSwingRepaintManager manager = (PSwingRepaintManager) RepaintManager.currentManager(component); manager.lockRepaint(component); - RenderingHints oldHints = g2.getRenderingHints(); + final RenderingHints oldHints = g2.getRenderingHints(); g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - + component.paint(g2); g2.setRenderingHints(oldHints); @@ -440,7 +444,7 @@ manager.unlockRepaint(component); } - public void setVisible(boolean visible) { + public void setVisible(final boolean visible) { super.setVisible(visible); component.setVisible(visible); } @@ -451,8 +455,8 @@ * * @param repaintBounds */ - public void repaint(PBounds repaintBounds) { - Shape sh = getTransform().createTransformedShape(repaintBounds); + public void repaint(final PBounds repaintBounds) { + final Shape sh = getTransform().createTransformedShape(repaintBounds); TEMP_REPAINT_BOUNDS2.setRect(sh.getBounds2D()); repaintFrom(TEMP_REPAINT_BOUNDS2, this); } @@ -463,7 +467,7 @@ * copy of these bounds */ public void computeBounds() { - reshape(); + reshape(); } /** @@ -487,13 +491,13 @@ * * @param c The Component to be recursively unDoubleBuffered */ - void init(Component c) { + void init(final Component c) { if (c.getFont() != null) { minFontSize = Math.min(minFontSize, c.getFont().getSize()); } if (c instanceof Container) { - Component[] children = ((Container) c).getComponents(); + final Component[] children = ((Container) c).getComponents(); if (children != null) { for (int j = 0; j < children.length; j++) { init(children[j]); @@ -510,11 +514,11 @@ ((JComponent) c).setDoubleBuffered(false); c.addPropertyChangeListener("font", this); c.addComponentListener(new ComponentAdapter() { - public void componentResized(ComponentEvent e) { + public void componentResized(final ComponentEvent e) { computeBounds(); } - public void componentShown(ComponentEvent e) { + public void componentShown(final ComponentEvent e) { computeBounds(); } }); @@ -524,13 +528,13 @@ /** * Listens for changes in font on components rooted at this PSwing */ - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { if (component.isAncestorOf((Component) evt.getSource()) && ((Component) evt.getSource()).getFont() != null) { minFontSize = Math.min(minFontSize, ((Component) evt.getSource()).getFont().getSize()); } } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); init(component); } @@ -547,26 +551,26 @@ * @param node The child node at which to begin a parent-based traversal for * adding listeners. */ - private void listenForCanvas(PNode node) { + private void listenForCanvas(final PNode node) { // need to get the full tree for this node PNode p = node; while (p != null) { listenToNode(p); - PNode parent = p; + final PNode parent = p; // System.out.println( "parent = " + parent.getClass() ); if (parent instanceof PCamera) { - PCamera cam = (PCamera) parent; + final PCamera cam = (PCamera) parent; if (cam.getComponent() instanceof PSwingCanvas) { updateCanvas((PSwingCanvas) cam.getComponent()); } } else if (parent instanceof PLayer) { - PLayer player = (PLayer) parent; + final PLayer player = (PLayer) parent; // System.out.println( "Found player: with " + // player.getCameraCount() + " cameras" ); for (int i = 0; i < player.getCameraCount(); i++) { - PCamera cam = player.getCamera(i); + final PCamera cam = player.getCamera(i); if (cam.getComponent() instanceof PSwingCanvas) { updateCanvas((PSwingCanvas) cam.getComponent()); break; @@ -583,7 +587,7 @@ * * @param node the node to listen to for parent/pcamera/pcanvas changes */ - private void listenToNode(PNode node) { + private void listenToNode(final PNode node) { // System.out.println( "listeningTo.size() = " + listeningTo.size() ); if (!listeningTo(node)) { listeningTo.add(node); @@ -599,9 +603,9 @@ * @return true if this PSwing is already listening to the specified node * for camera/canvas changes */ - private boolean listeningTo(PNode node) { + private boolean listeningTo(final PNode node) { for (int i = 0; i < listeningTo.size(); i++) { - PNode pNode = (PNode) listeningTo.get(i); + final PNode pNode = (PNode) listeningTo.get(i); if (pNode == node) { return true; } @@ -615,7 +619,7 @@ * * @param fromParent Parent to start with for clearing listeners */ - private void clearListeners(PNode fromParent) { + private void clearListeners(final PNode fromParent) { if (fromParent == null) { return; } @@ -632,7 +636,7 @@ * * @param newCanvas the new PSwingCanvas (may be null) */ - private void updateCanvas(PSwingCanvas newCanvas) { + private void updateCanvas(final PSwingCanvas newCanvas) { if (newCanvas != canvas) { if (canvas != null) { canvas.removePSwing(this); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingCanvas.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingCanvas.java index 3bf8e8f..76064f1 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingCanvas.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingCanvas.java @@ -28,10 +28,12 @@ */ package edu.umd.cs.piccolox.pswing; -import edu.umd.cs.piccolo.PCanvas; +import java.awt.Dimension; -import javax.swing.*; -import java.awt.*; +import javax.swing.JComponent; +import javax.swing.RepaintManager; + +import edu.umd.cs.piccolo.PCanvas; /** * The PSwingCanvas is a PCanvas that can display Swing components with @@ -42,8 +44,12 @@ * @author Lance E. Good */ public class PSwingCanvas extends PCanvas { + /** + * + */ + private static final long serialVersionUID = 1L; public static final String SWING_WRAPPER_KEY = "Swing Wrapper"; - private ChildWrapper swingWrapper; + private final ChildWrapper swingWrapper; /** * Construct a new PSwingCanvas. @@ -56,7 +62,7 @@ } private void initRepaintManager() { - RepaintManager repaintManager = RepaintManager.currentManager(this); + final RepaintManager repaintManager = RepaintManager.currentManager(this); PSwingRepaintManager pSwingRepaintManager; if (repaintManager instanceof PSwingRepaintManager) { pSwingRepaintManager = (PSwingRepaintManager) repaintManager; @@ -71,25 +77,30 @@ return swingWrapper; } - void addPSwing(PSwing pSwing) { + void addPSwing(final PSwing pSwing) { swingWrapper.add(pSwing.getComponent()); } - void removePSwing(PSwing pSwing) { + void removePSwing(final PSwing pSwing) { swingWrapper.remove(pSwing.getComponent()); } /** - * JComponent wrapper for a PSwingCanvas. Used by PSwingRepaintManager. + * JComponent wrapper for a PSwingCanvas. Used by PSwingRepaintManager. */ static class ChildWrapper extends JComponent { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * Create a new JComponent wrapper for the specified PSwingCanvas. */ - public ChildWrapper() { + public ChildWrapper() { setSize(new Dimension(0, 0)); setPreferredSize(new Dimension(0, 0)); putClientProperty(SWING_WRAPPER_KEY, SWING_WRAPPER_KEY); - } + } } } \ No newline at end of file diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingEventHandler.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingEventHandler.java index 10960f8..e401fb0 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingEventHandler.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingEventHandler.java @@ -28,6 +28,17 @@ */ package edu.umd.cs.piccolox.pswing; +import java.awt.Component; +import java.awt.Container; +import java.awt.Point; +import java.awt.event.InputEvent; +import java.awt.event.MouseEvent; +import java.awt.geom.AffineTransform; +import java.awt.geom.NoninvertibleTransformException; +import java.awt.geom.Point2D; + +import javax.swing.SwingUtilities; + import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolo.PLayer; import edu.umd.cs.piccolo.PNode; @@ -35,14 +46,6 @@ import edu.umd.cs.piccolo.event.PInputEventListener; import edu.umd.cs.piccolo.util.PAffineTransformException; -import javax.swing.*; -import java.awt.*; -import java.awt.event.InputEvent; -import java.awt.event.MouseEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.Point2D; - /** * Event handler to send MousePressed, MouseReleased, MouseMoved, MouseClicked, * and MouseDragged events on Swing components within a PCanvas. @@ -66,11 +69,11 @@ private boolean recursing = false;// to avoid accidental recursive handling - private ButtonData leftButtonData = new ButtonData(); - private ButtonData rightButtonData = new ButtonData(); - private ButtonData middleButtonData = new ButtonData(); + private final ButtonData leftButtonData = new ButtonData(); + private final ButtonData rightButtonData = new ButtonData(); + private final ButtonData middleButtonData = new ButtonData(); - private PSwingCanvas canvas; + private final PSwingCanvas canvas; /** * Constructs a new PSwingEventHandler for the given canvas, and a node that @@ -79,7 +82,7 @@ * @param canvas the canvas associated with this PSwingEventHandler. * @param node the node the mouse listeners will be attached to. */ - public PSwingEventHandler(PSwingCanvas canvas, PNode node) { + public PSwingEventHandler(final PSwingCanvas canvas, final PNode node) { this.canvas = canvas; listenNode = node; } @@ -87,7 +90,7 @@ /** * Constructs a new PSwingEventHandler for the given canvas. */ - public PSwingEventHandler(PSwingCanvas canvas) { + public PSwingEventHandler(final PSwingCanvas canvas) { this.canvas = canvas; } @@ -96,7 +99,7 @@ * * @param active */ - void setActive(boolean active) { + void setActive(final boolean active) { if (this.active && !active) { if (listenNode != null) { this.active = false; @@ -126,20 +129,20 @@ * @param y * @return the component at the specified location. */ - private Component findShowingComponentAt(Component c, int x, int y) { + private Component findShowingComponentAt(final Component c, final int x, final int y) { if (!c.contains(x, y)) { return null; } if (c instanceof Container) { - Container contain = ((Container) c); - int ncomponents = contain.getComponentCount(); - Component component[] = contain.getComponents(); + final Container contain = (Container) c; + final int ncomponents = contain.getComponentCount(); + final Component component[] = contain.getComponents(); for (int i = 0; i < ncomponents; i++) { Component comp = component[i]; if (comp != null) { - Point p = comp.getLocation(); + final Point p = comp.getLocation(); if (comp instanceof Container) { comp = findShowingComponentAt(comp, x - (int) p.getX(), y - (int) p.getY()); } @@ -164,21 +167,21 @@ * @param pSwingMouseEvent * @param aEvent */ - void dispatchEvent(PSwingMouseEvent pSwingMouseEvent, PInputEvent aEvent) { + void dispatchEvent(final PSwingMouseEvent pSwingMouseEvent, final PInputEvent aEvent) { Component comp = null; Point2D pt = null; - PNode pickedNode = pSwingMouseEvent.getPath().getPickedNode(); + final PNode pickedNode = pSwingMouseEvent.getPath().getPickedNode(); // The offsets to put the event in the correct context int offX = 0; int offY = 0; - PNode currentNode = pSwingMouseEvent.getCurrentNode(); + final PNode currentNode = pSwingMouseEvent.getCurrentNode(); if (currentNode instanceof PSwing) { - PSwing swing = (PSwing) currentNode; - PNode grabNode = pickedNode; + final PSwing swing = (PSwing) currentNode; + final PNode grabNode = pickedNode; if (grabNode.isDescendentOf(canvas.getRoot())) { pt = new Point2D.Double(pSwingMouseEvent.getX(), pSwingMouseEvent.getY()); @@ -242,13 +245,13 @@ // and mouseMoved events else if ((pSwingMouseEvent.getID() == MouseEvent.MOUSE_PRESSED || pSwingMouseEvent.getID() == MouseEvent.MOUSE_CLICKED || pSwingMouseEvent.getID() == MouseEvent.MOUSE_MOVED) - && (comp != null)) { + && comp != null) { - MouseEvent e_temp = new MouseEvent(comp, pSwingMouseEvent.getID(), pSwingMouseEvent.getWhen(), + final MouseEvent e_temp = new MouseEvent(comp, pSwingMouseEvent.getID(), pSwingMouseEvent.getWhen(), pSwingMouseEvent.getModifiers(), (int) pt.getX() - offX, (int) pt.getY() - offY, pSwingMouseEvent .getClickCount(), pSwingMouseEvent.isPopupTrigger()); - PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); + final PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); dispatchEvent(comp, e2); } @@ -260,9 +263,9 @@ // This shouldn't happen - since we're only getting node events if (comp == null || pSwingMouseEvent.getID() == MouseEvent.MOUSE_EXITED) { - MouseEvent e_temp = createExitEvent(pSwingMouseEvent); + final MouseEvent e_temp = createExitEvent(pSwingMouseEvent); - PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); + final PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); dispatchEvent(prevComponent, e2); prevComponent = null; @@ -282,8 +285,8 @@ else { // This means mouseEntered if (comp != null) { - MouseEvent e_temp = createEnterEvent(comp, pSwingMouseEvent, offX, offY); - PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); + final MouseEvent e_temp = createEnterEvent(comp, pSwingMouseEvent, offX, offY); + final PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); dispatchEvent(comp, e2); } } @@ -313,28 +316,28 @@ } } - private MouseEvent createEnterEvent(Component comp, PSwingMouseEvent e1, int offX, int offY) { + private MouseEvent createEnterEvent(final Component comp, final PSwingMouseEvent e1, final int offX, final int offY) { return new MouseEvent(comp, MouseEvent.MOUSE_ENTERED, e1.getWhen(), 0, (int) prevPoint.getX() - offX, (int) prevPoint.getY() - offY, e1.getClickCount(), e1.isPopupTrigger()); } - private MouseEvent createExitEvent(PSwingMouseEvent e1) { + private MouseEvent createExitEvent(final PSwingMouseEvent e1) { return new MouseEvent(prevComponent, MouseEvent.MOUSE_EXITED, e1.getWhen(), 0, (int) prevPoint.getX() - (int) prevOff.getX(), (int) prevPoint.getY() - (int) prevOff.getY(), e1.getClickCount(), e1 .isPopupTrigger()); } - private void handleButton(PSwingMouseEvent e1, PInputEvent aEvent, ButtonData buttonData) { + private void handleButton(final PSwingMouseEvent e1, final PInputEvent aEvent, final ButtonData buttonData) { Point2D pt; if (buttonData.getPNode().isDescendentOf(canvas.getRoot())) { pt = new Point2D.Double(e1.getX(), e1.getY()); cameraToLocal(e1.getPath().getTopCamera(), pt, buttonData.getPNode()); // todo this probably won't handle viewing through multiple cameras. - MouseEvent e_temp = new MouseEvent(buttonData.getFocusedComponent(), e1.getID(), e1.getWhen(), e1 + final MouseEvent e_temp = new MouseEvent(buttonData.getFocusedComponent(), e1.getID(), e1.getWhen(), e1 .getModifiers(), (int) pt.getX() - buttonData.getOffsetX(), (int) pt.getY() - buttonData.getOffsetY(), e1.getClickCount(), e1.isPopupTrigger()); - PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); + final PSwingMouseEvent e2 = PSwingMouseEvent.createMouseEvent(e_temp.getID(), e_temp, aEvent); dispatchEvent(buttonData.getFocusedComponent(), e2); } else { @@ -357,14 +360,15 @@ }); } - private void cameraToLocal(PCamera topCamera, Point2D pt, PNode node) { + private void cameraToLocal(final PCamera topCamera, final Point2D pt, final PNode node) { AffineTransform inverse; try { - inverse = topCamera.getViewTransform().createInverse(); - } catch (NoninvertibleTransformException e) { + inverse = topCamera.getViewTransform().createInverse(); + } + catch (final NoninvertibleTransformException e) { throw new PAffineTransformException(e, topCamera.getViewTransform()); } - + /* * Only apply the camera's view transform when this node is a descendant * of PLayer @@ -391,12 +395,12 @@ * @param aEvent * @param type */ - public void processEvent(PInputEvent aEvent, int type) { + public void processEvent(final PInputEvent aEvent, final int type) { if (aEvent.isMouseEvent()) { - InputEvent sourceSwingEvent = aEvent.getSourceSwingEvent(); + final InputEvent sourceSwingEvent = aEvent.getSourceSwingEvent(); if (sourceSwingEvent instanceof MouseEvent) { - MouseEvent swingMouseEvent = (MouseEvent) sourceSwingEvent; - PSwingMouseEvent pSwingMouseEvent = PSwingMouseEvent.createMouseEvent(swingMouseEvent.getID(), + final MouseEvent swingMouseEvent = (MouseEvent) sourceSwingEvent; + final PSwingMouseEvent pSwingMouseEvent = PSwingMouseEvent.createMouseEvent(swingMouseEvent.getID(), swingMouseEvent, aEvent); if (!recursing) { recursing = true; @@ -411,7 +415,7 @@ new Exception("PInputEvent.getSourceSwingEvent was not a MouseEvent. Actual event: " + sourceSwingEvent + ", class=" + sourceSwingEvent.getClass().getName()).printStackTrace(); } - } + } } /** @@ -424,7 +428,8 @@ private int focusOffX = 0; private int focusOffY = 0; - public void setState(PSwing swing, PNode visualNode, Component comp, int offX, int offY) { + public void setState(final PSwing swing, final PNode visualNode, final Component comp, final int offX, + final int offY) { focusPSwing = swing; focusComponent = comp; focusNode = visualNode; diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseEvent.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseEvent.java index 560b138..b3ab125 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseEvent.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseEvent.java @@ -28,17 +28,17 @@ */ package edu.umd.cs.piccolox.pswing; -import edu.umd.cs.piccolo.PNode; -import edu.umd.cs.piccolo.event.PInputEvent; -import edu.umd.cs.piccolo.util.PPickPath; - -import java.awt.*; +import java.awt.Component; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Point2D; import java.io.Serializable; +import edu.umd.cs.piccolo.PNode; +import edu.umd.cs.piccolo.event.PInputEvent; +import edu.umd.cs.piccolo.util.PPickPath; + /** * PMouseEvent is an event which indicates that a mouse action occurred * in a node. @@ -75,8 +75,12 @@ * @author Lance E. Good */ public class PSwingMouseEvent extends MouseEvent implements Serializable { - private int id; - private PInputEvent event; + /** + * + */ + private static final long serialVersionUID = 1L; + private final int id; + private final PInputEvent event; /** * Constructs a new PMouse event from a Java MouseEvent. @@ -85,7 +89,7 @@ * MOUSE_ENTERED, MOUSE_EXITED) * @param e The original Java mouse event when in MOUSE_RELEASED events. */ - protected PSwingMouseEvent(int id, MouseEvent e, PInputEvent event) { + protected PSwingMouseEvent(final int id, final MouseEvent e, final PInputEvent event) { super((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), e .getClickCount(), e.isPopupTrigger()); this.id = id; @@ -100,8 +104,8 @@ * @param e The original Java mouse event when in MOUSE_DRAGGED and * MOUSE_RELEASED events. */ - public static PSwingMouseEvent createMouseEvent(int id, MouseEvent e, PInputEvent pEvent) { - if (id == PSwingMouseEvent.MOUSE_MOVED || id == PSwingMouseEvent.MOUSE_DRAGGED) { + public static PSwingMouseEvent createMouseEvent(final int id, final MouseEvent e, final PInputEvent pEvent) { + if (id == MouseEvent.MOUSE_MOVED || id == MouseEvent.MOUSE_DRAGGED) { return new PSwingMouseMotionEvent(id, e, pEvent); } else { @@ -223,23 +227,23 @@ * * @param listener the MouseListener or MouseMotionListener to dispatch to. */ - public void dispatchTo(Object listener) { + public void dispatchTo(final Object listener) { if (listener instanceof MouseListener) { - MouseListener mouseListener = (MouseListener) listener; + final MouseListener mouseListener = (MouseListener) listener; switch (getID()) { - case PSwingMouseEvent.MOUSE_CLICKED: + case MouseEvent.MOUSE_CLICKED: mouseListener.mouseClicked(this); break; - case PSwingMouseEvent.MOUSE_ENTERED: + case MouseEvent.MOUSE_ENTERED: mouseListener.mouseEntered(this); break; - case PSwingMouseEvent.MOUSE_EXITED: + case MouseEvent.MOUSE_EXITED: mouseListener.mouseExited(this); break; - case PSwingMouseEvent.MOUSE_PRESSED: + case MouseEvent.MOUSE_PRESSED: mouseListener.mousePressed(this); break; - case PSwingMouseEvent.MOUSE_RELEASED: + case MouseEvent.MOUSE_RELEASED: mouseListener.mouseReleased(this); break; default: @@ -247,12 +251,12 @@ } } else { - MouseMotionListener mouseMotionListener = (MouseMotionListener) listener; + final MouseMotionListener mouseMotionListener = (MouseMotionListener) listener; switch (getID()) { - case PSwingMouseEvent.MOUSE_DRAGGED: + case MouseEvent.MOUSE_DRAGGED: mouseMotionListener.mouseDragged(this); break; - case PSwingMouseEvent.MOUSE_MOVED: + case MouseEvent.MOUSE_MOVED: mouseMotionListener.mouseMoved(this); break; default: @@ -268,7 +272,7 @@ * * @param aSource */ - public void setSource(Object aSource) { + public void setSource(final Object aSource) { source = aSource; } } \ No newline at end of file diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseMotionEvent.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseMotionEvent.java index 30a54ff..d55f121 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseMotionEvent.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingMouseMotionEvent.java @@ -28,11 +28,11 @@ */ package edu.umd.cs.piccolox.pswing; -import edu.umd.cs.piccolo.event.PInputEvent; - import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; +import edu.umd.cs.piccolo.event.PInputEvent; + /** * PMouseMotionEvent is an event which indicates that a mouse motion * action occurred in a node. @@ -69,12 +69,17 @@ public class PSwingMouseMotionEvent extends PSwingMouseEvent { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * Constructs a new PMouse event from a Java MouseEvent. * * @param id The event type (MOUSE_MOVED, MOUSE_DRAGGED) * @param e The original Java mouse event when in MOUSE_DRAGGED events. */ - protected PSwingMouseMotionEvent(int id, MouseEvent e, PInputEvent event) { + protected PSwingMouseMotionEvent(final int id, final MouseEvent e, final PInputEvent event) { super(id, e, event); } @@ -83,13 +88,13 @@ * * @param listener the target for dispatch. */ - public void dispatchTo(Object listener) { - MouseMotionListener mouseMotionListener = (MouseMotionListener) listener; + public void dispatchTo(final Object listener) { + final MouseMotionListener mouseMotionListener = (MouseMotionListener) listener; switch (getID()) { - case PSwingMouseEvent.MOUSE_DRAGGED: + case MouseEvent.MOUSE_DRAGGED: mouseMotionListener.mouseDragged(this); break; - case PSwingMouseEvent.MOUSE_MOVED: + case MouseEvent.MOUSE_MOVED: mouseMotionListener.mouseMoved(this); break; default: diff --git a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManager.java b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManager.java index a92eaec..50960e5 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManager.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManager.java @@ -75,14 +75,14 @@ // The components that are currently painting // This needs to be a vector for thread safety - private Vector paintingComponents = new Vector(); + private final Vector paintingComponents = new Vector(); /** * Locks repaint for a particular (Swing) component displayed by PCanvas * * @param c The component for which the repaint is to be locked */ - public void lockRepaint(JComponent c) { + public void lockRepaint(final JComponent c) { paintingComponents.addElement(c); } @@ -91,7 +91,7 @@ * * @param c The component for which the repaint is to be unlocked */ - public void unlockRepaint(JComponent c) { + public void unlockRepaint(final JComponent c) { paintingComponents.remove(c); } @@ -102,7 +102,7 @@ * @param c The component for which the repaint status is desired * @return Whether the component is currently painting */ - public boolean isPainting(JComponent c) { + public boolean isPainting(final JComponent c) { return paintingComponents.contains(c); } @@ -119,10 +119,11 @@ * @param width Width of the dirty region in the component * @param height Height of the dirty region in the component */ - public synchronized void addDirtyRegion(JComponent component, int x, int y, final int width, final int height) { + public synchronized void addDirtyRegion(final JComponent component, final int x, final int y, final int width, + final int height) { boolean captureRepaint = false; JComponent childComponent = null; - + int captureX = x; int captureY = y; @@ -140,16 +141,16 @@ else { // Adds to the offset since the component is nested captureX += comp.getLocation().getX(); - captureY += comp.getLocation().getY(); + captureY += comp.getLocation().getY(); } } // Now we check to see if we should capture the repaint and act // accordingly if (captureRepaint) { - if (!isPainting(childComponent)) { - double repaintW = Math.min(childComponent.getWidth() - captureX, width); - double repaintH = Math.min(childComponent.getHeight() - captureY, height); + if (!isPainting(childComponent)) { + final double repaintW = Math.min(childComponent.getWidth() - captureX, width); + final double repaintH = Math.min(childComponent.getHeight() - captureY, height); dispatchRepaint(childComponent, new PBounds(captureX, captureY, repaintW, repaintH)); } @@ -159,7 +160,7 @@ } } - private void dispatchRepaint(JComponent childComponent, final PBounds repaintBounds) { + private void dispatchRepaint(final JComponent childComponent, final PBounds repaintBounds) { final PSwing pSwing = (PSwing) childComponent.getClientProperty(PSwing.PSWING_PROPERTY); SwingUtilities.invokeLater(new Runnable() { @@ -178,7 +179,7 @@ * * @param invalidComponent The Swing component that needs validation */ - public synchronized void addInvalidComponent(JComponent invalidComponent) { + public synchronized void addInvalidComponent(final JComponent invalidComponent) { final JComponent capturedComponent = invalidComponent; if (capturedComponent.getParent() == null @@ -189,7 +190,7 @@ SwingUtilities.invokeLater(new Runnable() { public void run() { capturedComponent.validate(); - PSwing pSwing = (PSwing) capturedComponent.getClientProperty(PSwing.PSWING_PROPERTY); + final PSwing pSwing = (PSwing) capturedComponent.getClientProperty(PSwing.PSWING_PROPERTY); pSwing.reshape(); } }); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/swing/PCacheCanvas.java b/extras/src/main/java/edu/umd/cs/piccolox/swing/PCacheCanvas.java index 6b65928..77eee4b 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/swing/PCacheCanvas.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/swing/PCacheCanvas.java @@ -40,10 +40,15 @@ * @author Lance Good */ public class PCacheCanvas extends PCanvas { + /** + * + */ + private static final long serialVersionUID = 1L; + protected PCamera createDefaultCamera() { - PRoot r = new PRoot(); - PLayer l = new PLayer(); - PCamera c = new PCacheCamera(); + final PRoot r = new PRoot(); + final PLayer l = new PLayer(); + final PCamera c = new PCacheCamera(); r.addChild(c); r.addChild(l); diff --git a/extras/src/main/java/edu/umd/cs/piccolox/swing/PDefaultScrollDirector.java b/extras/src/main/java/edu/umd/cs/piccolox/swing/PDefaultScrollDirector.java index 6281209..912382c 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/swing/PDefaultScrollDirector.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/swing/PDefaultScrollDirector.java @@ -37,7 +37,7 @@ import java.util.Iterator; import java.util.List; -import javax.swing.JScrollPane; +import javax.swing.ScrollPaneConstants; import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolo.PCanvas; @@ -99,14 +99,14 @@ * @param viewPort The viewport on which this director directs * @param view The ZCanvas that the viewport looks at */ - public void install(PViewport viewPort, final PCanvas view) { - this.scrollPane = (PScrollPane) viewPort.getParent(); + public void install(final PViewport viewPort, final PCanvas view) { + scrollPane = (PScrollPane) viewPort.getParent(); this.viewPort = viewPort; this.view = view; if (view != null) { - this.camera = view.getCamera(); - this.root = view.getRoot(); + camera = view.getCamera(); + root = view.getRoot(); } if (camera != null) { @@ -145,14 +145,14 @@ * @param viewBounds The bounds for which the view position will be computed * @return The view position */ - public Point getViewPosition(Rectangle2D viewBounds) { - Point pos = new Point(); + public Point getViewPosition(final Rectangle2D viewBounds) { + final Point pos = new Point(); if (camera != null) { // First we compute the union of all the layers - PBounds layerBounds = new PBounds(); - List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } @@ -175,14 +175,14 @@ * computed * @return The view size */ - public Dimension getViewSize(Rectangle2D viewBounds) { - Dimension size = new Dimension(); + public Dimension getViewSize(final Rectangle2D viewBounds) { + final Dimension size = new Dimension(); if (camera != null) { // First we compute the union of all the layers - PBounds bounds = new PBounds(); - List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds bounds = new PBounds(); + final List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); bounds.add(layer.getFullBoundsReference()); } @@ -205,39 +205,40 @@ * @param x The new x position * @param y The new y position */ - public void setViewPosition(double x, double y) { + public void setViewPosition(final double x, final double y) { // Bail out if scrollInProgress because we can end up with an infinite // loop since the scrollbars depend on the camera location - if (camera == null || scrollInProgress) + if (camera == null || scrollInProgress) { return; + } scrollInProgress = true; // Get the union of all the layers' bounds - PBounds layerBounds = new PBounds(); - List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } - PAffineTransform at = camera.getViewTransform(); + final PAffineTransform at = camera.getViewTransform(); at.transform(layerBounds, layerBounds); // Union the camera bounds - PBounds viewBounds = camera.getBoundsReference(); + final PBounds viewBounds = camera.getBoundsReference(); layerBounds.add(viewBounds); // Now find the new view position in view coordinates - Point2D newPoint = new Point2D.Double(layerBounds.getX() + x, layerBounds.getY() + y); + final Point2D newPoint = new Point2D.Double(layerBounds.getX() + x, layerBounds.getY() + y); // Now transform the new view position into global coords camera.localToView(newPoint); // Compute the new matrix values to put the camera at the // correct location - double newX = -(at.getScaleX() * newPoint.getX() + at.getShearX() * newPoint.getY()); - double newY = -(at.getShearY() * newPoint.getX() + at.getScaleY() * newPoint.getY()); + final double newX = -(at.getScaleX() * newPoint.getX() + at.getShearX() * newPoint.getY()); + final double newY = -(at.getShearY() * newPoint.getX() + at.getScaleY() * newPoint.getY()); at.setTransform(at.getScaleX(), at.getShearY(), at.getShearX(), at.getScaleY(), newX, newY); @@ -250,9 +251,9 @@ * Invoked when the camera's view changes, or the bounds of the root or * camera changes */ - public void propertyChange(PropertyChangeEvent pce) { - boolean isRelevantViewEvent = (PCamera.PROPERTY_VIEW_TRANSFORM == pce.getPropertyName()); - boolean isRelevantBoundsEvent = isBoundsChangedEvent(pce) + public void propertyChange(final PropertyChangeEvent pce) { + final boolean isRelevantViewEvent = PCamera.PROPERTY_VIEW_TRANSFORM == pce.getPropertyName(); + final boolean isRelevantBoundsEvent = isBoundsChangedEvent(pce) && (pce.getSource() == camera || pce.getSource() == view.getRoot()); if (isRelevantViewEvent || isRelevantBoundsEvent) { @@ -265,8 +266,8 @@ } } - private boolean isBoundsChangedEvent(PropertyChangeEvent pce) { - return (PNode.PROPERTY_BOUNDS == pce.getPropertyName() || PNode.PROPERTY_FULL_BOUNDS == pce.getPropertyName()); + private boolean isBoundsChangedEvent(final PropertyChangeEvent pce) { + return PNode.PROPERTY_BOUNDS == pce.getPropertyName() || PNode.PROPERTY_FULL_BOUNDS == pce.getPropertyName(); } /** @@ -278,16 +279,16 @@ */ public boolean shouldRevalidateScrollPane() { if (camera != null) { - if (scrollPane.getHorizontalScrollBarPolicy() != JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED - && scrollPane.getVerticalScrollBarPolicy() != JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) { + if (scrollPane.getHorizontalScrollBarPolicy() != ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED + && scrollPane.getVerticalScrollBarPolicy() != ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) { return false; } // Get the union of all the layers' bounds - PBounds layerBounds = new PBounds(); - List layers = camera.getLayersReference(); - for (Iterator i = layers.iterator(); i.hasNext();) { - PLayer layer = (PLayer) i.next(); + final PBounds layerBounds = new PBounds(); + final List layers = camera.getLayersReference(); + for (final Iterator i = layers.iterator(); i.hasNext();) { + final PLayer layer = (PLayer) i.next(); layerBounds.add(layer.getFullBoundsReference()); } @@ -295,20 +296,20 @@ camera.viewToLocal(layerBounds); // And union with the camera bounds - PBounds cameraBounds = camera.getBoundsReference(); + final PBounds cameraBounds = camera.getBoundsReference(); layerBounds.add(cameraBounds); // Truncate these to ints before comparing since // that's what the ScrollPane uses - int layerWidth = (int) (layerBounds.getWidth() + 0.5); - int layerHeight = (int) (layerBounds.getHeight() + 0.5); - int cameraWidth = (int) (cameraBounds.getWidth() + 0.5); - int cameraHeight = (int) (cameraBounds.getHeight() + 0.5); + final int layerWidth = (int) (layerBounds.getWidth() + 0.5); + final int layerHeight = (int) (layerBounds.getHeight() + 0.5); + final int cameraWidth = (int) (cameraBounds.getWidth() + 0.5); + final int cameraHeight = (int) (cameraBounds.getHeight() + 0.5); - if ((scrollPane.getHorizontalScrollBar().isShowing() && layerWidth <= cameraWidth) - || (!scrollPane.getHorizontalScrollBar().isShowing() && layerWidth > cameraWidth) - || (scrollPane.getVerticalScrollBar().isShowing() && layerHeight <= cameraHeight) - || (!scrollPane.getVerticalScrollBar().isShowing() && layerHeight > cameraHeight)) { + if (scrollPane.getHorizontalScrollBar().isShowing() && layerWidth <= cameraWidth + || !scrollPane.getHorizontalScrollBar().isShowing() && layerWidth > cameraWidth + || scrollPane.getVerticalScrollBar().isShowing() && layerHeight <= cameraHeight + || !scrollPane.getVerticalScrollBar().isShowing() && layerHeight > cameraHeight) { return true; } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollDirector.java b/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollDirector.java index a039a29..cbe8c78 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollDirector.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollDirector.java @@ -28,8 +28,9 @@ */ package edu.umd.cs.piccolox.swing; -import java.awt.*; -import java.awt.geom.*; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.geom.Rectangle2D; import edu.umd.cs.piccolo.PCanvas; diff --git a/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPane.java b/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPane.java index 08786be..d334611 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPane.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPane.java @@ -50,6 +50,11 @@ */ public class PScrollPane extends JScrollPane { + /** + * + */ + private static final long serialVersionUID = 1L; + // A reusable null action protected PNullAction nullAction = null; @@ -59,11 +64,11 @@ /** * Pass on the constructor info to the super */ - public PScrollPane(Component view, int vsbPolicy, int hsbPolicy) { + public PScrollPane(final Component view, final int vsbPolicy, final int hsbPolicy) { super(view, vsbPolicy, hsbPolicy); // Set the layout and sync it with the scroll pane - PScrollPaneLayout layout = new PScrollPaneLayout.UIResource(); + final PScrollPaneLayout layout = new PScrollPaneLayout.UIResource(); setLayout(layout); layout.syncWithScrollPane(this); } @@ -71,14 +76,14 @@ /** * Pass on the constructor info to the super */ - public PScrollPane(Component view) { + public PScrollPane(final Component view) { this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); } /** * Pass on the constructor info to the super */ - public PScrollPane(int vsbPolicy, int hsbPolicy) { + public PScrollPane(final int vsbPolicy, final int hsbPolicy) { this(null, vsbPolicy, hsbPolicy); } @@ -94,13 +99,13 @@ * * @param disable true disables key actions, false enables key actions */ - public void setKeyActionsDisabled(boolean disable) { - if (disable && this.disableKeyActions != disable) { - this.disableKeyActions = disable; + public void setKeyActionsDisabled(final boolean disable) { + if (disable && disableKeyActions != disable) { + disableKeyActions = disable; disableKeyActions(); } - else if (!disable && this.disableKeyActions != disable) { - this.disableKeyActions = disable; + else if (!disable && disableKeyActions != disable) { + disableKeyActions = disable; installCustomKeyActions(); } } @@ -108,7 +113,7 @@ /** * Sets the UI */ - public void setUI(ScrollPaneUI ui) { + public void setUI(final ScrollPaneUI ui) { super.setUI(ui); if (!disableKeyActions) { @@ -124,7 +129,7 @@ * scroll the view */ protected void installCustomKeyActions() { - ActionMap map = getActionMap(); + final ActionMap map = getActionMap(); map.put("scrollUp", new PScrollAction("scrollUp", SwingConstants.VERTICAL, -1, true)); map.put("scrollDown", new PScrollAction("scrollDown", SwingConstants.VERTICAL, 1, true)); @@ -144,7 +149,7 @@ * Disables key actions on this PScrollPane */ protected void disableKeyActions() { - ActionMap map = getActionMap(); + final ActionMap map = getActionMap(); if (nullAction == null) { nullAction = new PNullAction(); @@ -180,34 +185,38 @@ * relevant scrollbar is visible */ protected static class PScrollAction extends AbstractAction { + /** + * + */ + private static final long serialVersionUID = 1L; /** Direction to scroll. */ protected int orientation; /** 1 indicates scroll down, -1 up. */ protected int direction; /** True indicates a block scroll, otherwise a unit scroll. */ - private boolean block; + private final boolean block; - protected PScrollAction(String name, int orientation, int direction, boolean block) { + protected PScrollAction(final String name, final int orientation, final int direction, final boolean block) { super(name); this.orientation = orientation; this.direction = direction; this.block = block; } - public void actionPerformed(ActionEvent e) { - JScrollPane scrollpane = (JScrollPane) e.getSource(); + public void actionPerformed(final ActionEvent e) { + final JScrollPane scrollpane = (JScrollPane) e.getSource(); // LEG: Modification to only perform these actions if the relevant // scrollbar is actually showing - if ((orientation == SwingConstants.VERTICAL && scrollpane.getVerticalScrollBar().isShowing()) - || (orientation == SwingConstants.HORIZONTAL && scrollpane.getHorizontalScrollBar().isShowing())) { + if (orientation == SwingConstants.VERTICAL && scrollpane.getVerticalScrollBar().isShowing() + || orientation == SwingConstants.HORIZONTAL && scrollpane.getHorizontalScrollBar().isShowing()) { - JViewport vp = scrollpane.getViewport(); + final JViewport vp = scrollpane.getViewport(); Component view; if (vp != null && (view = vp.getView()) != null) { - Rectangle visRect = vp.getViewRect(); + final Rectangle visRect = vp.getViewRect(); // LEG: Modification to query the viewport for the // view size rather than going directly to the view - Dimension vSize = vp.getViewSize(); + final Dimension vSize = vp.getViewSize(); int amount; if (view instanceof Scrollable) { @@ -232,8 +241,8 @@ } } if (orientation == SwingConstants.VERTICAL) { - visRect.y += (amount * direction); - if ((visRect.y + visRect.height) > vSize.height) { + visRect.y += amount * direction; + if (visRect.y + visRect.height > vSize.height) { visRect.y = Math.max(0, vSize.height - visRect.height); } else if (visRect.y < 0) { @@ -241,8 +250,8 @@ } } else { - visRect.x += (amount * direction); - if ((visRect.x + visRect.width) > vSize.width) { + visRect.x += amount * direction; + if (visRect.x + visRect.width > vSize.width) { visRect.x = Math.max(0, vSize.width - visRect.width); } else if (visRect.x < 0) { @@ -262,16 +271,21 @@ * Only performs the event if a scrollbar is visible */ private static class PScrollHomeAction extends AbstractAction { - protected PScrollHomeAction(String name) { + /** + * + */ + private static final long serialVersionUID = 1L; + + protected PScrollHomeAction(final String name) { super(name); } - public void actionPerformed(ActionEvent e) { - JScrollPane scrollpane = (JScrollPane) e.getSource(); + public void actionPerformed(final ActionEvent e) { + final JScrollPane scrollpane = (JScrollPane) e.getSource(); // LEG: Modification to only perform these actions if one of the // scrollbars is actually showing if (scrollpane.getVerticalScrollBar().isShowing() || scrollpane.getHorizontalScrollBar().isShowing()) { - JViewport vp = scrollpane.getViewport(); + final JViewport vp = scrollpane.getViewport(); if (vp != null && vp.getView() != null) { vp.setViewPosition(new Point(0, 0)); } @@ -287,23 +301,28 @@ * also only performs the event if a scrollbar is visible */ protected static class PScrollEndAction extends AbstractAction { - protected PScrollEndAction(String name) { + /** + * + */ + private static final long serialVersionUID = 1L; + + protected PScrollEndAction(final String name) { super(name); } - public void actionPerformed(ActionEvent e) { - JScrollPane scrollpane = (JScrollPane) e.getSource(); + public void actionPerformed(final ActionEvent e) { + final JScrollPane scrollpane = (JScrollPane) e.getSource(); // LEG: Modification to only perform these actions if one of the // scrollbars is actually showing if (scrollpane.getVerticalScrollBar().isShowing() || scrollpane.getHorizontalScrollBar().isShowing()) { - JViewport vp = scrollpane.getViewport(); + final JViewport vp = scrollpane.getViewport(); if (vp != null && vp.getView() != null) { - Rectangle visRect = vp.getViewRect(); + final Rectangle visRect = vp.getViewRect(); // LEG: Modification to query the viewport for the // view size rather than going directly to the view - Dimension size = vp.getViewSize(); + final Dimension size = vp.getViewSize(); vp.setViewPosition(new Point(size.width - visRect.width, size.height - visRect.height)); } } @@ -315,7 +334,12 @@ * to its parent */ protected static class PNullAction extends AbstractAction { - public void actionPerformed(ActionEvent e) { + /** + * + */ + private static final long serialVersionUID = 1L; + + public void actionPerformed(final ActionEvent e) { } } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPaneLayout.java b/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPaneLayout.java index 21127fd..ee936c8 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPaneLayout.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/swing/PScrollPaneLayout.java @@ -49,6 +49,11 @@ public class PScrollPaneLayout extends ScrollPaneLayout { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * MODIFIED FROM javax.swing.ScrollPaneLayout.layoutContainer * * This is largely the same as ScrollPaneLayout.layoutContainer but obtains @@ -57,18 +62,18 @@ * * @param parent the Container to lay out */ - public void layoutContainer(Container parent) { + public void layoutContainer(final Container parent) { /* * Sync the (now obsolete) policy fields with the JScrollPane. */ - JScrollPane scrollPane = (JScrollPane) parent; + final JScrollPane scrollPane = (JScrollPane) parent; vsbPolicy = scrollPane.getVerticalScrollBarPolicy(); hsbPolicy = scrollPane.getHorizontalScrollBarPolicy(); - Rectangle availR = scrollPane.getBounds(); + final Rectangle availR = scrollPane.getBounds(); availR.x = availR.y = 0; - Insets insets = parent.getInsets(); + final Insets insets = parent.getInsets(); availR.x = insets.left; availR.y = insets.top; availR.width -= insets.left + insets.right; @@ -77,17 +82,17 @@ /* * Get the scrollPane's orientation. */ - boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight(); + final boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight(); /* * If there's a visible column header remove the space it needs from the * top of availR. The column header is treated as if it were fixed * height, arbitrary width. */ - Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0); + final Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0); - if ((colHead != null) && (colHead.isVisible())) { - int colHeadHeight = colHead.getPreferredSize().height; + if (colHead != null && colHead.isVisible()) { + final int colHeadHeight = colHead.getPreferredSize().height; colHeadR.height = colHeadHeight; availR.y += colHeadHeight; availR.height -= colHeadHeight; @@ -98,10 +103,10 @@ * left or right of availR. The row header is treated as if it were * fixed width, arbitrary height. */ - Rectangle rowHeadR = new Rectangle(0, 0, 0, 0); + final Rectangle rowHeadR = new Rectangle(0, 0, 0, 0); - if ((rowHead != null) && (rowHead.isVisible())) { - int rowHeadWidth = rowHead.getPreferredSize().width; + if (rowHead != null && rowHead.isVisible()) { + final int rowHeadWidth = rowHead.getPreferredSize().width; rowHeadR.width = rowHeadWidth; availR.width -= rowHeadWidth; if (leftToRight) { @@ -117,7 +122,7 @@ * If there's a JScrollPane.viewportBorder, remove the space it occupies * for availR. */ - Border viewportBorder = scrollPane.getViewportBorder(); + final Border viewportBorder = scrollPane.getViewportBorder(); Insets vpbInsets; if (viewportBorder != null) { vpbInsets = viewportBorder.getBorderInsets(parent); @@ -145,21 +150,21 @@ * And we assume that the viewports layout manager will give the view * it's preferred size. */ - Dimension extentSize = (viewport != null) ? viewport.toViewCoordinates(availR.getSize()) : new Dimension(0, 0); + Dimension extentSize = viewport != null ? viewport.toViewCoordinates(availR.getSize()) : new Dimension(0, 0); - PBounds cameraBounds = new PBounds(0, 0, extentSize.getWidth(), extentSize.getHeight()); + final PBounds cameraBounds = new PBounds(0, 0, extentSize.getWidth(), extentSize.getHeight()); // LEG: Modification to ask the viewport for the view size rather // than asking the view directly - Dimension viewPrefSize = (viewport != null) ? ((PViewport) viewport).getViewSize(cameraBounds) : new Dimension( - 0, 0); + Dimension viewPrefSize = viewport != null ? ((PViewport) viewport).getViewSize(cameraBounds) : new Dimension(0, + 0); /* * If there's a vertical scrollbar and we need one, allocate space for * it (we'll make it visible later). A vertical scrollbar is considered * to be fixed width, arbitrary height. */ - Rectangle vsbR = new Rectangle(0, availR.y - vpbInsets.top, 0, 0); + final Rectangle vsbR = new Rectangle(0, availR.y - vpbInsets.top, 0, 0); boolean vsbNeeded; if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) { @@ -170,10 +175,10 @@ } else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED - vsbNeeded = (viewPrefSize.height > extentSize.height); + vsbNeeded = viewPrefSize.height > extentSize.height; } - if ((vsb != null) && vsbNeeded) { + if (vsb != null && vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates(availR.getSize()); @@ -188,7 +193,7 @@ * it (we'll make it visible later). A horizontal scrollbar is * considered to be fixed height, arbitrary width. */ - Rectangle hsbR = new Rectangle(availR.x - vpbInsets.left, 0, 0, 0); + final Rectangle hsbR = new Rectangle(availR.x - vpbInsets.left, 0, 0, 0); boolean hsbNeeded; if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) { hsbNeeded = true; @@ -197,10 +202,10 @@ hsbNeeded = false; } else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED - hsbNeeded = (viewPrefSize.width > extentSize.width); + hsbNeeded = viewPrefSize.width > extentSize.width; } - if ((hsb != null) && hsbNeeded) { + if (hsb != null && hsbNeeded) { adjustForHSB(true, availR, hsbR, vpbInsets); /* @@ -210,7 +215,7 @@ * hasn't been done so already. Ofcourse we don't bother with any of * this if the vsbPolicy is NEVER. */ - if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { + if (vsb != null && !vsbNeeded && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { extentSize = viewport.toViewCoordinates(availR.getSize()); @@ -307,9 +312,9 @@ * This method is called from ScrollPaneLayout.layoutContainer and is * private in ScrollPaneLayout so it was copied here */ - protected void adjustForVSB(boolean wantsVSB, Rectangle available, Rectangle vsbR, Insets vpbInsets, - boolean leftToRight) { - int vsbWidth = vsb.getPreferredSize().width; + protected void adjustForVSB(final boolean wantsVSB, final Rectangle available, final Rectangle vsbR, + final Insets vpbInsets, final boolean leftToRight) { + final int vsbWidth = vsb.getPreferredSize().width; if (wantsVSB) { available.width -= vsbWidth; vsbR.width = vsbWidth; @@ -333,8 +338,9 @@ * This method is called from ScrollPaneLayout.layoutContainer and is * private in ScrollPaneLayout so it was copied here */ - protected void adjustForHSB(boolean wantsHSB, Rectangle available, Rectangle hsbR, Insets vpbInsets) { - int hsbHeight = hsb.getPreferredSize().height; + protected void adjustForHSB(final boolean wantsHSB, final Rectangle available, final Rectangle hsbR, + final Insets vpbInsets) { + final int hsbHeight = hsb.getPreferredSize().height; if (wantsHSB) { available.height -= hsbHeight; hsbR.y = available.y + available.height + vpbInsets.bottom; @@ -350,5 +356,10 @@ * does this in ScrollPaneLayout but we'll do it here too just to be safe. */ public static class UIResource extends PScrollPaneLayout implements javax.swing.plaf.UIResource { + + /** + * + */ + private static final long serialVersionUID = 1L; } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/swing/PViewport.java b/extras/src/main/java/edu/umd/cs/piccolox/swing/PViewport.java index 08d3901..f54fff7 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/swing/PViewport.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/swing/PViewport.java @@ -28,9 +28,16 @@ */ package edu.umd.cs.piccolox.swing; -import java.awt.*; -import java.awt.geom.*; -import javax.swing.*; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.LayoutManager; +import java.awt.Point; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; + +import javax.swing.JViewport; +import javax.swing.ViewportLayout; import edu.umd.cs.piccolo.PCanvas; import edu.umd.cs.piccolo.util.PBounds; @@ -44,6 +51,10 @@ public class PViewport extends JViewport { /** + * + */ + private static final long serialVersionUID = 1L; + /** * Controls what happens when scrolling occurs */ PScrollDirector scrollDirector; @@ -83,7 +94,7 @@ * * @param scrollDirector The new scroll director */ - public void setScrollDirector(PScrollDirector scrollDirector) { + public void setScrollDirector(final PScrollDirector scrollDirector) { if (this.scrollDirector != null) { this.scrollDirector.unInstall(); } @@ -105,7 +116,7 @@ * * @param view The new view - it better be a ZCanvas! */ - public void setView(Component view) { + public void setView(final Component view) { if (!(view instanceof PCanvas)) { throw new UnsupportedOperationException("PViewport only supports ZCanvas"); } @@ -123,14 +134,15 @@ * * @param p a Point object giving the upper left coordinates */ - public void setViewPosition(Point p) { + public void setViewPosition(final Point p) { if (getView() == null) { return; } - double oldX = 0, oldY = 0, x = p.x, y = p.y; + double oldX = 0, oldY = 0; + final double x = p.x, y = p.y; - Point2D vp = getViewPosition(); + final Point2D vp = getViewPosition(); if (vp != null) { oldX = vp.getX(); oldY = vp.getY(); @@ -140,10 +152,10 @@ * Send the scroll director the exact view position and let it interpret * it as needed */ - double newX = x; - double newY = y; + final double newX = x; + final double newY = y; - if ((oldX != newX) || (oldY != newY)) { + if (oldX != newX || oldY != newY) { scrollUnderway = true; scrollDirector.setViewPosition(newX, newY); @@ -160,7 +172,7 @@ */ public Point getViewPosition() { if (scrollDirector != null) { - Dimension extent = getExtentSize(); + final Dimension extent = getExtentSize(); return scrollDirector.getViewPosition(new PBounds(0, 0, extent.getWidth(), extent.getHeight())); } else { @@ -175,7 +187,7 @@ * @return The new view size */ public Dimension getViewSize() { - Dimension extent = getExtentSize(); + final Dimension extent = getExtentSize(); return scrollDirector.getViewSize(new PBounds(0, 0, extent.getWidth(), extent.getHeight())); } @@ -186,7 +198,7 @@ * @param r The extent size from which the view is computed * @return The new view size */ - public Dimension getViewSize(Rectangle2D r) { + public Dimension getViewSize(final Rectangle2D r) { return scrollDirector.getViewSize(r); } @@ -203,19 +215,24 @@ */ public static class PViewportLayout extends ViewportLayout { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * Called when the specified container needs to be laid out. * * @param parent the container to lay out */ - public void layoutContainer(Container parent) { - JViewport vp = (JViewport) parent; - Component view = vp.getView(); + public void layoutContainer(final Container parent) { + final JViewport vp = (JViewport) parent; + final Component view = vp.getView(); if (view == null) { return; } - Dimension extentSize = vp.getSize(); + final Dimension extentSize = vp.getSize(); vp.setViewSize(extentSize); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/util/LineShape.java b/extras/src/main/java/edu/umd/cs/piccolox/util/LineShape.java index 77c2890..73a5488 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/util/LineShape.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/util/LineShape.java @@ -38,9 +38,9 @@ public class LineShape implements Shape, MutablePoints { private MutablePoints points; - private Rectangle2D bounds = new Rectangle2D.Double(); + private final Rectangle2D bounds = new Rectangle2D.Double(); - public LineShape(MutablePoints points) { + public LineShape(final MutablePoints points) { setPoints(points); } @@ -57,19 +57,19 @@ return points.getPointCount(); } - public double getX(int i) { + public double getX(final int i) { return points.getX(i); } - public double getY(int i) { + public double getY(final int i) { return points.getY(i); } - public Point2D getPoint(int i, Point2D dst) { + public Point2D getPoint(final int i, final Point2D dst) { return points.getPoint(i, dst); } - public Rectangle2D getBounds(Rectangle2D dst) { + public Rectangle2D getBounds(final Rectangle2D dst) { points.getBounds(dst); return dst; } @@ -81,23 +81,23 @@ points.getBounds(bounds); } - public void setPoint(int i, double x, double y) { + public void setPoint(final int i, final double x, final double y) { points.setPoint(i, x, y); updateBounds(); } - public void addPoint(int pos, double x, double y) { + public void addPoint(final int pos, final double x, final double y) { points.addPoint(pos, x, y); updateBounds(); } - public void removePoints(int pos, int num) { + public void removePoints(final int pos, final int num) { points.removePoints(pos, num); updateBounds(); } - public void transformPoints(AffineTransform trans) { - XYArray newPoints = new XYArray(points.getPointCount()); + public void transformPoints(final AffineTransform trans) { + final XYArray newPoints = new XYArray(points.getPointCount()); newPoints.appendPoints(points); newPoints.transformPoints(trans); points = newPoints; @@ -114,16 +114,16 @@ return bounds; } - public static boolean contains(double x, double y, double x1, double y1, double x2, double y2, boolean min, - boolean max, double d) { + public static boolean contains(final double x, final double y, final double x1, final double y1, final double x2, + final double y2, final boolean min, final boolean max, final double d) { double dx = x2 - x1, dy = y2 - y1; - double dx2 = dx * dx, dy2 = dy * dy; + final double dx2 = dx * dx, dy2 = dy * dy; double p; if (dx != 0) { - p = (((x - x1) / dx) + ((dy * (y - y1)) / dx2)) / (1 + (dy2 / dx2)); + p = ((x - x1) / dx + dy * (y - y1) / dx2) / (1 + dy2 / dx2); } else if (dy != 0) { - p = (((y - y1) / dy) + ((dx * (x - x1)) / dy2)) / (1 + (dx2 / dy2)); + p = ((y - y1) / dy + dx * (x - x1) / dy2) / (1 + dx2 / dy2); } else { return false; @@ -134,13 +134,13 @@ else if (min && p < 0.0) { return false; } - dx = (p * dx) + x1 - x; - dy = (p * dy) + y1 - y; - double len = dx * dx + dy * dy; - return (len < d); + dx = p * dx + x1 - x; + dy = p * dy + y1 - y; + final double len = dx * dx + dy * dy; + return len < d; } - public boolean contains(double x, double y, double d) { + public boolean contains(final double x, final double y, final double d) { double x1, y1, x2, y2; if (points.getPointCount() == 0) { return false; @@ -159,46 +159,47 @@ return false; } - public boolean contains(double x, double y) { + public boolean contains(final double x, final double y) { return contains(x, y, 2.0d); } - public boolean contains(Point2D p) { + public boolean contains(final Point2D p) { return contains(p.getX(), p.getY()); } - public static boolean intersects(double x1, double y1, double x2, double y2, double x3, double y3, double x4, - double y4, boolean min1, boolean max1, boolean min2, boolean max2) { - double dx1 = x2 - x1, dy1 = y2 - y1, dx2 = x4 - x3, dy2 = y4 - y3; + public static boolean intersects(final double x1, final double y1, final double x2, final double y2, + final double x3, final double y3, final double x4, final double y4, final boolean min1, final boolean max1, + final boolean min2, final boolean max2) { + final double dx1 = x2 - x1, dy1 = y2 - y1, dx2 = x4 - x3, dy2 = y4 - y3; double d, p2, p1; if (dy1 != 0.0) { d = dx1 / dy1; - p2 = (x3 - x1 + (d * (y1 - y3))) / ((d * dy2) - dx2); + p2 = (x3 - x1 + d * (y1 - y3)) / (d * dy2 - dx2); p1 = (dy2 * p2 + y3 - y1) / dy1; } else if (dy2 != 0.0) { d = dx2 / dy2; - p1 = (x1 - x3 + (d * (y3 - y1))) / ((d * dy1) - dx1); + p1 = (x1 - x3 + d * (y3 - y1)) / (d * dy1 - dx1); p2 = (dy1 * p1 + y1 - y3) / dy2; } else if (dx1 != 0.0) { d = dy1 / dx1; - p2 = (y3 - y1 + (d * (x1 - x3))) / ((d * dx2) - dy2); + p2 = (y3 - y1 + d * (x1 - x3)) / (d * dx2 - dy2); p1 = (dx2 * p2 + x3 - x1) / dx1; } else if (dx2 != 0.0) { d = dy2 / dx2; - p1 = (y1 - y3 + (d * (x3 - x1))) / ((d * dx1) - dy1); + p1 = (y1 - y3 + d * (x3 - x1)) / (d * dx1 - dy1); p2 = (dx1 * p1 + x1 - x3) / dx2; } else { return false; } - return (((!min1) || (p1 >= 0.0)) && ((!max1) || (p1 <= 1.0)) && ((!min2) || (p2 >= 0.0)) && ((!max2) || (p2 <= 1.0))); + return (!min1 || p1 >= 0.0) && (!max1 || p1 <= 1.0) && (!min2 || p2 >= 0.0) && (!max2 || p2 <= 1.0); } - public boolean intersects(double x, double y, double w, double h) { + public boolean intersects(final double x, final double y, final double w, final double h) { double x1, y1, x2, y2; if (points.getPointCount() == 0) { return false; @@ -220,15 +221,15 @@ return false; } - public boolean intersects(Rectangle2D r) { + public boolean intersects(final Rectangle2D r) { return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } - public boolean contains(double x, double y, double w, double h) { + public boolean contains(final double x, final double y, final double w, final double h) { return contains(x, y) && contains(x + w, y) && contains(x, y + h) && contains(x + w, y + h); } - public boolean contains(Rectangle2D r) { + public boolean contains(final Rectangle2D r) { return contains(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } @@ -236,21 +237,21 @@ // - public PathIterator getPathIterator(AffineTransform at) { + public PathIterator getPathIterator(final AffineTransform at) { return new LinePathIterator(points, at); } - public PathIterator getPathIterator(AffineTransform at, double flatness) { + public PathIterator getPathIterator(final AffineTransform at, final double flatness) { return new LinePathIterator(points, at); } private static class LinePathIterator implements PathIterator { - private Points points; - private AffineTransform trans; + private final Points points; + private final AffineTransform trans; private int i = 0; - public LinePathIterator(Points points, AffineTransform trans) { + public LinePathIterator(final Points points, final AffineTransform trans) { this.points = points; this.trans = trans; } @@ -267,7 +268,7 @@ i++; } - private Point2D tempPoint = new Point2D.Double(); + private final Point2D tempPoint = new Point2D.Double(); private void currentSegment() { tempPoint.setLocation(points.getX(i), points.getY(i)); @@ -276,18 +277,18 @@ } } - public int currentSegment(float[] coords) { + public int currentSegment(final float[] coords) { currentSegment(); coords[0] = (float) tempPoint.getX(); coords[1] = (float) tempPoint.getY(); - return (i == 0 ? PathIterator.SEG_MOVETO : PathIterator.SEG_LINETO); + return i == 0 ? PathIterator.SEG_MOVETO : PathIterator.SEG_LINETO; } - public int currentSegment(double[] coords) { + public int currentSegment(final double[] coords) { currentSegment(); coords[0] = tempPoint.getX(); coords[1] = tempPoint.getY(); - return (i == 0 ? PathIterator.SEG_MOVETO : PathIterator.SEG_LINETO); + return i == 0 ? PathIterator.SEG_MOVETO : PathIterator.SEG_LINETO; } } } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/util/PBoundsLocator.java b/extras/src/main/java/edu/umd/cs/piccolox/util/PBoundsLocator.java index e1b03e1..7b5bd45 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/util/PBoundsLocator.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/util/PBoundsLocator.java @@ -44,41 +44,45 @@ */ public class PBoundsLocator extends PNodeLocator { + /** + * + */ + private static final long serialVersionUID = 1L; private int side; - public static PBoundsLocator createEastLocator(PNode node) { + public static PBoundsLocator createEastLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.EAST); } - public static PBoundsLocator createNorthEastLocator(PNode node) { + public static PBoundsLocator createNorthEastLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.NORTH_EAST); } - public static PBoundsLocator createNorthWestLocator(PNode node) { + public static PBoundsLocator createNorthWestLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.NORTH_WEST); } - public static PBoundsLocator createNorthLocator(PNode node) { + public static PBoundsLocator createNorthLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.NORTH); } - public static PBoundsLocator createSouthLocator(PNode node) { + public static PBoundsLocator createSouthLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.SOUTH); } - public static PBoundsLocator createWestLocator(PNode node) { + public static PBoundsLocator createWestLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.WEST); } - public static PBoundsLocator createSouthWestLocator(PNode node) { + public static PBoundsLocator createSouthWestLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.SOUTH_WEST); } - public static PBoundsLocator createSouthEastLocator(PNode node) { + public static PBoundsLocator createSouthEastLocator(final PNode node) { return new PBoundsLocator(node, SwingConstants.SOUTH_EAST); } - public PBoundsLocator(PNode node, int aSide) { + public PBoundsLocator(final PNode node, final int aSide) { super(node); side = aSide; } @@ -87,12 +91,12 @@ return side; } - public void setSide(int side) { + public void setSide(final int side) { this.side = side; } public double locateX() { - Rectangle2D aBounds = node.getBoundsReference(); + final Rectangle2D aBounds = node.getBoundsReference(); switch (side) { case SwingConstants.NORTH_WEST: @@ -107,18 +111,18 @@ case SwingConstants.NORTH: case SwingConstants.SOUTH: - return aBounds.getX() + (aBounds.getWidth() / 2); + return aBounds.getX() + aBounds.getWidth() / 2; } return -1; } public double locateY() { - Rectangle2D aBounds = node.getBoundsReference(); + final Rectangle2D aBounds = node.getBoundsReference(); switch (side) { case SwingConstants.EAST: case SwingConstants.WEST: - return aBounds.getY() + (aBounds.getHeight() / 2); + return aBounds.getY() + aBounds.getHeight() / 2; case SwingConstants.SOUTH: case SwingConstants.SOUTH_WEST: diff --git a/extras/src/main/java/edu/umd/cs/piccolox/util/PLocator.java b/extras/src/main/java/edu/umd/cs/piccolox/util/PLocator.java index b690c71..636a665 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/util/PLocator.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/util/PLocator.java @@ -42,6 +42,11 @@ */ public abstract class PLocator implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + public PLocator() { } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/util/PNodeLocator.java b/extras/src/main/java/edu/umd/cs/piccolox/util/PNodeLocator.java index cc65040..fdfbd7f 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/util/PNodeLocator.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/util/PNodeLocator.java @@ -45,9 +45,13 @@ */ public class PNodeLocator extends PLocator { + /** + * + */ + private static final long serialVersionUID = 1L; protected PNode node; - public PNodeLocator(PNode node) { + public PNodeLocator(final PNode node) { setNode(node); } @@ -55,7 +59,7 @@ return node; } - public void setNode(PNode node) { + public void setNode(final PNode node) { this.node = node; } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/util/POcclusionDetection.java b/extras/src/main/java/edu/umd/cs/piccolox/util/POcclusionDetection.java index c0da03a..4ce89af 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/util/POcclusionDetection.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/util/POcclusionDetection.java @@ -45,17 +45,17 @@ * nodes. Note that this is only detecting a subset of occlusions (parent, * child), others such as overlapping siblings or cousins are not detected. */ - public void detectOccusions(PNode n, PBounds parentBounds) { + public void detectOccusions(final PNode n, final PBounds parentBounds) { detectOcclusions(n, new PPickPath(null, parentBounds)); } - public void detectOcclusions(PNode n, PPickPath pickPath) { + public void detectOcclusions(final PNode n, final PPickPath pickPath) { if (n.fullIntersects(pickPath.getPickBounds())) { pickPath.pushTransform(n.getTransformReference(false)); - int count = n.getChildrenCount(); + final int count = n.getChildrenCount(); for (int i = count - 1; i >= 0; i--) { - PNode each = (PNode) n.getChild(i); + final PNode each = n.getChild(i); if (n.getOccluded()) { // if n has been occuded by a previous decendent then // this child must also be occuded @@ -71,7 +71,7 @@ if (!n.getOccluded()) { if (n.intersects(pickPath.getPickBounds())) { if (n.isOpaque(pickPath.getPickBounds())) { - PNode p = n.getParent(); + final PNode p = n.getParent(); while (p != null && !p.getOccluded()) { p.setOccluded(true); } diff --git a/extras/src/main/java/edu/umd/cs/piccolox/util/XYArray.java b/extras/src/main/java/edu/umd/cs/piccolox/util/XYArray.java index 2f403ed..b1e7f57 100644 --- a/extras/src/main/java/edu/umd/cs/piccolox/util/XYArray.java +++ b/extras/src/main/java/edu/umd/cs/piccolox/util/XYArray.java @@ -41,11 +41,11 @@ private int numPoints = 0; - public XYArray(double[] points) { + public XYArray(final double[] points) { initPoints(points, points.length / 2); } - public XYArray(int n) { + public XYArray(final int n) { initPoints(null, n); } @@ -53,58 +53,57 @@ this(0); } - public int getPointCount() { return numPoints; } // normalize an index, negative counts from end - private int normalize(int i) { + private int normalize(final int i) { if (i >= numPoints) { throw new IllegalArgumentException("The point index " + i + " is not below " + numPoints); } - return (i < 0) ? numPoints + i : i; + return i < 0 ? numPoints + i : i; } - public double getX(int i) { + public double getX(final int i) { return points[normalize(i) * 2]; } - public double getY(int i) { + public double getY(final int i) { return points[normalize(i) * 2 + 1]; } - public Point2D getPoint(int i, Point2D dst) { - int pointIndex = normalize(i); + public Point2D getPoint(final int i, final Point2D dst) { + final int pointIndex = normalize(i); dst.setLocation(points[pointIndex * 2], points[pointIndex * 2 + 1]); return dst; } - public void setX(int i, double x) { + public void setX(final int i, final double x) { points[normalize(i) * 2] = x; } - public void setY(int i, double y) { + public void setY(final int i, final double y) { points[normalize(i) * 2 + 1] = y; } - public void setPoint(int i, double x, double y) { - int pointIndex = normalize(i); + public void setPoint(final int i, final double x, final double y) { + final int pointIndex = normalize(i); points[pointIndex * 2] = x; points[pointIndex * 2 + 1] = y; } - public void setPoint(int i, Point2D pt) { + public void setPoint(final int i, final Point2D pt) { setPoint(i, pt.getX(), pt.getY()); } - public void transformPoints(AffineTransform t) { + public void transformPoints(final AffineTransform t) { t.transform(points, 0, points, 0, numPoints); } - public Rectangle2D getBounds(Rectangle2D dst) { + public Rectangle2D getBounds(final Rectangle2D dst) { int i = 0; if (dst.isEmpty() && getPointCount() > 0) { dst.setRect(getX(i), getY(i), 1.0d, 1.0d); @@ -117,33 +116,33 @@ return dst; } - public static double[] initPoints(double[] points, int n, double[] old) { + public static double[] initPoints(double[] points, final int n, final double[] old) { if (points == null || n * 2 > points.length) { points = new double[n * 2]; } if (old != null && points != old) { System.arraycopy(old, 0, points, 0, Math.min(old.length, n * 2)); } - return (points); + return points; } - private void initPoints(double[] points, int n) { + private void initPoints(final double[] points, final int n) { this.points = initPoints(points, n, this.points); - numPoints = (points != null ? points.length / 2 : 0); + numPoints = points != null ? points.length / 2 : 0; } - public void addPoints(int pos, Points pts, int start, int end) { + public void addPoints(final int pos, final Points pts, int start, int end) { if (end < 0) { end = pts.getPointCount() + end + 1; } - int n = numPoints + end - start; + final int n = numPoints + end - start; points = initPoints(points, n, points); - int pos1 = pos * 2; - int pos2 = (pos + end - start) * 2; - int len = (numPoints - pos) * 2; - + final int pos1 = pos * 2; + final int pos2 = (pos + end - start) * 2; + final int len = (numPoints - pos) * 2; + System.arraycopy(points, pos1, points, pos2, len); - + numPoints = n; if (pts != null) { for (int count = 0; start < end; count++, start++) { @@ -152,33 +151,34 @@ } } - public void addPoints(int pos, Points pts) { + public void addPoints(final int pos, final Points pts) { addPoints(pos, pts, 0, pts.getPointCount()); } - public void appendPoints(Points pts) { + public void appendPoints(final Points pts) { addPoints(numPoints, pts); } - public static XYArray copyPoints(Points pts) { - XYArray newList = new XYArray(pts.getPointCount()); + public static XYArray copyPoints(final Points pts) { + final XYArray newList = new XYArray(pts.getPointCount()); newList.appendPoints(pts); return newList; } - - public void addPoint(int pos, double x, double y) { + + public void addPoint(final int pos, final double x, final double y) { addPoints(pos, null, 0, 1); setPoint(pos, x, y); } - public void addPoint(int pos, Point2D pt) { + public void addPoint(final int pos, final Point2D pt) { addPoint(pos, pt.getX(), pt.getY()); } - public void removePoints(int pos, int num) { + public void removePoints(final int pos, int num) { num = Math.min(num, numPoints - pos); - if (num <= 0) + if (num <= 0) { return; + } System.arraycopy(points, (pos + num) * 2, points, pos * 2, (numPoints - (pos + num)) * 2); numPoints -= num; } @@ -186,18 +186,18 @@ public void removeAllPoints() { removePoints(0, numPoints); } - + public Object clone() { XYArray ps = null; - + try { - ps = (XYArray) (super.clone()); + ps = (XYArray) super.clone(); ps.points = initPoints(ps.points, numPoints, points); ps.numPoints = numPoints; } - catch (CloneNotSupportedException e) { + catch (final CloneNotSupportedException e) { } - return (ps); + return ps; } } diff --git a/extras/src/test/java/edu/umd/cs/piccolox/POffscreenCanvasTest.java b/extras/src/test/java/edu/umd/cs/piccolox/POffscreenCanvasTest.java index 4e06937..10d2694 100755 --- a/extras/src/test/java/edu/umd/cs/piccolox/POffscreenCanvasTest.java +++ b/extras/src/test/java/edu/umd/cs/piccolox/POffscreenCanvasTest.java @@ -31,61 +31,58 @@ import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics2D; - import java.awt.image.BufferedImage; +import junit.framework.TestCase; import edu.umd.cs.piccolo.PCamera; - import edu.umd.cs.piccolo.nodes.PPath; import edu.umd.cs.piccolo.util.PPaintContext; -import junit.framework.TestCase; - /** * Unit test for POffscreenCanvas. */ public class POffscreenCanvasTest extends TestCase { public void testConstructor() { - POffscreenCanvas canvas0 = new POffscreenCanvas(100, 100); + final POffscreenCanvas canvas0 = new POffscreenCanvas(100, 100); assertNotNull(canvas0); - POffscreenCanvas canvas1 = new POffscreenCanvas(0, 0); + final POffscreenCanvas canvas1 = new POffscreenCanvas(0, 0); assertNotNull(canvas1); - POffscreenCanvas canvas2 = new POffscreenCanvas(0, 100); + final POffscreenCanvas canvas2 = new POffscreenCanvas(0, 100); assertNotNull(canvas2); - POffscreenCanvas canvas3 = new POffscreenCanvas(100, 0); + final POffscreenCanvas canvas3 = new POffscreenCanvas(100, 0); assertNotNull(canvas3); try { new POffscreenCanvas(-1, 100); fail("ctr(-1, 100) expected IllegalArgumentException"); } - catch (IllegalArgumentException e) { + catch (final IllegalArgumentException e) { // expected } try { new POffscreenCanvas(100, -1); fail("ctr(100, -1) expected IllegalArgumentException"); } - catch (IllegalArgumentException e) { + catch (final IllegalArgumentException e) { // expected } try { new POffscreenCanvas(-1, -1); fail("ctr(-1, -1) expected IllegalArgumentException"); } - catch (IllegalArgumentException e) { + catch (final IllegalArgumentException e) { // expected } } public void testCamera() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); assertNotNull(canvas); - PCamera camera = canvas.getCamera(); + final PCamera camera = canvas.getCamera(); assertNotNull(camera); assertEquals(canvas, camera.getComponent()); - PCamera camera1 = new PCamera(); + final PCamera camera1 = new PCamera(); canvas.setCamera(camera1); assertEquals(camera1, canvas.getCamera()); assertEquals(null, camera.getComponent()); @@ -96,33 +93,29 @@ } public void testRenderEmpty() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); - BufferedImage image = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = image.createGraphics(); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final BufferedImage image = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB); + final Graphics2D graphics = image.createGraphics(); canvas.render(graphics); - for (int x = 0; x < 100; x++) - { - for (int y = 0; y < 200; y++) - { + for (int x = 0; x < 100; x++) { + for (int y = 0; y < 200; y++) { assertEquals(0, image.getRGB(x, y)); } } } public void testRenderFull() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); - PPath rect = PPath.createRectangle(0.0f, 0.0f, 200.0f, 300.0f); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final PPath rect = PPath.createRectangle(0.0f, 0.0f, 200.0f, 300.0f); rect.setPaint(new Color(255, 0, 0)); rect.setStroke(null); rect.offset(-100.0d, -100.0d); canvas.getCamera().getLayer(0).addChild(rect); - BufferedImage image = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = image.createGraphics(); + final BufferedImage image = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB); + final Graphics2D graphics = image.createGraphics(); canvas.render(graphics); - for (int x = 0; x < 100; x++) - { - for (int y = 0; y < 200; y++) - { + for (int x = 0; x < 100; x++) { + for (int y = 0; y < 200; y++) { // red pixel, RGBA is 255, 0, 0, 255 assertEquals(-65536, image.getRGB(x, y)); } @@ -131,17 +124,17 @@ public void testRenderNull() { try { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); canvas.render(null); fail("render(null) expected IllegalArgumentException"); } - catch (IllegalArgumentException e) { + catch (final IllegalArgumentException e) { // expected } } public void testRenderQuality() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); assertEquals(POffscreenCanvas.DEFAULT_RENDER_QUALITY, canvas.getRenderQuality()); canvas.setRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING); assertEquals(PPaintContext.HIGH_QUALITY_RENDERING, canvas.getRenderQuality()); @@ -151,29 +144,29 @@ try { canvas.setRenderQuality(-1); } - catch (IllegalArgumentException e) { + catch (final IllegalArgumentException e) { // expected } } public void testPaintImmediately() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); canvas.paintImmediately(); } public void testPopCursor() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); canvas.popCursor(); } public void testPushCursor() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); canvas.pushCursor(null); canvas.pushCursor(Cursor.getDefaultCursor()); } public void testInteracting() { - POffscreenCanvas canvas = new POffscreenCanvas(100, 200); + final POffscreenCanvas canvas = new POffscreenCanvas(100, 200); canvas.setInteracting(true); canvas.setInteracting(false); } diff --git a/extras/src/test/java/edu/umd/cs/piccolox/event/PNotificationCenterTest.java b/extras/src/test/java/edu/umd/cs/piccolox/event/PNotificationCenterTest.java index ba82906..695a6b1 100644 --- a/extras/src/test/java/edu/umd/cs/piccolox/event/PNotificationCenterTest.java +++ b/extras/src/test/java/edu/umd/cs/piccolox/event/PNotificationCenterTest.java @@ -37,12 +37,12 @@ boolean changed3; boolean changed4; - public PNotificationCenterTest(String name) { + public PNotificationCenterTest(final String name) { super(name); } public void testToString() throws SecurityException, NoSuchMethodException { - PNotificationCenter center = PNotificationCenter.defaultCenter(); + final PNotificationCenter center = PNotificationCenter.defaultCenter(); center.addListener(this, "changed1", "propertyChanged", this); center.addListener(this, "changed2", null, this); @@ -66,19 +66,19 @@ changed1 = changed2 = changed3 = changed4 = false; } - public void changed1(PNotification notification) { + public void changed1(final PNotification notification) { changed1 = true; } - public void changed2(PNotification notification) { + public void changed2(final PNotification notification) { changed2 = true; } - public void changed3(PNotification notification) { + public void changed3(final PNotification notification) { changed3 = true; } - public void changed4(PNotification notification) { + public void changed4(final PNotification notification) { changed4 = true; } } diff --git a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PComboBoxTest.java b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PComboBoxTest.java index c1b1de9..74b3dd2 100644 --- a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PComboBoxTest.java +++ b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PComboBoxTest.java @@ -8,44 +8,45 @@ public class PComboBoxTest extends TestCase { public void testPComboInstallsItsOwnUI() { - PComboBox combo = new PComboBox(); + final PComboBox combo = new PComboBox(); assertTrue(combo.getUI() instanceof PComboBox.PBasicComboBoxUI); } public void testConstructsWithVector() { - Vector items = new Vector(); + final Vector items = new Vector(); items.add("A"); items.add("B"); - PComboBox combo = new PComboBox(items); + final PComboBox combo = new PComboBox(items); assertEquals(2, combo.getModel().getSize()); } public void testConstructsWithArray() { - String[] items = new String[] { "A", "B" }; - PComboBox combo = new PComboBox(items); + final String[] items = new String[] { "A", "B" }; + final PComboBox combo = new PComboBox(items); assertEquals(2, combo.getModel().getSize()); } - + public void testConstructsWithComboBoxModel() { - DefaultComboBoxModel model = new DefaultComboBoxModel(); + final DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement("A"); - model.addElement("B"); - PComboBox combo = new PComboBox(model); + model.addElement("B"); + final PComboBox combo = new PComboBox(model); assertEquals(2, combo.getModel().getSize()); } - + public void testSetEnvironmentPersists() { - PComboBox combo = new PComboBox(); - - PSwingCanvas canvas = new PSwingCanvas(); - PSwing pCombo = new PSwing(combo); + final PComboBox combo = new PComboBox(); + + final PSwingCanvas canvas = new PSwingCanvas(); + final PSwing pCombo = new PSwing(combo); combo.setEnvironment(pCombo, canvas); - + assertEquals(pCombo, combo.getPSwing()); assertEquals(canvas, combo.getCanvas()); } - + public void testPopupIsRepositioned() { - // Need a way of dispatching mock events to canvas before this can be tested + // Need a way of dispatching mock events to canvas before this can be + // tested } } diff --git a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingCanvasTest.java b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingCanvasTest.java index 306be8d..14e7b40 100644 --- a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingCanvasTest.java +++ b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingCanvasTest.java @@ -39,13 +39,18 @@ protected int finalizerCallCount; public void setUp() { - finalizerCallCount = 0; + finalizerCallCount = 0; } - + public void testMemoryLeak() throws InterruptedException { JPanel panel = new JPanel(); for (int i = 0; i < 10; i++) { PSwingCanvas canvas = new PSwingCanvas() { + /** + * + */ + private static final long serialVersionUID = 1L; + public void finalize() { finalizerCallCount++; } @@ -56,11 +61,12 @@ } panel = null; System.gc(); - System.runFinalization(); + System.runFinalization(); // Not sure why I need -1 here, but I do. If I create 10000 it'll always // be 1 less - //TODO: make this work in all environments. Will not work at the command line for some. - //assertEquals(10 - 1, finalizerCallCount); + // TODO: make this work in all environments. Will not work at the + // command line for some. + // assertEquals(10 - 1, finalizerCallCount); } } diff --git a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManagerTest.java b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManagerTest.java index f96070b..d5087f8 100644 --- a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManagerTest.java +++ b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingRepaintManagerTest.java @@ -43,29 +43,30 @@ public class PSwingRepaintManagerTest extends TestCase { public void testConstructor() { - PSwingRepaintManager repaintManager = new PSwingRepaintManager(); + final PSwingRepaintManager repaintManager = new PSwingRepaintManager(); assertNotNull(repaintManager); } public void testCurrentManager() { RepaintManager currentManager = RepaintManager.currentManager(null); assertNotNull(currentManager); - // TODO: this assertion is true when running this test case in isolation - // but since PSwingCanvas may have been instantiated elsewhere in the test suite - // may not be true when running this test case as part of a test suite - //assertFalse(currentManager instanceof PSwingRepaintManager); + // TODO: this assertion is true when running this test case in isolation + // but since PSwingCanvas may have been instantiated elsewhere in the + // test suite + // may not be true when running this test case as part of a test suite + // assertFalse(currentManager instanceof PSwingRepaintManager); - Component awtComponent = new Canvas(); + final Component awtComponent = new Canvas(); currentManager = RepaintManager.currentManager(awtComponent); assertNotNull(currentManager); - //assertFalse(currentManager instanceof PSwingRepaintManager); + // assertFalse(currentManager instanceof PSwingRepaintManager); - JComponent swingComponent = new JPanel(); + final JComponent swingComponent = new JPanel(); currentManager = RepaintManager.currentManager(swingComponent); assertNotNull(currentManager); - //assertFalse(currentManager instanceof PSwingRepaintManager); + // assertFalse(currentManager instanceof PSwingRepaintManager); - PSwingCanvas pswingCanvas = new PSwingCanvas(); + final PSwingCanvas pswingCanvas = new PSwingCanvas(); currentManager = RepaintManager.currentManager(pswingCanvas); assertNotNull(currentManager); assertTrue(currentManager instanceof PSwingRepaintManager); @@ -83,50 +84,50 @@ } public void testLockRepaint() { - PSwingCanvas canvas = new PSwingCanvas(); - RepaintManager currentManager = RepaintManager.currentManager(canvas); + final PSwingCanvas canvas = new PSwingCanvas(); + final RepaintManager currentManager = RepaintManager.currentManager(canvas); assertNotNull(currentManager); assertTrue(currentManager instanceof PSwingRepaintManager); - PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; - // TODO: should lockRepaint allow null? + final PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; + // TODO: should lockRepaint allow null? repaintManager.lockRepaint(null); repaintManager.lockRepaint(canvas); } public void testUnlockRepaint() { - PSwingCanvas canvas = new PSwingCanvas(); - RepaintManager currentManager = RepaintManager.currentManager(canvas); + final PSwingCanvas canvas = new PSwingCanvas(); + final RepaintManager currentManager = RepaintManager.currentManager(canvas); assertNotNull(currentManager); assertTrue(currentManager instanceof PSwingRepaintManager); - PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; + final PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; repaintManager.lockRepaint(null); repaintManager.lockRepaint(canvas); repaintManager.unlockRepaint(null); repaintManager.unlockRepaint(canvas); - // TODO: catch this array index out of bounds exception? - JComponent notLocked = new JPanel(); + // TODO: catch this array index out of bounds exception? + final JComponent notLocked = new JPanel(); try { repaintManager.unlockRepaint(notLocked); } - catch (ArrayIndexOutOfBoundsException e) { + catch (final ArrayIndexOutOfBoundsException e) { // expected } } public void testIsPainting() { - PSwingCanvas canvas = new PSwingCanvas(); - RepaintManager currentManager = RepaintManager.currentManager(canvas); + final PSwingCanvas canvas = new PSwingCanvas(); + final RepaintManager currentManager = RepaintManager.currentManager(canvas); assertNotNull(currentManager); assertTrue(currentManager instanceof PSwingRepaintManager); - PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; + final PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; repaintManager.lockRepaint(null); repaintManager.lockRepaint(canvas); - JComponent notLocked = new JPanel(); + final JComponent notLocked = new JPanel(); assertTrue(repaintManager.isPainting(null)); assertTrue(repaintManager.isPainting(canvas)); @@ -134,44 +135,44 @@ } public void testAddDirtyRegion() { - PSwingCanvas canvas = new PSwingCanvas(); - RepaintManager currentManager = RepaintManager.currentManager(canvas); + final PSwingCanvas canvas = new PSwingCanvas(); + final RepaintManager currentManager = RepaintManager.currentManager(canvas); assertNotNull(currentManager); assertTrue(currentManager instanceof PSwingRepaintManager); - PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; + final PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; repaintManager.addDirtyRegion(canvas, 0, 0, canvas.getWidth(), canvas.getHeight()); - JComponent child = new JPanel(); + final JComponent child = new JPanel(); canvas.add(child); repaintManager.addDirtyRegion(child, 0, 0, child.getWidth(), child.getHeight()); - // TODO: will need some additional work here for full test coverage + // TODO: will need some additional work here for full test coverage } public void testAddInvalidComponent() { - PSwingCanvas canvas = new PSwingCanvas(); - RepaintManager currentManager = RepaintManager.currentManager(canvas); + final PSwingCanvas canvas = new PSwingCanvas(); + final RepaintManager currentManager = RepaintManager.currentManager(canvas); assertNotNull(currentManager); assertTrue(currentManager instanceof PSwingRepaintManager); - PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; - // TODO: should check for null and throw IAE, or keep NPE? + final PSwingRepaintManager repaintManager = (PSwingRepaintManager) currentManager; + // TODO: should check for null and throw IAE, or keep NPE? try { repaintManager.addInvalidComponent(null); } - catch (NullPointerException e) { + catch (final NullPointerException e) { // expected } - JComponent component = new JPanel(); - JComponent child = new JPanel(); + final JComponent component = new JPanel(); + final JComponent child = new JPanel(); canvas.add(child); repaintManager.addInvalidComponent(canvas); repaintManager.addInvalidComponent(component); repaintManager.addInvalidComponent(child); - // TODO: will need some additional work here for full test coverage + // TODO: will need some additional work here for full test coverage } } diff --git a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingTest.java b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingTest.java index 6449e55..d8a3cac 100644 --- a/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingTest.java +++ b/extras/src/test/java/edu/umd/cs/piccolox/pswing/PSwingTest.java @@ -45,7 +45,7 @@ * * @author Stephen Chin */ -public class PSwingTest extends TestCase { +public class PSwingTest extends TestCase { public void setUp() { RepaintManager.setCurrentManager(new PSwingRepaintManager()); } @@ -53,29 +53,35 @@ public void testConstructorFailsOnNullComponent() { try { new PSwing(null); - } catch (NullPointerException e) { + } + catch (final NullPointerException e) { // expected } } public void testPSwingRegistersItselfWithComponent() { - JPanel panel = new JPanel(); - PSwing pSwing = new PSwing(panel); + final JPanel panel = new JPanel(); + final PSwing pSwing = new PSwing(panel); assertEquals(pSwing, panel.getClientProperty(PSwing.PSWING_PROPERTY)); } public void testGetComponentReturnsValidComponent() { - JPanel panel = new JPanel(); - PSwing pSwing = new PSwing(panel); + final JPanel panel = new JPanel(); + final PSwing pSwing = new PSwing(panel); assertEquals(panel, pSwing.getComponent()); } public void testPSwingResizesItselfWhenComponentIsResized() { final boolean[] reshaped = new boolean[1]; - JPanel panel = new JPanel(); + final JPanel panel = new JPanel(); new PSwing(panel) { + /** + * + */ + private static final long serialVersionUID = 1L; + protected void reshape() { super.reshape(); @@ -87,37 +93,36 @@ } public void testPSwingDelegatesPaintingToItsComponent() throws IOException { - JPanel panel = new JPanel(); - PSwing pSwing = new PSwing(panel); + final JPanel panel = new JPanel(); + final PSwing pSwing = new PSwing(panel); panel.setBackground(Color.RED); panel.setPreferredSize(new Dimension(100, 100)); - BufferedImage img = new BufferedImage(100, 100, - BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = GraphicsEnvironment.getLocalGraphicsEnvironment() - .createGraphics(img); + final BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + final Graphics2D graphics = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img); pSwing.paint(graphics); assertEquals(Color.RED.getRGB(), img.getRGB(50, 50)); } - - public void testHidingComponentHidesPSwing() throws InterruptedException { - JPanel panel = new JPanel(); - PSwing pSwing = new PSwing(panel); + + public void testHidingComponentHidesPSwing() throws InterruptedException { + final JPanel panel = new JPanel(); + final PSwing pSwing = new PSwing(panel); panel.setPreferredSize(new Dimension(100, 100)); pSwing.setBounds(0, 0, 00, 100); panel.setVisible(false); - - // Wow, do I hate this next line. Turns out that the event dispatch - // thread needs time to push the component hidden method before this test passes + + // Wow, do I hate this next line. Turns out that the event dispatch + // thread needs time to push the component hidden method before this + // test passes // There has to be a way of forcing this without a sleep Thread.sleep(50); assertFalse(pSwing.getVisible()); } - + public void testHidingPNodeHidesComponent() { - JPanel panel = new JPanel(); - PSwing pSwing = new PSwing(panel); + final JPanel panel = new JPanel(); + final PSwing pSwing = new PSwing(panel); pSwing.setVisible(false); assertFalse(panel.isVisible()); } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTBoundsHandle.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTBoundsHandle.java index a399a29..f677741 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTBoundsHandle.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTBoundsHandle.java @@ -57,9 +57,13 @@ */ public class PSWTBoundsHandle extends PSWTHandle { + /** + * + */ + private static final long serialVersionUID = 1L; private PBasicInputEventHandler handleCursorHandler; - public static void addBoundsHandlesTo(PNode aNode) { + public static void addBoundsHandlesTo(final PNode aNode) { aNode.addChild(new PSWTBoundsHandle(PBoundsLocator.createEastLocator(aNode))); aNode.addChild(new PSWTBoundsHandle(PBoundsLocator.createWestLocator(aNode))); aNode.addChild(new PSWTBoundsHandle(PBoundsLocator.createNorthLocator(aNode))); @@ -70,7 +74,7 @@ aNode.addChild(new PSWTBoundsHandle(PBoundsLocator.createSouthWestLocator(aNode))); } - public static void addStickyBoundsHandlesTo(PNode aNode, PCamera camera) { + public static void addStickyBoundsHandlesTo(final PNode aNode, final PCamera camera) { camera.addChild(new PSWTBoundsHandle(PBoundsLocator.createEastLocator(aNode))); camera.addChild(new PSWTBoundsHandle(PBoundsLocator.createWestLocator(aNode))); camera.addChild(new PSWTBoundsHandle(PBoundsLocator.createNorthLocator(aNode))); @@ -81,12 +85,12 @@ camera.addChild(new PSWTBoundsHandle(PBoundsLocator.createSouthWestLocator(aNode))); } - public static void removeBoundsHandlesFrom(PNode aNode) { - ArrayList handles = new ArrayList(); + public static void removeBoundsHandlesFrom(final PNode aNode) { + final ArrayList handles = new ArrayList(); - Iterator i = aNode.getChildrenIterator(); + final Iterator i = aNode.getChildrenIterator(); while (i.hasNext()) { - PNode each = (PNode) i.next(); + final PNode each = (PNode) i.next(); if (each instanceof PSWTBoundsHandle) { handles.add(each); } @@ -94,7 +98,7 @@ aNode.removeChildren(handles); } - public PSWTBoundsHandle(PBoundsLocator aLocator) { + public PSWTBoundsHandle(final PBoundsLocator aLocator) { super(aLocator); } @@ -103,15 +107,15 @@ handleCursorHandler = new PBasicInputEventHandler() { boolean cursorPushed = false; - public void mouseEntered(PInputEvent aEvent) { + public void mouseEntered(final PInputEvent aEvent) { if (!cursorPushed) { aEvent.pushCursor(getCursorFor(((PBoundsLocator) getLocator()).getSide())); cursorPushed = true; } } - public void mouseExited(PInputEvent aEvent) { - PPickPath focus = aEvent.getInputManager().getMouseFocus(); + public void mouseExited(final PInputEvent aEvent) { + final PPickPath focus = aEvent.getInputManager().getMouseFocus(); if (cursorPushed) { if (focus == null || focus.getPickedNode() != PSWTBoundsHandle.this) { aEvent.popCursor(); @@ -120,7 +124,7 @@ } } - public void mouseReleased(PInputEvent event) { + public void mouseReleased(final PInputEvent event) { if (cursorPushed) { event.popCursor(); cursorPushed = false; @@ -138,18 +142,18 @@ return handleCursorHandler; } - public void startHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void startHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); l.getNode().startResizeBounds(); } - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); - PNode n = l.getNode(); - PBounds b = n.getBounds(); + final PNode n = l.getNode(); + final PBounds b = n.getBounds(); - PNode parent = getParent(); + final PNode parent = getParent(); if (parent != n && parent instanceof PCamera) { ((PCamera) parent).localToView(aLocalDimension); } @@ -157,8 +161,8 @@ localToGlobal(aLocalDimension); n.globalToLocal(aLocalDimension); - double dx = aLocalDimension.getWidth(); - double dy = aLocalDimension.getHeight(); + final double dx = aLocalDimension.getWidth(); + final double dy = aLocalDimension.getHeight(); switch (l.getSide()) { case SwingConstants.NORTH: @@ -216,23 +220,23 @@ n.setBounds(b); } - public void endHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void endHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); l.getNode().endResizeBounds(); } - public void flipSiblingBoundsHandles(boolean flipX, boolean flipY) { - Iterator i = getParent().getChildrenIterator(); + public void flipSiblingBoundsHandles(final boolean flipX, final boolean flipY) { + final Iterator i = getParent().getChildrenIterator(); while (i.hasNext()) { - Object each = i.next(); + final Object each = i.next(); if (each instanceof PSWTBoundsHandle) { ((PSWTBoundsHandle) each).flipHandleIfNeeded(flipX, flipY); } } } - public void flipHandleIfNeeded(boolean flipX, boolean flipY) { - PBoundsLocator l = (PBoundsLocator) getLocator(); + public void flipHandleIfNeeded(final boolean flipX, final boolean flipY) { + final PBoundsLocator l = (PBoundsLocator) getLocator(); if (flipX || flipY) { switch (l.getSide()) { @@ -323,7 +327,7 @@ setLocator(l); } - public Cursor getCursorFor(int side) { + public Cursor getCursorFor(final int side) { switch (side) { case SwingConstants.NORTH: return new Cursor(Cursor.N_RESIZE_CURSOR); diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTCanvas.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTCanvas.java index 3136669..313bf41 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTCanvas.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTCanvas.java @@ -79,14 +79,14 @@ private boolean doubleBuffered = true; private PCamera camera; - private PStack cursorStack; + private final PStack cursorStack; private Cursor curCursor; private int interacting; private int defaultRenderQuality; private int animatingRenderQuality; private int interactingRenderQuality; - private PPanEventHandler panEventHandler; - private PZoomEventHandler zoomEventHandler; + private final PPanEventHandler panEventHandler; + private final PZoomEventHandler zoomEventHandler; private boolean paintingImmediately; private boolean animatingOnLastPaint; @@ -95,7 +95,7 @@ * camera, and layer. Event handlers for zooming and panning are * automatically installed. */ - public PSWTCanvas(Composite parent, int style) { + public PSWTCanvas(final Composite parent, final int style) { super(parent, style | SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE); CURRENT_CANVAS = this; @@ -112,7 +112,7 @@ // Add a paint listener to call paint addPaintListener(new PaintListener() { - public void paintControl(PaintEvent pe) { + public void paintControl(final PaintEvent pe) { paintComponent(pe.gc, pe.x, pe.y, pe.width, pe.height); } }); @@ -121,7 +121,7 @@ // Colors SWTGraphics2D.incrementGCCount(); addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent de) { + public void widgetDisposed(final DisposeEvent de) { getRoot().getActivityScheduler().removeAllActivities(); SWTGraphics2D.decrementGCCount(); } @@ -164,7 +164,7 @@ * canvas go through this camera. And this is the camera that paints this * canvas. */ - public void setCamera(PCamera newCamera) { + public void setCamera(final PCamera newCamera) { if (camera != null) { camera.setComponent(null); } @@ -174,7 +174,7 @@ if (camera != null) { camera.setComponent(this); - Rectangle swtRect = getBounds(); + final Rectangle swtRect = getBounds(); camera.setBounds(new Rectangle2D.Double(swtRect.x, swtRect.y, swtRect.width, swtRect.height)); } @@ -197,21 +197,21 @@ /** * Add an input listener to the camera associated with this canvas. */ - public void addInputEventListener(PInputEventListener listener) { + public void addInputEventListener(final PInputEventListener listener) { getCamera().addInputEventListener(listener); } /** * Remove an input listener to the camera associated with this canvas. */ - public void removeInputEventListener(PInputEventListener listener) { + public void removeInputEventListener(final PInputEventListener listener) { getCamera().removeInputEventListener(listener); } public PCamera createBasicSceneGraph() { - PRoot r = new PSWTRoot(this); - PLayer l = new PLayer(); - PCamera c = new PCamera(); + final PRoot r = new PSWTRoot(this); + final PLayer l = new PLayer(); + final PCamera c = new PCamera(); r.addChild(c); r.addChild(l); @@ -246,7 +246,7 @@ * Set if this canvas is interacting. If so the canvas will normally render * at a lower quality that is faster. */ - public void setInteracting(boolean isInteracting) { + public void setInteracting(final boolean isInteracting) { if (isInteracting) { interacting++; } @@ -271,8 +271,8 @@ * Set whether this canvas should use double buffering - the default is no * double buffering */ - public void setDoubleBuffered(boolean dBuffered) { - this.doubleBuffered = dBuffered; + public void setDoubleBuffered(final boolean dBuffered) { + doubleBuffered = dBuffered; } /** @@ -282,7 +282,7 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setDefaultRenderQuality(int requestedQuality) { + public void setDefaultRenderQuality(final int requestedQuality) { defaultRenderQuality = requestedQuality; repaint(); } @@ -295,7 +295,7 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setAnimatingRenderQuality(int requestedQuality) { + public void setAnimatingRenderQuality(final int requestedQuality) { animatingRenderQuality = requestedQuality; repaint(); } @@ -308,7 +308,7 @@ * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ - public void setInteractingRenderQuality(int requestedQuality) { + public void setInteractingRenderQuality(final int requestedQuality) { interactingRenderQuality = requestedQuality; repaint(); } @@ -317,46 +317,46 @@ * Set the canvas cursor, and remember the previous cursor on the cursor * stack. */ - public void pushCursor(java.awt.Cursor cursor) { + public void pushCursor(final java.awt.Cursor cursor) { Cursor aCursor = null; if (cursor.getType() == java.awt.Cursor.N_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZEN); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZEN); } else if (cursor.getType() == java.awt.Cursor.NE_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZENE); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZENE); } else if (cursor.getType() == java.awt.Cursor.NW_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZENW); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZENW); } else if (cursor.getType() == java.awt.Cursor.S_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZES); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZES); } else if (cursor.getType() == java.awt.Cursor.SE_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZESE); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZESE); } else if (cursor.getType() == java.awt.Cursor.SW_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZESW); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZESW); } else if (cursor.getType() == java.awt.Cursor.E_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZEE); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZEE); } else if (cursor.getType() == java.awt.Cursor.W_RESIZE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZEW); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZEW); } else if (cursor.getType() == java.awt.Cursor.TEXT_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_IBEAM); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_IBEAM); } else if (cursor.getType() == java.awt.Cursor.HAND_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_HAND); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_HAND); } else if (cursor.getType() == java.awt.Cursor.MOVE_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_SIZEALL); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_SIZEALL); } else if (cursor.getType() == java.awt.Cursor.CROSSHAIR_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_CROSS); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_CROSS); } else if (cursor.getType() == java.awt.Cursor.WAIT_CURSOR) { - aCursor = new Cursor(this.getDisplay(), SWT.CURSOR_WAIT); + aCursor = new Cursor(getDisplay(), SWT.CURSOR_WAIT); } if (aCursor != null) { @@ -404,8 +404,8 @@ * those events to piccolo. */ protected void installInputSources() { - this.addMouseListener(new MouseListener() { - public void mouseDown(MouseEvent me) { + addMouseListener(new MouseListener() { + public void mouseDown(final MouseEvent me) { boolean shouldBalanceEvent = false; switch (me.button) { @@ -430,17 +430,17 @@ } if (shouldBalanceEvent) { - java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, + final java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, java.awt.event.MouseEvent.MOUSE_RELEASED, 1); sendInputEventToInputManager(balanceEvent, java.awt.event.MouseEvent.MOUSE_RELEASED); } - java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, + final java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, java.awt.event.MouseEvent.MOUSE_PRESSED, 1); sendInputEventToInputManager(balanceEvent, java.awt.event.MouseEvent.MOUSE_PRESSED); } - public void mouseUp(MouseEvent me) { + public void mouseUp(final MouseEvent me) { boolean shouldBalanceEvent = false; switch (me.button) { @@ -465,12 +465,12 @@ } if (shouldBalanceEvent) { - java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, + final java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, java.awt.event.MouseEvent.MOUSE_PRESSED, 1); sendInputEventToInputManager(balanceEvent, java.awt.event.MouseEvent.MOUSE_PRESSED); } - java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, + final java.awt.event.MouseEvent balanceEvent = new PSWTMouseEvent(me, java.awt.event.MouseEvent.MOUSE_RELEASED, 1); sendInputEventToInputManager(balanceEvent, java.awt.event.MouseEvent.MOUSE_RELEASED); } @@ -487,40 +487,40 @@ } }); - this.addMouseMoveListener(new MouseMoveListener() { - public void mouseMove(MouseEvent me) { + addMouseMoveListener(new MouseMoveListener() { + public void mouseMove(final MouseEvent me) { if (isButton1Pressed || isButton2Pressed || isButton3Pressed) { - java.awt.event.MouseEvent inputEvent = new PSWTMouseEvent(me, + final java.awt.event.MouseEvent inputEvent = new PSWTMouseEvent(me, java.awt.event.MouseEvent.MOUSE_DRAGGED, 1); sendInputEventToInputManager(inputEvent, java.awt.event.MouseEvent.MOUSE_DRAGGED); } else { - java.awt.event.MouseEvent inputEvent = new PSWTMouseEvent(me, + final java.awt.event.MouseEvent inputEvent = new PSWTMouseEvent(me, java.awt.event.MouseEvent.MOUSE_MOVED, 1); sendInputEventToInputManager(inputEvent, java.awt.event.MouseEvent.MOUSE_MOVED); } } }); - this.addKeyListener(new KeyListener() { - public void keyPressed(KeyEvent ke) { - java.awt.event.KeyEvent inputEvent = new PSWTKeyEvent(ke, java.awt.event.KeyEvent.KEY_PRESSED); + addKeyListener(new KeyListener() { + public void keyPressed(final KeyEvent ke) { + final java.awt.event.KeyEvent inputEvent = new PSWTKeyEvent(ke, java.awt.event.KeyEvent.KEY_PRESSED); sendInputEventToInputManager(inputEvent, java.awt.event.KeyEvent.KEY_PRESSED); } - public void keyReleased(KeyEvent ke) { - java.awt.event.KeyEvent inputEvent = new PSWTKeyEvent(ke, java.awt.event.KeyEvent.KEY_RELEASED); + public void keyReleased(final KeyEvent ke) { + final java.awt.event.KeyEvent inputEvent = new PSWTKeyEvent(ke, java.awt.event.KeyEvent.KEY_RELEASED); sendInputEventToInputManager(inputEvent, java.awt.event.KeyEvent.KEY_RELEASED); } }); } - protected void sendInputEventToInputManager(InputEvent e, int type) { + protected void sendInputEventToInputManager(final InputEvent e, final int type) { getRoot().getDefaultInputManager().processEventFromCamera(e, type, getCamera()); } - public void setBounds(int x, int y, final int w, final int h) { + public void setBounds(final int x, final int y, final int w, final int h) { camera.setBounds(camera.getX(), camera.getY(), w, h); if (backBuffer == null || backBuffer.getBounds().width < w || backBuffer.getBounds().height < h) { @@ -534,14 +534,14 @@ super.redraw(); } - public void repaint(PBounds bounds) { + public void repaint(final PBounds bounds) { bounds.expandNearestIntegerDimensions(); bounds.inset(-1, -1); redraw((int) bounds.x, (int) bounds.y, (int) bounds.width, (int) bounds.height, true); } - public void paintComponent(GC gc, int x, int y, int w, int h) { + public void paintComponent(final GC gc, final int x, final int y, final int w, final int h) { PDebug.startProcessingOutput(); GC imageGC = null; @@ -557,20 +557,20 @@ g2.setColor(Color.white); g2.setBackground(Color.white); - Rectangle rect = getBounds(); + final Rectangle rect = getBounds(); g2.fillRect(0, 0, rect.width, rect.height); // This fixes a problem with standard debugging of region management in // SWT if (PDebug.debugRegionManagement) { - Rectangle r = gc.getClipping(); - Rectangle2D r2 = new Rectangle2D.Double(r.x, r.y, r.width, r.height); + final Rectangle r = gc.getClipping(); + final Rectangle2D r2 = new Rectangle2D.Double(r.x, r.y, r.width, r.height); g2.setBackground(PDebug.getDebugPaintColor()); g2.fill(r2); } // create new paint context and set render quality - PPaintContext paintContext = new PPaintContext(g2); + final PPaintContext paintContext = new PPaintContext(g2); if (getInteracting() || getAnimating()) { if (interactingRenderQuality > animatingRenderQuality) { paintContext.setRenderQuality(interactingRenderQuality); @@ -594,7 +594,7 @@ } animatingOnLastPaint = getAnimating(); - boolean region = PDebug.debugRegionManagement; + final boolean region = PDebug.debugRegionManagement; PDebug.debugRegionManagement = false; PDebug.endProcessingOutput(g2); PDebug.debugRegionManagement = region; diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTHandle.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTHandle.java index 5370837..cd880d9 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTHandle.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTHandle.java @@ -60,6 +60,10 @@ */ public class PSWTHandle extends PSWTPath { + /** + * + */ + private static final long serialVersionUID = 1L; public static float DEFAULT_HANDLE_SIZE = 8; public static Shape DEFAULT_HANDLE_SHAPE = new Ellipse2D.Float(0f, 0f, DEFAULT_HANDLE_SIZE, DEFAULT_HANDLE_SIZE); public static Color DEFAULT_COLOR = Color.white; @@ -71,7 +75,7 @@ * Construct a new handle that will use the given locator to locate itself * on its parent node. */ - public PSWTHandle(PLocator aLocator) { + public PSWTHandle(final PLocator aLocator) { super(DEFAULT_HANDLE_SHAPE); locator = aLocator; setPaint(DEFAULT_COLOR); @@ -80,27 +84,27 @@ protected void installHandleEventHandlers() { handleDragger = new PDragSequenceEventHandler() { - protected void startDrag(PInputEvent event) { + protected void startDrag(final PInputEvent event) { super.startDrag(event); startHandleDrag(event.getPositionRelativeTo(PSWTHandle.this), event); } - protected void drag(PInputEvent event) { + protected void drag(final PInputEvent event) { super.drag(event); - PDimension aDelta = event.getDeltaRelativeTo(PSWTHandle.this); + final PDimension aDelta = event.getDeltaRelativeTo(PSWTHandle.this); if (aDelta.getWidth() != 0 || aDelta.getHeight() != 0) { dragHandle(aDelta, event); } } - protected void endDrag(PInputEvent event) { + protected void endDrag(final PInputEvent event) { super.endDrag(event); endHandleDrag(event.getPositionRelativeTo(PSWTHandle.this), event); } }; addPropertyChangeListener(PNode.PROPERTY_TRANSFORM, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(final PropertyChangeEvent evt) { relocateHandle(); } }); @@ -135,7 +139,7 @@ * Set the locator that this handle uses to position itself on its parent * node. */ - public void setLocator(PLocator aLocator) { + public void setLocator(final PLocator aLocator) { locator = aLocator; invalidatePaint(); relocateHandle(); @@ -150,20 +154,20 @@ * Override this method to get notified when the handle starts to get * dragged. */ - public void startHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { + public void startHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { } /** * Override this method to get notified as the handle is dragged. */ - public void dragHandle(PDimension aLocalDimension, PInputEvent aEvent) { + public void dragHandle(final PDimension aLocalDimension, final PInputEvent aEvent) { } /** * Override this method to get notified when the handle stops getting * dragged. */ - public void endHandleDrag(Point2D aLocalPoint, PInputEvent aEvent) { + public void endHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) { } // **************************************************************** @@ -173,7 +177,7 @@ // position. // **************************************************************** - public void setParent(PNode newParent) { + public void setParent(final PNode newParent) { super.setParent(newParent); relocateHandle(); } @@ -187,12 +191,12 @@ */ public void relocateHandle() { if (locator != null) { - PBounds b = getBoundsReference(); - Point2D aPoint = locator.locatePoint(null); + final PBounds b = getBoundsReference(); + final Point2D aPoint = locator.locatePoint(null); if (locator instanceof PNodeLocator) { - PNode located = ((PNodeLocator) locator).getNode(); - PNode parent = getParent(); + final PNode located = ((PNodeLocator) locator).getNode(); + final PNode parent = getParent(); located.localToGlobal(aPoint); globalToLocal(aPoint); @@ -202,8 +206,8 @@ } } - double newCenterX = aPoint.getX(); - double newCenterY = aPoint.getY(); + final double newCenterX = aPoint.getX(); + final double newCenterY = aPoint.getY(); if (newCenterX != b.getCenterX() || newCenterY != b.getCenterY()) { centerBoundsOnPoint(newCenterX, newCenterY); @@ -215,7 +219,7 @@ // Serialization // **************************************************************** - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); installHandleEventHandlers(); } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTImage.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTImage.java index 6627e88..fc566bf 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTImage.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTImage.java @@ -49,16 +49,21 @@ */ public class PSWTImage extends PNode { - private transient PSWTCanvas canvas; + /** + * + */ + private static final long serialVersionUID = 1L; + + private transient final PSWTCanvas canvas; private transient Image image; - public PSWTImage(PSWTCanvas canvas) { + public PSWTImage(final PSWTCanvas canvas) { super(); this.canvas = canvas; canvas.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent de) { + public void widgetDisposed(final DisposeEvent de) { if (image != null) { image.dispose(); } @@ -66,12 +71,12 @@ }); } - public PSWTImage(PSWTCanvas canvas, Image newImage) { + public PSWTImage(final PSWTCanvas canvas, final Image newImage) { this(canvas); setImage(newImage); } - public PSWTImage(PSWTCanvas canvas, String fileName) { + public PSWTImage(final PSWTCanvas canvas, final String fileName) { this(canvas); setImage(fileName); } @@ -93,7 +98,7 @@ * have transparent regions, for those cases you may want to set the PImage * to be not accelerated. */ - public void setImage(String fileName) { + public void setImage(final String fileName) { setImage(new Image(canvas.getDisplay(), fileName)); } @@ -105,12 +110,12 @@ * have transparent regions, for those cases you may want to set the PImage * to be not accelerated. */ - public void setImage(Image newImage) { - Image old = image; + public void setImage(final Image newImage) { + final Image old = image; image = newImage; if (image != null) { - Rectangle bounds = getImage().getBounds(); + final Rectangle bounds = getImage().getBounds(); setBounds(0, 0, bounds.width, bounds.height); invalidatePaint(); } @@ -121,13 +126,13 @@ firePropertyChange(PImage.PROPERTY_CODE_IMAGE, PImage.PROPERTY_IMAGE, old, image); } - protected void paint(PPaintContext paintContext) { + protected void paint(final PPaintContext paintContext) { if (getImage() != null) { - Rectangle r = image.getBounds(); - double iw = r.width; - double ih = r.height; - PBounds b = getBoundsReference(); - SWTGraphics2D g2 = (SWTGraphics2D) paintContext.getGraphics(); + final Rectangle r = image.getBounds(); + final double iw = r.width; + final double ih = r.height; + final PBounds b = getBoundsReference(); + final SWTGraphics2D g2 = (SWTGraphics2D) paintContext.getGraphics(); if (b.x != 0 || b.y != 0 || b.width != iw || b.height != ih) { g2.translate(b.x, b.y); @@ -155,7 +160,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("image=" + (image == null ? "null" : image.toString())); diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTKeyEvent.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTKeyEvent.java index 1d89208..31bbf66 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTKeyEvent.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTKeyEvent.java @@ -43,12 +43,22 @@ */ public class PSWTKeyEvent extends KeyEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + static Component fakeSrc = new Component() { + + /** + * + */ + private static final long serialVersionUID = 1L; }; org.eclipse.swt.events.KeyEvent swtEvent; - public PSWTKeyEvent(org.eclipse.swt.events.KeyEvent ke, int eventType) { + public PSWTKeyEvent(final org.eclipse.swt.events.KeyEvent ke, final int eventType) { super(fakeSrc, eventType, ke.time, 0, ke.keyCode, ke.character, KeyEvent.KEY_LOCATION_STANDARD); swtEvent = ke; diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTMouseEvent.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTMouseEvent.java index 6fea5a4..fa94507 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTMouseEvent.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTMouseEvent.java @@ -43,17 +43,27 @@ */ public class PSWTMouseEvent extends MouseEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + static Component fakeSrc = new Component() { + + /** + * + */ + private static final long serialVersionUID = 1L; }; protected org.eclipse.swt.events.MouseEvent swtEvent; protected int clickCount; - public PSWTMouseEvent(org.eclipse.swt.events.MouseEvent me, int type, int clickCount) { - super(fakeSrc, type, me.time, 0, me.x, me.y, clickCount, (me.button == 3), me.button); + public PSWTMouseEvent(final org.eclipse.swt.events.MouseEvent me, final int type, final int clickCount) { + super(fakeSrc, type, me.time, 0, me.x, me.y, clickCount, me.button == 3, me.button); - this.swtEvent = me; + swtEvent = me; this.clickCount = clickCount; } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTPath.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTPath.java index 9794fe2..78e50a8 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTPath.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTPath.java @@ -70,6 +70,11 @@ public class PSWTPath extends PNode { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * The property name that identifies a change of this node's path. In any * property change event the new value will be a reference to this node's * path, but old value will always be null. @@ -95,37 +100,37 @@ double[] shapePts; - public static PSWTPath createRectangle(float x, float y, float width, float height) { + public static PSWTPath createRectangle(final float x, final float y, final float width, final float height) { TEMP_RECTANGLE.setFrame(x, y, width, height); - PSWTPath result = new PSWTPath(TEMP_RECTANGLE); + final PSWTPath result = new PSWTPath(TEMP_RECTANGLE); result.setPaint(Color.white); return result; } - public static PSWTPath createRoundRectangle(float x, float y, float width, float height, float arcWidth, - float arcHeight) { + public static PSWTPath createRoundRectangle(final float x, final float y, final float width, final float height, + final float arcWidth, final float arcHeight) { TEMP_ROUNDRECTANGLE.setRoundRect(x, y, width, height, arcWidth, arcHeight); - PSWTPath result = new PSWTPath(TEMP_ROUNDRECTANGLE); + final PSWTPath result = new PSWTPath(TEMP_ROUNDRECTANGLE); result.setPaint(Color.white); return result; } - public static PSWTPath createEllipse(float x, float y, float width, float height) { + public static PSWTPath createEllipse(final float x, final float y, final float width, final float height) { TEMP_ELLIPSE.setFrame(x, y, width, height); - PSWTPath result = new PSWTPath(TEMP_ELLIPSE); + final PSWTPath result = new PSWTPath(TEMP_ELLIPSE); result.setPaint(Color.white); return result; } - public static PSWTPath createPolyline(Point2D[] points) { - PSWTPath result = new PSWTPath(); + public static PSWTPath createPolyline(final Point2D[] points) { + final PSWTPath result = new PSWTPath(); result.setPathToPolyline(points); result.setPaint(Color.white); return result; } - public static PSWTPath createPolyline(float[] xp, float[] yp) { - PSWTPath result = new PSWTPath(); + public static PSWTPath createPolyline(final float[] xp, final float[] yp) { + final PSWTPath result = new PSWTPath(); result.setPathToPolyline(xp, yp); result.setPaint(Color.white); return result; @@ -135,7 +140,7 @@ strokePaint = DEFAULT_STROKE_PAINT; } - public PSWTPath(Shape aShape) { + public PSWTPath(final Shape aShape) { this(); setShape(aShape); } @@ -148,8 +153,8 @@ return strokePaint; } - public void setStrokeColor(Paint aPaint) { - Paint old = strokePaint; + public void setStrokeColor(final Paint aPaint) { + final Paint old = strokePaint; strokePaint = aPaint; invalidatePaint(); firePropertyChange(PPath.PROPERTY_CODE_STROKE_PAINT, PPath.PROPERTY_STROKE_PAINT, old, strokePaint); @@ -162,13 +167,15 @@ * again since all its numbers have tended to zero, so application code may * need to take this into consideration. */ - protected void internalUpdateBounds(double x, double y, double width, double height) { - if (updatingBoundsFromPath) + protected void internalUpdateBounds(final double x, final double y, final double width, final double height) { + if (updatingBoundsFromPath) { return; - if (origShape == null) + } + if (origShape == null) { return; + } - Rectangle2D pathBounds = origShape.getBounds2D(); + final Rectangle2D pathBounds = origShape.getBounds2D(); if (Math.abs(x - pathBounds.getX()) / x < BOUNDS_TOLERANCE && Math.abs(y - pathBounds.getY()) / y < BOUNDS_TOLERANCE @@ -188,7 +195,7 @@ try { inverseXForm = internalXForm.createInverse(); } - catch (Exception e) { + catch (final Exception e) { } } @@ -217,7 +224,7 @@ resetBounds(); } else { - Rectangle2D b = origShape.getBounds2D(); + final Rectangle2D b = origShape.getBounds2D(); // Note that this pen width code does not really work for SWT since // it assumes @@ -235,9 +242,9 @@ // Painting // **************************************************************** - protected void paint(PPaintContext paintContext) { - Paint p = getPaint(); - SWTGraphics2D g2 = (SWTGraphics2D) paintContext.getGraphics(); + protected void paint(final PPaintContext paintContext) { + final Paint p = getPaint(); + final SWTGraphics2D g2 = (SWTGraphics2D) paintContext.getGraphics(); if (internalXForm != null) { g2.transform(internalXForm); @@ -246,7 +253,7 @@ if (p != null) { g2.setBackground((Color) p); - double lineWidth = g2.getTransformedLineWidth(); + final double lineWidth = g2.getTransformedLineWidth(); if (shape instanceof Rectangle2D) { g2.fillRect(shapePts[0] + lineWidth / 2, shapePts[1] + lineWidth / 2, shapePts[2] - lineWidth, shapePts[3] - lineWidth); @@ -271,7 +278,7 @@ if (strokePaint != null) { g2.setColor((Color) strokePaint); - double lineWidth = g2.getTransformedLineWidth(); + final double lineWidth = g2.getTransformedLineWidth(); if (shape instanceof Rectangle2D) { g2.drawRect(shapePts[0] + lineWidth / 2, shapePts[1] + lineWidth / 2, shapePts[2] - lineWidth, shapePts[3] - lineWidth); @@ -300,9 +307,9 @@ } } - public void setShape(Shape aShape) { - this.shape = cloneShape(aShape); - this.origShape = shape; + public void setShape(final Shape aShape) { + shape = cloneShape(aShape); + origShape = shape; updateShapePoints(aShape); firePropertyChange(PPath.PROPERTY_CODE_PATH, PPath.PROPERTY_PATH, null, shape); @@ -310,7 +317,7 @@ invalidatePaint(); } - public void updateShapePoints(Shape aShape) { + public void updateShapePoints(final Shape aShape) { if (aShape instanceof Rectangle2D) { if (shapePts == null || shapePts.length < 4) { shapePts = new double[4]; @@ -360,53 +367,54 @@ } } - public Shape cloneShape(Shape aShape) { + public Shape cloneShape(final Shape aShape) { if (aShape instanceof Rectangle2D) { return new PBounds((Rectangle2D) aShape); } else if (aShape instanceof Ellipse2D) { - Ellipse2D e2 = (Ellipse2D) aShape; + final Ellipse2D e2 = (Ellipse2D) aShape; return new Ellipse2D.Double(e2.getX(), e2.getY(), e2.getWidth(), e2.getHeight()); } else if (aShape instanceof Arc2D) { - Arc2D a2 = (Arc2D) aShape; + final Arc2D a2 = (Arc2D) aShape; return new Arc2D.Double(a2.getX(), a2.getY(), a2.getWidth(), a2.getHeight(), a2.getAngleStart(), a2 .getAngleExtent(), a2.getArcType()); } else if (aShape instanceof RoundRectangle2D) { - RoundRectangle2D r2 = (RoundRectangle2D) aShape; + final RoundRectangle2D r2 = (RoundRectangle2D) aShape; return new RoundRectangle2D.Double(r2.getX(), r2.getY(), r2.getWidth(), r2.getHeight(), r2.getArcWidth(), r2.getArcHeight()); } else if (aShape instanceof Line2D) { - Line2D l2 = (Line2D) aShape; + final Line2D l2 = (Line2D) aShape; return new Line2D.Double(l2.getP1(), l2.getP2()); } else { new Exception().printStackTrace(); - GeneralPath aPath = new GeneralPath(); + final GeneralPath aPath = new GeneralPath(); aPath.append(aShape, false); return aPath; } } - public void setPathToRectangle(float x, float y, float width, float height) { + public void setPathToRectangle(final float x, final float y, final float width, final float height) { TEMP_RECTANGLE.setFrame(x, y, width, height); setShape(TEMP_RECTANGLE); } - public void setPathToRoundRectangle(float x, float y, float width, float height, float arcWidth, float arcHeight) { + public void setPathToRoundRectangle(final float x, final float y, final float width, final float height, + final float arcWidth, final float arcHeight) { TEMP_ROUNDRECTANGLE.setRoundRect(x, y, width, height, arcWidth, arcHeight); setShape(TEMP_ROUNDRECTANGLE); } - public void setPathToEllipse(float x, float y, float width, float height) { + public void setPathToEllipse(final float x, final float y, final float width, final float height) { TEMP_ELLIPSE.setFrame(x, y, width, height); setShape(TEMP_ELLIPSE); } - public void setPathToPolyline(Point2D[] points) { - GeneralPath path = new GeneralPath(); + public void setPathToPolyline(final Point2D[] points) { + final GeneralPath path = new GeneralPath(); path.reset(); path.moveTo((float) points[0].getX(), (float) points[0].getY()); for (int i = 1; i < points.length; i++) { @@ -415,8 +423,8 @@ setShape(path); } - public void setPathToPolyline(float[] xp, float[] yp) { - GeneralPath path = new GeneralPath(); + public void setPathToPolyline(final float[] xp, final float[] yp) { + final GeneralPath path = new GeneralPath(); path.reset(); path.moveTo(xp[0], yp[0]); for (int i = 1; i < xp.length; i++) { @@ -438,7 +446,7 @@ * @return a string representation of this node's state */ protected String paramString() { - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); result.append("path=" + (shape == null ? "null" : shape.toString())); result.append(",strokePaint=" + (strokePaint == null ? "null" : strokePaint.toString())); diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTRoot.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTRoot.java index ae958eb..1747e4f 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTRoot.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTRoot.java @@ -29,6 +29,7 @@ package edu.umd.cs.piccolox.swt; import java.awt.event.ActionListener; + import javax.swing.Timer; import org.eclipse.swt.widgets.Composite; @@ -47,13 +48,17 @@ */ public class PSWTRoot extends PRoot { - private Composite composite; + /** + * + */ + private static final long serialVersionUID = 1L; + private final Composite composite; - public PSWTRoot(Composite composite) { + public PSWTRoot(final Composite composite) { this.composite = composite; } - public Timer createTimer(int delay, ActionListener listener) { + public Timer createTimer(final int delay, final ActionListener listener) { return new SWTTimer(composite.getDisplay(), delay, listener); } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTSelectionEventHandler.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTSelectionEventHandler.java index 0b2ce38..aa17a50 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTSelectionEventHandler.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTSelectionEventHandler.java @@ -63,7 +63,7 @@ * @param selectableParent The node whose children will be selected by this * event handler. */ - public PSWTSelectionEventHandler(PNode marqueeParent, PNode selectableParent) { + public PSWTSelectionEventHandler(final PNode marqueeParent, final PNode selectableParent) { super(new PNode(), selectableParent); this.marqueeParent = marqueeParent; } @@ -76,31 +76,36 @@ * @param selectableParents A list of nodes whose children will be selected * by this event handler. */ - public PSWTSelectionEventHandler(PNode marqueeParent, List selectableParents) { + public PSWTSelectionEventHandler(final PNode marqueeParent, final List selectableParents) { super(new PNode(), selectableParents); this.marqueeParent = marqueeParent; } - public void decorateSelectedNode(PNode node) { + public void decorateSelectedNode(final PNode node) { PSWTBoundsHandle.addBoundsHandlesTo(node); } - public void undecorateSelectedNode(PNode node) { + public void undecorateSelectedNode(final PNode node) { PSWTBoundsHandle.removeBoundsHandlesFrom(node); } - protected void initializeSelection(PInputEvent pie) { + protected void initializeSelection(final PInputEvent pie) { super.initializeSelection(pie); pressPt = pie.getPosition(); canvasPressPt = pie.getCanvasPosition(); } - protected void initializeMarquee(PInputEvent e) { + protected void initializeMarquee(final PInputEvent e) { super.initializeMarquee(e); marquee = new PSWTPath(new Rectangle2D.Float((float) pressPt.getX(), (float) pressPt.getY(), 0, 0)) { - protected void paint(PPaintContext paintContext) { - SWTGraphics2D s2g = (SWTGraphics2D) paintContext.getGraphics(); + /** + * + */ + private static final long serialVersionUID = 1L; + + protected void paint(final PPaintContext paintContext) { + final SWTGraphics2D s2g = (SWTGraphics2D) paintContext.getGraphics(); s2g.gc.setLineStyle(SWT.LINE_DASH); super.paint(paintContext); s2g.gc.setLineStyle(SWT.LINE_SOLID); @@ -111,10 +116,10 @@ marqueeParent.addChild(marquee); } - protected void updateMarquee(PInputEvent pie) { + protected void updateMarquee(final PInputEvent pie) { super.updateMarquee(pie); - PBounds b = new PBounds(); + final PBounds b = new PBounds(); if (marqueeParent instanceof PCamera) { b.add(canvasPressPt); @@ -138,7 +143,7 @@ return new PBounds(); } - protected void endMarqueeSelection(PInputEvent e) { + protected void endMarqueeSelection(final PInputEvent e) { super.endMarqueeSelection(e); // Remove marquee @@ -150,6 +155,6 @@ * This gets called continuously during the drag, and is used to animate the * marquee */ - protected void dragActivityStep(PInputEvent aEvent) { + protected void dragActivityStep(final PInputEvent aEvent) { } } \ No newline at end of file diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTStickyHandleManager.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTStickyHandleManager.java index 7a44fb6..74486ec 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTStickyHandleManager.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTStickyHandleManager.java @@ -35,22 +35,26 @@ public class PSWTStickyHandleManager extends PNode { + /** + * + */ + private static final long serialVersionUID = 1L; private PNode target; private PCamera camera; - public PSWTStickyHandleManager(PCamera newCamera, PNode newTarget) { + public PSWTStickyHandleManager(final PCamera newCamera, final PNode newTarget) { setCameraTarget(newCamera, newTarget); PSWTBoundsHandle.addBoundsHandlesTo(this); } - public void setCameraTarget(PCamera newCamera, PNode newTarget) { + public void setCameraTarget(final PCamera newCamera, final PNode newTarget) { camera = newCamera; camera.addChild(this); target = newTarget; } - public boolean setBounds(double x, double y, double width, double height) { - PBounds b = new PBounds(x, y, width, height); + public boolean setBounds(final double x, final double y, final double width, final double height) { + final PBounds b = new PBounds(x, y, width, height); camera.localToGlobal(b); camera.localToView(b); target.globalToLocal(b); @@ -63,10 +67,10 @@ } public PBounds getBoundsReference() { - PBounds targetBounds = target.getFullBounds(); + final PBounds targetBounds = target.getFullBounds(); camera.viewToLocal(targetBounds); camera.globalToLocal(targetBounds); - PBounds bounds = super.getBoundsReference(); + final PBounds bounds = super.getBoundsReference(); bounds.setRect(targetBounds); return super.getBoundsReference(); } @@ -81,7 +85,7 @@ target.endResizeBounds(); } - public boolean pickAfterChildren(PPickPath pickPath) { + public boolean pickAfterChildren(final PPickPath pickPath) { return false; } } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTText.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTText.java index 6e1c0d2..038699d 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTText.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/PSWTText.java @@ -8,8 +8,11 @@ import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; -import java.awt.geom.*; -import java.util.*; +import java.awt.geom.AffineTransform; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.Iterator; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; @@ -35,6 +38,11 @@ public class PSWTText extends PNode { /** + * + */ + private static final long serialVersionUID = 1L; + + /** * Below this magnification render text as 'greek'. */ static protected final double DEFAULT_GREEK_THRESHOLD = 5.5; @@ -131,7 +139,7 @@ * * @param str The initial text. */ - public PSWTText(String str) { + public PSWTText(final String str) { this(str, DEFAULT_FONT); } @@ -141,19 +149,19 @@ * @param str The initial text. * @param font The font for this PSWTText component. */ - public PSWTText(String str, Font font) { + public PSWTText(final String str, final Font font) { setText(str); this.font = font; recomputeBounds(); } - //************************************************************************** + // ************************************************************************** // ** // // Get/Set and pairs // - //************************************************************************** + // ************************************************************************** // * /** @@ -168,7 +176,7 @@ * * @param color use this color. */ - public void setPenColor(Color color) { + public void setPenColor(final Color color) { penColor = color; repaint(); } @@ -185,7 +193,7 @@ * * @param aPaint use this paint. */ - public void setPenPaint(Paint aPaint) { + public void setPenPaint(final Paint aPaint) { penColor = (Color) aPaint; } @@ -201,7 +209,7 @@ * * @param color use this color. */ - public void setBackgroundColor(Color color) { + public void setBackgroundColor(final Color color) { super.setPaint(color); } @@ -219,7 +227,7 @@ * * @param threshold compared to renderContext magnification. */ - public void setGreekThreshold(double threshold) { + public void setGreekThreshold(final double threshold) { greekThreshold = threshold; repaint(); } @@ -241,7 +249,7 @@ String result = new String(); int lineNum = 0; - for (Iterator i = lines.iterator(); i.hasNext();) { + for (final Iterator i = lines.iterator(); i.hasNext();) { if (lineNum > 0) { result += '\n'; } @@ -266,7 +274,7 @@ * * @param aFont use this font. */ - public void setFont(Font aFont) { + public void setFont(final Font aFont) { font = aFont; recomputeBounds(); @@ -279,7 +287,7 @@ * @param str use this string. */ public void setText(String str) { - int pos = 0; + final int pos = 0; int index; boolean done = false; lines = new ArrayList(); @@ -303,7 +311,7 @@ * * @param x the X translation. */ - public void setTranslateX(double x) { + public void setTranslateX(final double x) { setTranslation(x, translateY); } @@ -321,7 +329,7 @@ * * @param y the Y translation. */ - public void setTranslateY(double y) { + public void setTranslateY(final double y) { setTranslation(translateX, y); } @@ -340,7 +348,7 @@ * @param x the X-coord of translation * @param y the Y-coord of translation */ - public void setTranslation(double x, double y) { + public void setTranslation(final double x, final double y) { translateX = x; translateY = y; @@ -352,7 +360,7 @@ * * @param p The translation offset. */ - public void setTranslation(Point2D p) { + public void setTranslation(final Point2D p) { setTranslation(p.getX(), p.getY()); } @@ -362,7 +370,7 @@ * @return The translation offset. */ public Point2D getTranslation() { - Point2D p = new Point2D.Double(translateX, translateY); + final Point2D p = new Point2D.Double(translateX, translateY); return p; } @@ -378,26 +386,26 @@ * * @param ppc Contains information about current render. */ - public void paint(PPaintContext ppc) { - Graphics2D g2 = ppc.getGraphics(); + public void paint(final PPaintContext ppc) { + final Graphics2D g2 = ppc.getGraphics(); AffineTransform at = null; boolean translated = false; if (!lines.isEmpty()) { - if ((translateX != 0.0) || (translateY != 0.0)) { + if (translateX != 0.0 || translateY != 0.0) { at = g2.getTransform(); // save transform g2.translate(translateX, translateY); translated = true; } // If font too small and not antialiased, then greek - double renderedFontSize = font.getSize() * ppc.getScale(); + final double renderedFontSize = font.getSize() * ppc.getScale(); // BBB: HACK ALERT - July 30, 1999 // This is a workaround for a bug in Sun JDK 1.2.2 where // fonts that are rendered at very small magnifications show up big! // So, we render as greek if requested (that's normal) // OR if the font is very small (that's the workaround) - if ((renderedFontSize < 0.5) || (renderedFontSize < greekThreshold)) { + if (renderedFontSize < 0.5 || renderedFontSize < greekThreshold) { paintAsGreek(ppc); } else { @@ -414,8 +422,8 @@ * * @param ppc The graphics context to paint into. */ - public void paintAsGreek(PPaintContext ppc) { - Graphics2D g2 = ppc.getGraphics(); + public void paintAsGreek(final PPaintContext ppc) { + final Graphics2D g2 = ppc.getGraphics(); if (greekColor != null) { g2.setBackground(greekColor); @@ -430,20 +438,20 @@ * * @param ppc The graphics context to paint into. */ - public void paintAsText(PPaintContext ppc) { - SWTGraphics2D sg2 = (SWTGraphics2D) ppc.getGraphics(); + public void paintAsText(final PPaintContext ppc) { + final SWTGraphics2D sg2 = (SWTGraphics2D) ppc.getGraphics(); if (getPaint() != null) { sg2.setBackground((Color) getPaint()); - Rectangle2D rect = new Rectangle2D.Double(0.0, 0.0, getWidth(), getHeight()); + final Rectangle2D rect = new Rectangle2D.Double(0.0, 0.0, getWidth(), getHeight()); sg2.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); } sg2.translate(padding, padding); - double scale = Math.min(sg2.getTransform().getScaleX(), sg2.getTransform().getScaleY()); - double dSize = scale * font.getSize(); - double fixupScale = Math.floor(dSize) / dSize; + final double scale = Math.min(sg2.getTransform().getScaleX(), sg2.getTransform().getScaleY()); + final double dSize = scale * font.getSize(); + final double fixupScale = Math.floor(dSize) / dSize; // This moves the text size down to the next closest integer size - to // help it stay in @@ -462,18 +470,18 @@ String line; double y; - FontMetrics metrics = sg2.getSWTFontMetrics(); + final FontMetrics metrics = sg2.getSWTFontMetrics(); - for (Iterator i = lines.iterator(); i.hasNext();) { + for (final Iterator i = lines.iterator(); i.hasNext();) { line = (String) i.next(); // ADDED BY LEG ON 2/25/03 - BUG CAUSING PROBLEMS AT CERTAIN // SCALES WHEN LINE WAS EMPTY - line = (line.equals("")) ? " " : line; + line = line.equals("") ? " " : line; - y = (lineNum * metrics.getHeight()); + y = lineNum * metrics.getHeight(); - sg2.drawString(line, (double) 0, (double) y); + sg2.drawString(line, 0, y); lineNum++; } @@ -496,19 +504,19 @@ height = 0.0; boolean hasText = true; - if ((lines.size() == 1) && (((String) lines.get(0)).equals(""))) { + if (lines.size() == 1 && ((String) lines.get(0)).equals("")) { hasText = false; } - GC gc = new GC(Display.getDefault()); - SWTGraphics2D g2 = new SWTGraphics2D(gc, Display.getDefault()); + final GC gc = new GC(Display.getDefault()); + final SWTGraphics2D g2 = new SWTGraphics2D(gc, Display.getDefault()); g2.setFont(font); - FontMetrics fm = g2.getSWTFontMetrics(); + final FontMetrics fm = g2.getSWTFontMetrics(); if (!lines.isEmpty() && hasText) { String line; int lineNum = 0; - for (Iterator i = lines.iterator(); i.hasNext();) { + for (final Iterator i = lines.iterator(); i.hasNext();) { line = (String) i.next(); // Find the longest line in the text @@ -543,7 +551,7 @@ setBounds(translateX, translateY, maxWidth + 2 * DEFAULT_PADDING, height + 2 * DEFAULT_PADDING); } - protected void internalUpdateBounds(double x, double y, double width, double height) { + protected void internalUpdateBounds(final double x, final double y, final double width, final double height) { recomputeBounds(); } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTGraphics2D.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTGraphics2D.java index 0274484..2ed7147 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTGraphics2D.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTGraphics2D.java @@ -100,7 +100,7 @@ /** * Constructor for SWTGraphics2D. */ - public SWTGraphics2D(GC gc, Device device) { + public SWTGraphics2D(final GC gc, final Device device) { super(); this.gc = gc; @@ -115,18 +115,18 @@ * @see java.awt.Graphics#getClipBounds() */ public Rectangle getClipBounds() { - org.eclipse.swt.graphics.Rectangle rect = gc.getClipping(); - Rectangle aRect = new Rectangle(rect.x, rect.y, rect.width, rect.height); + final org.eclipse.swt.graphics.Rectangle rect = gc.getClipping(); + final Rectangle aRect = new Rectangle(rect.x, rect.y, rect.width, rect.height); try { SWTShapeManager.transform(aRect, transform.createInverse()); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } return aRect; } - public void clipRect(int x, int y, int width, int height) { + public void clipRect(final int x, final int y, final int width, final int height) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -137,7 +137,7 @@ gc.setClipping(clip); } - public void setClip(int x, int y, int width, int height) { + public void setClip(final int x, final int y, final int width, final int height) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -148,8 +148,8 @@ /** * This method isn't really supported by SWT - so will use the shape bounds */ - public void clip(Shape s) { - Rectangle2D clipBds = s.getBounds2D(); + public void clip(final Shape s) { + final Rectangle2D clipBds = s.getBounds2D(); SWTShapeManager.transform(clipBds, transform); SWTShapeManager.awtToSWT(clipBds, SWT_RECT); @@ -162,12 +162,12 @@ /** * This method isn't really supported by SWT - so will use the shape bounds */ - public void setClip(Shape clip) { + public void setClip(final Shape clip) { if (clip == null) { gc.setClipping((org.eclipse.swt.graphics.Rectangle) null); } else { - Rectangle2D clipBds = clip.getBounds2D(); + final Rectangle2D clipBds = clip.getBounds2D(); SWTShapeManager.transform(clipBds, transform); SWTShapeManager.awtToSWT(clipBds, SWT_RECT); @@ -176,12 +176,12 @@ } public Shape getClip() { - org.eclipse.swt.graphics.Rectangle rect = gc.getClipping(); - Rectangle2D aRect = new Rectangle2D.Double(rect.x, rect.y, rect.width, rect.height); + final org.eclipse.swt.graphics.Rectangle rect = gc.getClipping(); + final Rectangle2D aRect = new Rectangle2D.Double(rect.x, rect.y, rect.width, rect.height); try { SWTShapeManager.transform(aRect, transform.createInverse()); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } return aRect; @@ -203,19 +203,19 @@ return getColor(); } - public void setPaint(Paint paint) { + public void setPaint(final Paint paint) { if (paint instanceof Color) { setColor((Color) paint); } } public Color getColor() { - org.eclipse.swt.graphics.Color color = gc.getForeground(); - Color awtColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); + final org.eclipse.swt.graphics.Color color = gc.getForeground(); + final Color awtColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); return awtColor; } - public void setColor(Color c) { + public void setColor(final Color c) { org.eclipse.swt.graphics.Color cachedColor = (org.eclipse.swt.graphics.Color) COLOR_CACHE.get(c); if (cachedColor == null) { cachedColor = new org.eclipse.swt.graphics.Color(device, c.getRed(), c.getGreen(), c.getBlue()); @@ -224,11 +224,11 @@ gc.setForeground(cachedColor); } - public void setColor(org.eclipse.swt.graphics.Color c) { + public void setColor(final org.eclipse.swt.graphics.Color c) { gc.setForeground(c); } - public void setBackground(Color c) { + public void setBackground(final Color c) { org.eclipse.swt.graphics.Color cachedColor = (org.eclipse.swt.graphics.Color) COLOR_CACHE.get(c); if (cachedColor == null) { cachedColor = new org.eclipse.swt.graphics.Color(device, c.getRed(), c.getGreen(), c.getBlue()); @@ -237,13 +237,13 @@ gc.setBackground(cachedColor); } - public void setBackground(org.eclipse.swt.graphics.Color c) { + public void setBackground(final org.eclipse.swt.graphics.Color c) { gc.setBackground(c); } public Color getBackground() { - org.eclipse.swt.graphics.Color color = gc.getBackground(); - Color awtColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); + final org.eclipse.swt.graphics.Color color = gc.getBackground(); + final Color awtColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); return awtColor; } @@ -264,7 +264,7 @@ if (curFont != null) { int style = Font.PLAIN; - FontData[] fd = curFont.getFontData(); + final FontData[] fd = curFont.getFontData(); if (fd.length > 0) { if ((fd[0].getStyle() & SWT.BOLD) != 0) { style = style | Font.BOLD; @@ -282,18 +282,18 @@ } } - public void setFont(Font font) { - String fontString = "name=" + font.getFamily() + ";bold=" + font.isBold() + ";italic=" + font.isItalic() + public void setFont(final Font font) { + final String fontString = "name=" + font.getFamily() + ";bold=" + font.isBold() + ";italic=" + font.isItalic() + ";size=" + font.getSize(); curFont = getFont(fontString); } - public void setFont(org.eclipse.swt.graphics.Font font) { + public void setFont(final org.eclipse.swt.graphics.Font font) { curFont = font; } - public org.eclipse.swt.graphics.Font getFont(String fontString) { + public org.eclipse.swt.graphics.Font getFont(final String fontString) { org.eclipse.swt.graphics.Font cachedFont = (org.eclipse.swt.graphics.Font) FONT_CACHE.get(fontString); if (cachedFont == null) { int style = 0; @@ -304,13 +304,13 @@ style = style | SWT.ITALIC; } - String name = fontString.substring(0, fontString.indexOf(";")); - String size = fontString.substring(fontString.lastIndexOf(";") + 1, fontString.length()); + final String name = fontString.substring(0, fontString.indexOf(";")); + final String size = fontString.substring(fontString.lastIndexOf(";") + 1, fontString.length()); int sizeInt = 12; try { sizeInt = Integer.parseInt(size.substring(size.indexOf("=") + 1, size.length())); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } @@ -323,13 +323,13 @@ protected org.eclipse.swt.graphics.Font getTransformedFont() { if (curFont != null) { - FontData fontData = curFont.getFontData()[0]; + final FontData fontData = curFont.getFontData()[0]; int height = fontData.getHeight(); RECT.setRect(0, 0, height, height); SWTShapeManager.transform(RECT, transform); height = (int) (RECT.getHeight() + 0.5); - String fontString = "name=" + fontData.getName() + ";bold=" + ((fontData.getStyle() & SWT.BOLD) != 0) + final String fontString = "name=" + fontData.getName() + ";bold=" + ((fontData.getStyle() & SWT.BOLD) != 0) + ";italic=" + ((fontData.getStyle() & SWT.ITALIC) != 0) + ";size=" + height; return getFont(fontString); } @@ -340,35 +340,35 @@ // AFFINE TRANSFORM METHODS // ///////////////////////// - public void translate(int x, int y) { + public void translate(final int x, final int y) { transform.translate(x, y); } - public void translate(double tx, double ty) { + public void translate(final double tx, final double ty) { transform.translate(tx, ty); } - public void rotate(double theta) { + public void rotate(final double theta) { transform.rotate(theta); } - public void rotate(double theta, double x, double y) { + public void rotate(final double theta, final double x, final double y) { transform.rotate(theta, x, y); } - public void scale(double sx, double sy) { + public void scale(final double sx, final double sy) { transform.scale(sx, sy); } - public void shear(double shx, double shy) { + public void shear(final double shx, final double shy) { transform.shear(shx, shy); } - public void transform(AffineTransform Tx) { + public void transform(final AffineTransform Tx) { transform.concatenate(Tx); } - public void setTransform(AffineTransform Tx) { + public void setTransform(final AffineTransform Tx) { transform = (AffineTransform) Tx.clone(); } @@ -380,25 +380,25 @@ // DRAWING AND FILLING METHODS // ///////////////////////////// - public void clearRect(int x, int y, int width, int height) { + public void clearRect(final int x, final int y, final int width, final int height) { fillRect(x, y, width, height); } - public void draw(Shape s) { + public void draw(final Shape s) { if (s instanceof Rectangle2D) { - Rectangle2D r2 = (Rectangle2D) s; + final Rectangle2D r2 = (Rectangle2D) s; drawRect(r2.getX(), r2.getY(), r2.getWidth(), r2.getHeight()); } else if (s instanceof Ellipse2D) { - Ellipse2D e2 = (Ellipse2D) s; + final Ellipse2D e2 = (Ellipse2D) s; drawOval(e2.getX(), e2.getY(), e2.getWidth(), e2.getHeight()); } else if (s instanceof RoundRectangle2D) { - RoundRectangle2D r2 = (RoundRectangle2D) s; + final RoundRectangle2D r2 = (RoundRectangle2D) s; drawRoundRect(r2.getX(), r2.getY(), r2.getWidth(), r2.getHeight(), r2.getArcWidth(), r2.getArcHeight()); } else if (s instanceof Arc2D) { - Arc2D a2 = (Arc2D) s; + final Arc2D a2 = (Arc2D) s; drawArc(a2.getX(), a2.getY(), a2.getWidth(), a2.getHeight(), a2.getAngleStart(), a2.getAngleExtent()); } else { @@ -413,21 +413,21 @@ } } - public void fill(Shape s) { + public void fill(final Shape s) { if (s instanceof Rectangle2D) { - Rectangle2D r2 = (Rectangle2D) s; + final Rectangle2D r2 = (Rectangle2D) s; fillRect(r2.getX(), r2.getY(), r2.getWidth(), r2.getHeight()); } else if (s instanceof Ellipse2D) { - Ellipse2D e2 = (Ellipse2D) s; + final Ellipse2D e2 = (Ellipse2D) s; fillOval(e2.getX(), e2.getY(), e2.getWidth(), e2.getHeight()); } else if (s instanceof RoundRectangle2D) { - RoundRectangle2D r2 = (RoundRectangle2D) s; + final RoundRectangle2D r2 = (RoundRectangle2D) s; fillRoundRect(r2.getX(), r2.getY(), r2.getWidth(), r2.getHeight(), r2.getArcWidth(), r2.getArcHeight()); } else if (s instanceof Arc2D) { - Arc2D a2 = (Arc2D) s; + final Arc2D a2 = (Arc2D) s; fillArc(a2.getX(), a2.getY(), a2.getWidth(), a2.getHeight(), a2.getAngleStart(), a2.getAngleExtent()); } else { @@ -442,8 +442,8 @@ } } - public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { - int[] ptArray = new int[2 * nPoints]; + public void drawPolyline(final int[] xPoints, final int[] yPoints, final int nPoints) { + final int[] ptArray = new int[2 * nPoints]; for (int i = 0; i < nPoints; i++) { PT.setLocation(xPoints[i], yPoints[i]); transform.transform(PT, PT); @@ -455,13 +455,13 @@ gc.drawPolyline(ptArray); } - public void drawPolyline(double[] pts) { - int[] intPts = SWTShapeManager.transform(pts, transform); + public void drawPolyline(final double[] pts) { + final int[] intPts = SWTShapeManager.transform(pts, transform); gc.drawPolyline(intPts); } - public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { - int[] ptArray = new int[2 * nPoints]; + public void drawPolygon(final int[] xPoints, final int[] yPoints, final int nPoints) { + final int[] ptArray = new int[2 * nPoints]; for (int i = 0; i < nPoints; i++) { PT.setLocation(xPoints[i], yPoints[i]); transform.transform(PT, PT); @@ -472,13 +472,13 @@ gc.drawPolygon(ptArray); } - public void fillPolygon(double[] pts) { - int[] intPts = SWTShapeManager.transform(pts, transform); + public void fillPolygon(final double[] pts) { + final int[] intPts = SWTShapeManager.transform(pts, transform); gc.fillPolygon(intPts); } - public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { - int[] ptArray = new int[2 * nPoints]; + public void fillPolygon(final int[] xPoints, final int[] yPoints, final int nPoints) { + final int[] ptArray = new int[2 * nPoints]; for (int i = 0; i < nPoints; i++) { PT.setLocation(xPoints[i], yPoints[i]); transform.transform(PT, PT); @@ -489,7 +489,7 @@ gc.fillPolygon(ptArray); } - public void drawLine(int x1, int y1, int x2, int y2) { + public void drawLine(final int x1, final int y1, final int x2, final int y2) { drawLine((double) x1, (double) y1, (double) x2, (double) y2); } @@ -507,20 +507,20 @@ gc.drawLine((int) (x1 + 0.5), (int) (y1 + 0.5), (int) (x2 + 0.5), (int) (y2 + 0.5)); } - //************************************************************************** + // ************************************************************************** // * // FOR NOW - ASSUME NO ROTATION ON THE TRANSFORM FOR THE FOLLOWING CALLS! - //************************************************************************** + // ************************************************************************** // * - public void copyArea(org.eclipse.swt.graphics.Image img, double x, double y) { + public void copyArea(final org.eclipse.swt.graphics.Image img, final double x, final double y) { PT.setLocation(x, y); transform.transform(PT, PT); gc.copyArea(img, (int) (PT.getX() + 0.5), (int) (PT.getY() + 0.5)); } - public void copyArea(int x, int y, int width, int height, int dx, int dy) { + public void copyArea(final int x, final int y, final int width, final int height, final int dx, final int dy) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); @@ -530,40 +530,40 @@ .getX(), (int) PT.getY()); } - public void drawString(String str, double x, double y) { + public void drawString(final String str, final double x, final double y) { PT.setLocation(x, y); transform.transform(PT, PT); gc.setFont(getTransformedFont()); gc.drawString(str, (int) (PT.getX() + 0.5), (int) (PT.getY() + 0.5), true); } - public void drawString(String str, int x, int y) { + public void drawString(final String str, final int x, final int y) { drawString(str, (double) x, (double) y); } - public void drawString(String str, float x, float y) { + public void drawString(final String str, final float x, final float y) { drawString(str, (double) x, (double) y); } - public void drawText(String s, double x, double y) { + public void drawText(final String s, final double x, final double y) { PT.setLocation(x, y); transform.transform(PT, PT); gc.setFont(getTransformedFont()); gc.drawText(s, (int) (PT.getX() + 0.5), (int) (PT.getY() + 0.5), true); } - public void drawText(String s, double x, double y, int flags) { + public void drawText(final String s, final double x, final double y, final int flags) { PT.setLocation(x, y); transform.transform(PT, PT); gc.setFont(getTransformedFont()); gc.drawText(s, (int) (PT.getX() + 0.5), (int) (PT.getY() + 0.5), flags); } - public void drawRect(int x, int y, int width, int height) { + public void drawRect(final int x, final int y, final int width, final int height) { drawRect((double) x, (double) y, (double) width, (double) height); } - public void drawRect(double x, double y, double width, double height) { + public void drawRect(final double x, final double y, final double width, final double height) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -572,11 +572,11 @@ gc.drawRectangle(SWT_RECT); } - public void fillRect(int x, int y, int width, int height) { + public void fillRect(final int x, final int y, final int width, final int height) { fillRect((double) x, (double) y, (double) width, (double) height); } - public void fillRect(double x, double y, double width, double height) { + public void fillRect(final double x, final double y, final double width, final double height) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -584,7 +584,8 @@ gc.fillRectangle(SWT_RECT); } - public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { + public void drawRoundRect(final int x, final int y, final int width, final int height, final int arcWidth, + final int arcHeight) { drawRoundRect((double) x, (double) y, (double) width, (double) height, (double) arcWidth, (double) arcHeight); } @@ -606,7 +607,8 @@ (int) (arcWidth + 0.5), (int) (arcHeight + 0.5)); } - public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { + public void fillRoundRect(final int x, final int y, final int width, final int height, final int arcWidth, + final int arcHeight) { fillRoundRect((double) x, (double) y, (double) width, (double) height, (double) arcWidth, (double) arcHeight); } @@ -628,11 +630,11 @@ (int) (arcWidth + 0.5), (int) (arcHeight + 0.5)); } - public void drawOval(int x, int y, int width, int height) { + public void drawOval(final int x, final int y, final int width, final int height) { drawOval((double) x, (double) y, (double) width, (double) height); } - public void drawOval(double x, double y, double width, double height) { + public void drawOval(final double x, final double y, final double width, final double height) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); @@ -641,11 +643,11 @@ .getHeight() + 0.5)); } - public void fillOval(int x, int y, int width, int height) { + public void fillOval(final int x, final int y, final int width, final int height) { fillOval((double) x, (double) y, (double) width, (double) height); } - public void fillOval(double x, double y, double width, double height) { + public void fillOval(final double x, final double y, final double width, final double height) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); @@ -653,11 +655,13 @@ .getHeight() + 0.5)); } - public void drawArc(int x, int y, int width, int height, int startAngle, int extent) { + public void drawArc(final int x, final int y, final int width, final int height, final int startAngle, + final int extent) { drawArc((double) x, (double) y, (double) width, (double) height, (double) startAngle, (double) extent); } - public void drawArc(double x, double y, double width, double height, double startAngle, double extent) { + public void drawArc(final double x, final double y, final double width, final double height, + final double startAngle, final double extent) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); @@ -666,11 +670,13 @@ .getHeight() + 0.5), (int) (startAngle + 0.5), (int) (startAngle + extent + 0.5)); } - public void fillArc(int x, int y, int width, int height, int startAngle, int extent) { + public void fillArc(final int x, final int y, final int width, final int height, final int startAngle, + final int extent) { drawArc((double) x, (double) y, (double) width, (double) height, (double) startAngle, (double) extent); } - public void fillArc(double x, double y, double width, double height, double startAngle, double extent) { + public void fillArc(final double x, final double y, final double width, final double height, + final double startAngle, final double extent) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); @@ -682,8 +688,8 @@ // SWT IMAGE METHODS // //////////////////////// - public void drawImage(org.eclipse.swt.graphics.Image image, double x, double y) { - org.eclipse.swt.graphics.Rectangle bounds = image.getBounds(); + public void drawImage(final org.eclipse.swt.graphics.Image image, final double x, final double y) { + final org.eclipse.swt.graphics.Rectangle bounds = image.getBounds(); RECT.setRect(x, y, bounds.width, bounds.height); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -691,8 +697,8 @@ gc.drawImage(image, 0, 0, bounds.width, bounds.height, SWT_RECT.x, SWT_RECT.y, SWT_RECT.width, SWT_RECT.height); } - public void drawImage(org.eclipse.swt.graphics.Image image, int srcX, int srcY, int srcW, int srcH, double destX, - double destY, double destW, double destH) { + public void drawImage(final org.eclipse.swt.graphics.Image image, final int srcX, final int srcY, final int srcW, + final int srcH, final double destX, final double destY, final double destW, final double destH) { RECT.setRect(destX, destY, destW, destH); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -704,7 +710,7 @@ // OTHER SWT SPECIFIC METHODS // //////////////////////////// - public void setLineWidth(double lineWidth) { + public void setLineWidth(final double lineWidth) { this.lineWidth = lineWidth; } @@ -715,7 +721,8 @@ return (int) (Math.max(LINE_RECT.getWidth(), 1) + 0.5); } - public void fillGradientRectangle(double x, double y, double width, double height, boolean vertical) { + public void fillGradientRectangle(final double x, final double y, final double width, final double height, + final boolean vertical) { RECT.setRect(x, y, width, height); SWTShapeManager.transform(RECT, transform); SWTShapeManager.awtToSWT(RECT, SWT_RECT); @@ -723,46 +730,46 @@ gc.fillGradientRectangle(SWT_RECT.x, SWT_RECT.y, SWT_RECT.width, SWT_RECT.height, vertical); } - public void setXORMode(boolean xOr) { + public void setXORMode(final boolean xOr) { gc.setXORMode(xOr); } - public int getAdvanceWidth(char ch) { - org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); + public int getAdvanceWidth(final char ch) { + final org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); gc.setFont(curFont); - int width = gc.getAdvanceWidth(ch); + final int width = gc.getAdvanceWidth(ch); gc.setFont(scaledFont); return width; } - public int getCharWidth(char ch) { - org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); + public int getCharWidth(final char ch) { + final org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); gc.setFont(curFont); - int width = gc.getCharWidth(ch); + final int width = gc.getCharWidth(ch); gc.setFont(scaledFont); return width; } - public org.eclipse.swt.graphics.Point stringExtent(String str) { - org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); + public org.eclipse.swt.graphics.Point stringExtent(final String str) { + final org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); gc.setFont(curFont); - org.eclipse.swt.graphics.Point extent = gc.stringExtent(str); + final org.eclipse.swt.graphics.Point extent = gc.stringExtent(str); gc.setFont(scaledFont); return extent; } - public org.eclipse.swt.graphics.Point textExtent(String str) { - org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); + public org.eclipse.swt.graphics.Point textExtent(final String str) { + final org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); gc.setFont(curFont); - org.eclipse.swt.graphics.Point extent = gc.textExtent(str); + final org.eclipse.swt.graphics.Point extent = gc.textExtent(str); gc.setFont(scaledFont); return extent; } - public org.eclipse.swt.graphics.Point textExtent(String str, int flags) { - org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); + public org.eclipse.swt.graphics.Point textExtent(final String str, final int flags) { + final org.eclipse.swt.graphics.Font scaledFont = gc.getFont(); gc.setFont(curFont); - org.eclipse.swt.graphics.Point extent = gc.textExtent(str, flags); + final org.eclipse.swt.graphics.Point extent = gc.textExtent(str, flags); gc.setFont(scaledFont); return extent; } @@ -774,58 +781,58 @@ /** * @see java.awt.Graphics#drawString(AttributedCharacterIterator, int, int) */ - public void drawString(AttributedCharacterIterator iterator, int x, int y) { + public void drawString(final AttributedCharacterIterator iterator, final int x, final int y) { } /** * @see java.awt.Graphics2D#drawString(AttributedCharacterIterator, float, * float) */ - public void drawString(AttributedCharacterIterator iterator, float x, float y) { + public void drawString(final AttributedCharacterIterator iterator, final float x, final float y) { } /** * @see java.awt.Graphics2D#drawGlyphVector(GlyphVector, float, float) */ - public void drawGlyphVector(GlyphVector g, float x, float y) { + public void drawGlyphVector(final GlyphVector g, final float x, final float y) { } /** * @see java.awt.Graphics2D#hit(Rectangle, Shape, boolean) */ - public boolean hit(Rectangle rect, Shape s, boolean onStroke) { + public boolean hit(final Rectangle rect, final Shape s, final boolean onStroke) { return false; } /** * @see java.awt.Graphics2D#setComposite(Composite) */ - public void setComposite(Composite comp) { + public void setComposite(final Composite comp) { } /** * @see java.awt.Graphics2D#setStroke(Stroke) */ - public void setStroke(Stroke s) { + public void setStroke(final Stroke s) { } - public void setRenderingHint(Key hintKey, Object hintValue) { + public void setRenderingHint(final Key hintKey, final Object hintValue) { } - public Object getRenderingHint(Key hintKey) { + public Object getRenderingHint(final Key hintKey) { return null; } /** * @see java.awt.Graphics2D#setRenderingHints(Map) */ - public void setRenderingHints(Map hints) { + public void setRenderingHints(final Map hints) { } /** * @see java.awt.Graphics2D#addRenderingHints(Map) */ - public void addRenderingHints(Map hints) { + public void addRenderingHints(final Map hints) { } /** @@ -872,20 +879,20 @@ /** * @see java.awt.Graphics#setXORMode(Color) */ - public void setXORMode(Color c1) { + public void setXORMode(final Color c1) { } /** * @see java.awt.Graphics#getFontMetrics(Font) */ - public FontMetrics getFontMetrics(Font f) { + public FontMetrics getFontMetrics(final Font f) { return null; } /** * @see java.awt.Graphics2D#drawImage(Image, AffineTransform, ImageObserver) */ - public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { + public boolean drawImage(final Image img, final AffineTransform xform, final ImageObserver obs) { return false; } @@ -893,27 +900,27 @@ * @see java.awt.Graphics2D#drawImage(BufferedImage, BufferedImageOp, int, * int) */ - public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { + public void drawImage(final BufferedImage img, final BufferedImageOp op, final int x, final int y) { } /** * @see java.awt.Graphics2D#drawRenderedImage(RenderedImage, * AffineTransform) */ - public void drawRenderedImage(RenderedImage img, AffineTransform xform) { + public void drawRenderedImage(final RenderedImage img, final AffineTransform xform) { } /** * @see java.awt.Graphics2D#drawRenderableImage(RenderableImage, * AffineTransform) */ - public void drawRenderableImage(RenderableImage img, AffineTransform xform) { + public void drawRenderableImage(final RenderableImage img, final AffineTransform xform) { } /** * @see java.awt.Graphics#drawImage(Image, int, int, ImageObserver) */ - public boolean drawImage(Image img, int x, int y, ImageObserver observer) { + public boolean drawImage(final Image img, final int x, final int y, final ImageObserver observer) { return false; } @@ -921,14 +928,16 @@ * @see java.awt.Graphics#drawImage(Image, int, int, int, int, * ImageObserver) */ - public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { + public boolean drawImage(final Image img, final int x, final int y, final int width, final int height, + final ImageObserver observer) { return false; } /** * @see java.awt.Graphics#drawImage(Image, int, int, Color, ImageObserver) */ - public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { + public boolean drawImage(final Image img, final int x, final int y, final Color bgcolor, + final ImageObserver observer) { return false; } @@ -936,7 +945,8 @@ * @see java.awt.Graphics#drawImage(Image, int, int, int, int, Color, * ImageObserver) */ - public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { + public boolean drawImage(final Image img, final int x, final int y, final int width, final int height, + final Color bgcolor, final ImageObserver observer) { return false; } @@ -944,8 +954,8 @@ * @see java.awt.Graphics#drawImage(Image, int, int, int, int, int, int, * int, int, ImageObserver) */ - public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, - ImageObserver observer) { + public boolean drawImage(final Image img, final int dx1, final int dy1, final int dx2, final int dy2, + final int sx1, final int sy1, final int sx2, final int sy2, final ImageObserver observer) { return false; } @@ -953,8 +963,9 @@ * @see java.awt.Graphics#drawImage(Image, int, int, int, int, int, int, * int, int, Color, ImageObserver) */ - public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, - Color bgcolor, ImageObserver observer) { + public boolean drawImage(final Image img, final int dx1, final int dy1, final int dx2, final int dy2, + final int sx1, final int sy1, final int sx2, final int sy2, final Color bgcolor, + final ImageObserver observer) { return false; } @@ -976,12 +987,12 @@ CACHE_COUNT--; if (CACHE_COUNT == 0) { - for (Iterator i = FONT_CACHE.values().iterator(); i.hasNext();) { - org.eclipse.swt.graphics.Font font = (org.eclipse.swt.graphics.Font) i.next(); + for (final Iterator i = FONT_CACHE.values().iterator(); i.hasNext();) { + final org.eclipse.swt.graphics.Font font = (org.eclipse.swt.graphics.Font) i.next(); font.dispose(); } - for (Iterator i = COLOR_CACHE.values().iterator(); i.hasNext();) { - org.eclipse.swt.graphics.Color color = (org.eclipse.swt.graphics.Color) i.next(); + for (final Iterator i = COLOR_CACHE.values().iterator(); i.hasNext();) { + final org.eclipse.swt.graphics.Color color = (org.eclipse.swt.graphics.Color) i.next(); color.dispose(); } } diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTShapeManager.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTShapeManager.java index 0dae48f..dd9f67a 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTShapeManager.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTShapeManager.java @@ -54,7 +54,7 @@ * @param rect The rectangle to be transformed * @param at The transform to use to transform the rectangle */ - public static void transform(Rectangle2D rect, AffineTransform at) { + public static void transform(final Rectangle2D rect, final AffineTransform at) { // First, transform all 4 corners of the rectangle pts[0] = rect.getX(); // top left corner pts[1] = rect.getY(); @@ -89,20 +89,20 @@ rect.setRect(minX, minY, maxX - minX, maxY - minY); } - public static void awtToSWT(Rectangle2D aRect, Rectangle sRect) { + public static void awtToSWT(final Rectangle2D aRect, final Rectangle sRect) { sRect.x = (int) (aRect.getX() + 0.5); sRect.y = (int) (aRect.getY() + 0.5); sRect.width = (int) (aRect.getWidth() + 0.5); sRect.height = (int) (aRect.getHeight() + 0.5); } - public static double[] shapeToPolyline(Shape s) { + public static double[] shapeToPolyline(final Shape s) { segList.clear(); aPoint.setLocation(0, 0); - PathIterator pi = s.getPathIterator(IDENTITY_XFORM, 0.000000001); + final PathIterator pi = s.getPathIterator(IDENTITY_XFORM, 0.000000001); while (!pi.isDone()) { - int segType = pi.currentSegment(pts); + final int segType = pi.currentSegment(pts); switch (segType) { case PathIterator.SEG_MOVETO: aPoint.setLocation(pts[0], pts[1]); @@ -118,9 +118,9 @@ pi.next(); } - double[] polyObj = new double[2 * segList.size()]; + final double[] polyObj = new double[2 * segList.size()]; for (int i = 0; i < segList.size(); i++) { - Point2D p2 = (Point2D) segList.get(i); + final Point2D p2 = (Point2D) segList.get(i); polyObj[2 * i] = (int) (p2.getX() + 0.5); polyObj[2 * i + 1] = (int) (p2.getY() + 0.5); } @@ -128,8 +128,8 @@ return polyObj; } - public static int[] transform(double[] pts, AffineTransform at) { - int[] intPts = new int[pts.length]; + public static int[] transform(final double[] pts, final AffineTransform at) { + final int[] intPts = new int[pts.length]; for (int i = 0; i < pts.length / 2; i++) { aPoint.setLocation(pts[2 * i], pts[2 * i + 1]); at.transform(aPoint, aPoint); diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimer.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimer.java index d818f14..9482615 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimer.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimer.java @@ -40,6 +40,11 @@ */ public class SWTTimer extends Timer { + /** + * + */ + private static final long serialVersionUID = 1L; + private boolean notify = false; int initialDelay, delay; @@ -84,10 +89,10 @@ * @param delay * @param listener */ - public SWTTimer(Display display, int delay, ActionListener listener) { + public SWTTimer(final Display display, final int delay, final ActionListener listener) { super(delay, listener); this.delay = delay; - this.initialDelay = delay; + initialDelay = delay; doPostEvent = new SWTDoPostEvent(); this.display = display; @@ -99,9 +104,9 @@ * * @param e the action event to fire */ - protected void fireActionPerformed(ActionEvent e) { + protected void fireActionPerformed(final ActionEvent e) { // Guaranteed to return a non-null array - Object[] listeners = listenerList.getListenerList(); + final Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event @@ -126,7 +131,7 @@ * @param delay the delay in milliseconds * @see #setInitialDelay */ - public void setDelay(int delay) { + public void setDelay(final int delay) { if (delay < 0) { throw new IllegalArgumentException("Invalid delay: " + delay); } @@ -156,7 +161,7 @@ * * @see #setDelay */ - public void setInitialDelay(int initialDelay) { + public void setInitialDelay(final int initialDelay) { if (initialDelay < 0) { throw new IllegalArgumentException("Invalid initial delay: " + initialDelay); } @@ -182,7 +187,7 @@ * @param flag specify false to make the timer stop after * sending its first action event */ - public void setRepeats(boolean flag) { + public void setRepeats(final boolean flag) { repeats = flag; } @@ -208,8 +213,8 @@ * * @param flag specify false to turn off coalescing */ - public void setCoalesce(boolean flag) { - boolean old = coalesce; + public void setCoalesce(final boolean flag) { + final boolean old = coalesce; coalesce = flag; if (!old && coalesce) { // We must do this as otherwise if the Timer once notified diff --git a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimerQueue.java b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimerQueue.java index 0d08247..acf69b2 100644 --- a/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimerQueue.java +++ b/swt/src/main/java/edu/umd/cs/piccolox/swt/SWTTimerQueue.java @@ -44,7 +44,7 @@ /** * Constructor for TimerQueue. */ - public SWTTimerQueue(Display display) { + public SWTTimerQueue(final Display display) { super(); this.display = display; @@ -53,7 +53,7 @@ start(); } - public static SWTTimerQueue sharedInstance(Display display) { + public static SWTTimerQueue sharedInstance(final Display display) { if (instance == null) { instance = new SWTTimerQueue(display); } @@ -67,7 +67,7 @@ else { Display.getDefault().asyncExec(new Runnable() { public void run() { - Thread timerThread = new Thread(SWTTimerQueue.this, "TimerQueue"); + final Thread timerThread = new Thread(SWTTimerQueue.this, "TimerQueue"); timerThread.setDaemon(true); timerThread.setPriority(Thread.NORM_PRIORITY); timerThread.start(); @@ -82,7 +82,7 @@ notify(); } - synchronized void addTimer(SWTTimer timer, long expirationTime) { + synchronized void addTimer(final SWTTimer timer, final long expirationTime) { SWTTimer previousTimer; SWTTimer nextTimer; @@ -99,8 +99,9 @@ // later so they expire in the order they came in. while (nextTimer != null) { - if (nextTimer.expirationTime > expirationTime) + if (nextTimer.expirationTime > expirationTime) { break; + } previousTimer = nextTimer; nextTimer = nextTimer.nextTimer; @@ -119,13 +120,14 @@ notify(); } - synchronized void removeTimer(SWTTimer timer) { + synchronized void removeTimer(final SWTTimer timer) { SWTTimer previousTimer; SWTTimer nextTimer; boolean found; - if (!timer.running) + if (!timer.running) { return; + } previousTimer = null; nextTimer = firstTimer; @@ -141,8 +143,9 @@ nextTimer = nextTimer.nextTimer; } - if (!found) + if (!found) { return; + } if (previousTimer == null) { firstTimer = timer.nextTimer; @@ -156,7 +159,7 @@ timer.running = false; } - synchronized boolean containsTimer(SWTTimer timer) { + synchronized boolean containsTimer(final SWTTimer timer) { return timer.running; } @@ -175,8 +178,9 @@ do { timer = firstTimer; - if (timer == null) + if (timer == null) { return 0; + } currentTime = System.currentTimeMillis(); timeToWait = timer.expirationTime - currentTime; @@ -185,7 +189,7 @@ try { timer.postOverride(); // have timer post an event } - catch (SecurityException e) { + catch (final SecurityException e) { } // Remove the timer from the queue @@ -205,7 +209,7 @@ try { wait(1); } - catch (InterruptedException e) { + catch (final InterruptedException e) { } } } while (timeToWait <= 0); @@ -222,11 +226,11 @@ try { wait(timeToWait); } - catch (InterruptedException e) { + catch (final InterruptedException e) { } } } - catch (ThreadDeath td) { + catch (final ThreadDeath td) { running = false; // Mark all the timers we contain as not being queued. SWTTimer timer = firstTimer; @@ -251,8 +255,9 @@ buf.append(nextTimer.toString()); nextTimer = nextTimer.nextTimer; - if (nextTimer != null) + if (nextTimer != null) { buf.append(", "); + } } buf.append(")"); @@ -268,18 +273,19 @@ Display display = null; - public SWTTimerQueueRestart(Display display) { + public SWTTimerQueueRestart(final Display display) { this.display = display; } public synchronized void run() { // Only try and restart the q once. if (!attemptedStart) { - SWTTimerQueue q = SWTTimerQueue.sharedInstance(display); + final SWTTimerQueue q = SWTTimerQueue.sharedInstance(display); synchronized (q) { - if (!q.running) + if (!q.running) { q.start(); + } } attemptedStart = true; }