verinec.gui.core
Class DrawPanel

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JPanel
                  extended by verinec.gui.core.DrawPanel
All Implemented Interfaces:
MouseListener, MouseMotionListener, ImageObserver, MenuContainer, Serializable, EventListener, Accessible, IConfigurable

public class DrawPanel
extends JPanel
implements IConfigurable, MouseListener, MouseMotionListener

This panel holds all the nodes, hubs, interfaces etc of the configuration. The main work of the panel itself (i.e. programmed in this class) is to listen to events and to perform corresponding actions. For achieving these functionalities, a lot of communictation between nodes and this panel is required.

A note on moving the nodes using the mouse:

Author:
Renato Loeffel
See Also:
Serialized Form

Nested Class Summary
(package private)  class DrawPanel.ViewConfig
          Configuration panel for the drawing options.
 
Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanel
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
private static Dimension canvasSize
          The canvas size.
private static String configName
          Name of the configuration data within the VerinecStudio.saveConfig(String, Document) method.
static int CREATE
          Show preview rectangle where the node would be placed if you press the button.
private  int dragEndX
          Coordinate where we did drag to until now NOTHING: undefined CREATE, SELECT, WIRE: relative to the DrawPanel MOVE: relative to the center of node where the drag click was on
private  int dragEndY
          Coordinate where we did drag to until now NOTHING: undefined CREATE, SELECT, WIRE: relative to the DrawPanel MOVE: relative to the center of node where the drag click was on
private  int dragLastEndX
          Helper variable for repainting: old value of dragEndX.
private  int dragLastEndY
          Helper variable for repainting: old value of dragEndY.
private  int dragStartX
          Coordinate where dragging started.
private  int dragStartY
          Coordinate where dragging started.
private  int editState
          Current state (one of the above).
private  VerinecStudio gui
          The main application class.
static int MOVE
          Draw an outline of the new position for every node and interface when moving some nodes.
private static Color networkBackground
          Background color for the network windows.
static int NOTHING
          Do not draw any outline.
private  int scaledSnapRaster
          Scaled snap raster width.
static int SELECT
          Draw a blue selection rectangle to show what will be selected in multiple selection.
private  boolean showNodeNames
          Whether node names must be displayed.
private  int snapRaster
          Constant for the snap to grid coordinates.
private  boolean snapToGrid
          Whether nodes moved should snap to grid.
private  StandardToolbar stdToolbar
          The toolbar instance.
static int WIRE
          Draw an outline of the wire.
private  float zoomFactor
          The current zoom factor.
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
DrawPanel(VerinecStudio gui, StandardToolbar stdToolbar)
          Initializes the panel, registers several listeners.
 
Method Summary
 int deleteSelectedNodes()
          Deletes all selected Nodes in the panel.
private  void drawPreview(Graphics g, NwComponent c)
          Draw a preview rectangle for a component when dragging nodes.
 void focusSelectedNode()
          Give focus to a selected node.
 NwBinding getBinding(String id)
          Return a reference to the binding identified by the id.
 ConfigPanel getConfigPanel()
          Return a config panel, as in IVerinecModule.
 int getEditState()
          Get the current outline state.
 PCNode getPCNode(String name)
          Get a node by name which is visible on the panel.
private  Document getSavedConfig()
          Load stored configuration or create default if none found.
 int getScaledSnapRaster()
          Get the snap raster width in pixels, adjusted to current scaling.
 int getSnappedCoordinate(int c)
          Rounds the coordinate to the nearest snap point.
 float getZoomFactor()
          Get the current zoom factor.
private  void initConfig(Document config)
          Initialise configuration from config element.
 void initialize()
          (Re)set the panel to its initial state.
 void invertNodeSelection()
          Unselect all selected nodes and select all unselected ones.
 boolean isSnapToGrid()
          Return whether nodes should snap to grid.
 void mouseClicked(MouseEvent e)
          Empty procedure, only added because the listener needs it.
private  void mouseCreateMove(MouseEvent e)
          Execute moving of the preview square.
 void mouseDragged(MouseEvent e)
          Performs one of the following action, according to the type of dragging: if a Node is dragged, update the dragging position if the user draws a selection rectangle, save new coordinates
 void mouseEntered(MouseEvent e)
          Repaint the view, just in case.
 void mouseExited(MouseEvent e)
          Repaint the view, just in case
 void mouseMoved(MouseEvent e)
          If we are in create mode - Save Coordinates into variables - repaint the Component to draw the new node outline
 void mousePressed(MouseEvent e)
          Right click deselects all selected nodes.
 void mouseReleased(MouseEvent e)
          Performs one of the following action according to the type of release.
 void moveSelectedNodes(int x, int y)
          Move all selected nodes in the panel.
 void paint(Graphics g)
          Adjust the paint method to call paintOverlays after painting of the rest.
 void paintComponent(Graphics g)
          Draws the wires.
 void paintOverlays(Graphics g)
          Paint selection rectangle or placement preview.
 void saveConfiguration(Document config)
          Save the config and update values from xml.
 void selectAllNodes()
          Select all nodes.
 void setEditState(int s)
          Set the current state for the panel.
 void setShowNames(boolean show)
          Hides or shows the node name display.
 void setSnapToGrid(boolean snap)
          Enables or disables snap to grid behaviour when moving nodes.
 void setZoomFactor(float factor)
          Set the new zoom factor to apply.
 void unselectAllComponents()
          Sets the selection property of every NwComponent to false
 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

NOTHING

public static final int NOTHING
Do not draw any outline. (Occurs, when cursor is selected in toolbar and no dragging is performed.)

See Also:
Constant Field Values

CREATE

public static final int CREATE
Show preview rectangle where the node would be placed if you press the button.

See Also:
Constant Field Values

SELECT

public static final int SELECT
Draw a blue selection rectangle to show what will be selected in multiple selection.

See Also:
Constant Field Values

MOVE

public static final int MOVE
Draw an outline of the new position for every node and interface when moving some nodes.

See Also:
Constant Field Values

WIRE

public static final int WIRE
Draw an outline of the wire.

See Also:
Constant Field Values

editState

private int editState
Current state (one of the above).


configName

private static final String configName
Name of the configuration data within the VerinecStudio.saveConfig(String, Document) method.

See Also:
Constant Field Values

canvasSize

private static final Dimension canvasSize
The canvas size. todo: Make sizing flexible, as needed


networkBackground

private static Color networkBackground
Background color for the network windows. A dirty brown-grey to distinguish from normal background.


dragStartX

private int dragStartX
Coordinate where dragging started. CREATE, NOTHING: undefined SELECT, WIRE: relative to the DrawPanel MOVE: relative to the center of node where the drag click was on


dragStartY

private int dragStartY
Coordinate where dragging started. CREATE, NOTHING: undefined SELECT, WIRE: relative to the DrawPanel MOVE: relative to the center of node where the drag click was on


dragEndX

private int dragEndX
Coordinate where we did drag to until now NOTHING: undefined CREATE, SELECT, WIRE: relative to the DrawPanel MOVE: relative to the center of node where the drag click was on


dragEndY

private int dragEndY
Coordinate where we did drag to until now NOTHING: undefined CREATE, SELECT, WIRE: relative to the DrawPanel MOVE: relative to the center of node where the drag click was on


dragLastEndX

private int dragLastEndX
Helper variable for repainting: old value of dragEndX.


dragLastEndY

private int dragLastEndY
Helper variable for repainting: old value of dragEndY.


snapRaster

private int snapRaster
Constant for the snap to grid coordinates. Do not used this, but scaledSnapRaster!


scaledSnapRaster

private int scaledSnapRaster
Scaled snap raster width. This is updated whenever snapRaster or zoomFactor changes. Width in pixels of the raster * zoom factor.


snapToGrid

private boolean snapToGrid
Whether nodes moved should snap to grid.


showNodeNames

private boolean showNodeNames
Whether node names must be displayed.


zoomFactor

private float zoomFactor
The current zoom factor. A multiplier for screen coordinates.


gui

private VerinecStudio gui
The main application class.


stdToolbar

private StandardToolbar stdToolbar
The toolbar instance.

Constructor Detail

DrawPanel

public DrawPanel(VerinecStudio gui,
                 StandardToolbar stdToolbar)
          throws VerinecException
Initializes the panel, registers several listeners.

Parameters:
gui - The main application.
stdToolbar - The toolbar instance to update zoom etc.
Throws:
VerinecException - If no saved configuration and no default can be found.
Method Detail

initialize

public void initialize()
(Re)set the panel to its initial state.


getSavedConfig

private Document getSavedConfig()
                         throws VerinecException
Load stored configuration or create default if none found.

Returns:
The view configuration.
Throws:
VerinecException - if configuration can not be loaded (inexisting or invalid).

initConfig

private void initConfig(Document config)
                 throws VerinecException
Initialise configuration from config element.

Parameters:
config - XML document containing the new configuration.
Throws:
VerinecException - if the configuration parameter is incomplete.

getPCNode

public PCNode getPCNode(String name)
Get a node by name which is visible on the panel.

Parameters:
name - The name of the node to retreive.
Returns:
A reference to the requested node or null if it is not found.

getBinding

public NwBinding getBinding(String id)
Return a reference to the binding identified by the id.

Parameters:
id - The id of the desired binding.
Returns:
A reference to the requested binding or null if it is not found.

selectAllNodes

public void selectAllNodes()
Select all nodes.


invertNodeSelection

public void invertNodeSelection()
Unselect all selected nodes and select all unselected ones.


unselectAllComponents

public void unselectAllComponents()
Sets the selection property of every NwComponent to false


focusSelectedNode

public void focusSelectedNode()
Give focus to a selected node. If there is none, focus the DrawPanel.


deleteSelectedNodes

public int deleteSelectedNodes()
Deletes all selected Nodes in the panel.

Returns:
The number of nodes deleted.

moveSelectedNodes

public void moveSelectedNodes(int x,
                              int y)
Move all selected nodes in the panel. If VerinecStudio.isModifyAllowed() is false, will do nothing.

Parameters:
x - Amount to move in direction of x.
y - Amount to move in direction of y.

setZoomFactor

public void setZoomFactor(float factor)
Set the new zoom factor to apply. If you want to set everything to normal, set 1, if you want to zoom out to 25%, send 0.25. To zoom in to 300%, set the factor to 3.

Parameters:
factor - The zoom factor.

getZoomFactor

public float getZoomFactor()
Get the current zoom factor.

1 is no zoom, 2 is zoom 200%, 0.5 is zoom 50% ecc...

Returns:
The current zoom factor.

getScaledSnapRaster

public int getScaledSnapRaster()
Get the snap raster width in pixels, adjusted to current scaling.

Returns:
The snap raster width in pixels.

setEditState

public void setEditState(int s)
Set the current state for the panel. The states are: NOTHING, CREATE, SELECT, MOVE, WIRE. See the constants for details. Setting the state to SELECT will have the side effect of selecting the nodes under the rectangle dragged by the mouse.

Parameters:
s - The new outline state.

getEditState

public int getEditState()
Get the current outline state.

Returns:
The current outline state (one of NOTHING, SELECT, CREATE, MOVE, WIRE)
See Also:
setEditState(int)

setShowNames

public void setShowNames(boolean show)
Hides or shows the node name display.

Parameters:
show - True if names should be shown, false otherwise.

setSnapToGrid

public void setSnapToGrid(boolean snap)
Enables or disables snap to grid behaviour when moving nodes.

Parameters:
snap - Enables snap to grid if true, disables if false.

isSnapToGrid

public boolean isSnapToGrid()
Return whether nodes should snap to grid.

Returns:
True if snap to grid is enabled, false otherwise.

getSnappedCoordinate

public int getSnappedCoordinate(int c)
Rounds the coordinate to the nearest snap point.

Parameters:
c - The coordinate
Returns:
Nearest snap coordinate for c.

getConfigPanel

public ConfigPanel getConfigPanel()
                           throws VerinecException
Return a config panel, as in IVerinecModule.

Specified by:
getConfigPanel in interface IConfigurable
Returns:
A config panel for display options.
Throws:
VerinecException - If the configuration xml can not be found and no default is available.

saveConfiguration

public void saveConfiguration(Document config)
Save the config and update values from xml. Uses initConfig(Document) internally as does the constructor.

Specified by:
saveConfiguration in interface IConfigurable
Parameters:
config - The new configuration.

paint

public void paint(Graphics g)
Adjust the paint method to call paintOverlays after painting of the rest.

Overrides:
paint in class JComponent
Parameters:
g - The graphics object to draw on.

paintComponent

public void paintComponent(Graphics g)
Draws the wires. (Outlines must be drawn separately by call to paintOverlays)

Overrides:
paintComponent in class JComponent
Parameters:
g - The graphics object to draw on.

paintOverlays

public void paintOverlays(Graphics g)
Paint selection rectangle or placement preview.

Parameters:
g - The graphics object to draw on.

drawPreview

private void drawPreview(Graphics g,
                         NwComponent c)
Draw a preview rectangle for a component when dragging nodes.

Parameters:
g - The graphics object to paint on.
c - The component to get the coordinates from.

mousePressed

public void mousePressed(MouseEvent e)
Right click deselects all selected nodes. Otherwise we test the event source and set the state.

Specified by:
mousePressed in interface MouseListener
Parameters:
e - The mouse click event.

mouseReleased

public void mouseReleased(MouseEvent e)
Performs one of the following action according to the type of release.

Specified by:
mouseReleased in interface MouseListener
Parameters:
e - The mouse event.

mouseDragged

public void mouseDragged(MouseEvent e)
Performs one of the following action, according to the type of dragging:

Specified by:
mouseDragged in interface MouseMotionListener
Parameters:
e - The event.

mouseMoved

public void mouseMoved(MouseEvent e)
If we are in create mode - Save Coordinates into variables - repaint the Component to draw the new node outline

Specified by:
mouseMoved in interface MouseMotionListener
Parameters:
e - The event.

mouseCreateMove

private void mouseCreateMove(MouseEvent e)
Execute moving of the preview square. (This is both for mouseMoved and mouseDragged, as the creation occurs when the key is released.)

Parameters:
e - The mouse event.

mouseClicked

public void mouseClicked(MouseEvent e)
Empty procedure, only added because the listener needs it.

Specified by:
mouseClicked in interface MouseListener
Parameters:
e - The event.

mouseExited

public void mouseExited(MouseEvent e)
Repaint the view, just in case

Specified by:
mouseExited in interface MouseListener
Parameters:
e - The event.

mouseEntered

public void mouseEntered(MouseEvent e)
Repaint the view, just in case.

Specified by:
mouseEntered in interface MouseListener
Parameters:
e - The event.

Copyright © 2005 Verinec, DIUF