Class Diffusion

java.lang.Object
  |
  +--java.awt.Component
        |
        +--java.awt.Container
              |
              +--java.awt.Panel
                    |
                    +--java.applet.Applet
                          |
                          +--BaseApplet
                                |
                                +--BaseApplet2
                                      |
                                      +--Diffusion

public class Diffusion
extends BaseApplet2
implements java.lang.Runnable

Applet to model diffusion. Displays electrons moving in a rectangular area, plus a temperature slider and momentum histograms.

See Also:
Serialized Form

Inner Class Summary
 class Diffusion.Electron
          Class to simulate a single electron
protected  class Diffusion.TemperatureListener
          Listener to detect changes in the position of the temperature slider.
 
Inner classes inherited from class BaseApplet2
BaseApplet2.FixedButton, BaseApplet2.FixedCheckbox, BaseApplet2.GraphClickListener
 
Inner classes inherited from class BaseApplet
BaseApplet.MozillaWorkaround, BaseApplet.ResizeListener
 
Inner classes inherited from class java.awt.Component
java.awt.Component.AWTTreeLock
 
Field Summary
protected  java.awt.Button animButton
           
protected  java.awt.TextField countField
           
protected  double dt
          The time step to use (default 0.001)
protected  int electronCount
          The number of electrons
protected  java.util.Vector electrons
          A Vector containing all electrons present in the simulation.
protected  int electronSize
          The size (in pixels) of circle to draw for an electron
protected  int h
          Local copy of the height of the display area
protected  int hSpace
           
protected  boolean killed
          true if the animation should terminate at the next available opportunity, otherwise false.
protected  double maxT
          The maximum temperature permitted
protected  double minT
          The minimum temperature permitted
protected  java.awt.Button resetButton
           
protected  double simH
          Width of the box, in simulation units
protected  double simW
          Width of the box, in simulation units
protected  int sliderW
           
protected  int sliderX
           
protected  double temp
          The temperature
protected  java.awt.TextField tempField
           
protected  Diffusion.TemperatureListener tempListener
           
protected  java.lang.Thread thr
          The animation thread, or null if no animation is in progress.
protected  Plotter tPlotter
           
protected  double vMultiplier
          The velocity multiplier.
protected  int vSpace
           
protected  int w
          Local copy of the width of this applet
protected  Histogram xHist
           
protected  Plotter xvPlotter
           
protected  Histogram yHist
           
protected  Plotter yvPlotter
           
 
Fields inherited from class BaseApplet2
boxes, buttons, enablePrompt, fields, focus, panel, statusLabel, useSwing, V_MARGIN
 
Fields inherited from class BaseApplet
buffer, GRAPH_MARGIN, refresh, resizeListener, safetyLimit, useBuffer
 
Fields inherited from class java.applet.Applet
serialVersionUID, stub
 
Fields inherited from class java.awt.Panel
base, nameCounter, serialVersionUID
 
Fields inherited from class java.awt.Container
component, containerListener, containerSerializedDataVersion, dispatcher, layoutMgr, maxSize, ncomponents, serialVersionUID
 
Fields inherited from class java.awt.Component
actionListenerK, adjustmentListenerK, appContext, assert, background, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, changeSupport, componentListener, componentListenerK, componentOrientation, componentSerializedDataVersion, containerListenerK, cursor, dropTarget, enabled, eventMask, focusListener, focusListenerK, font, foreground, hasFocus, height, incRate, inputMethodListener, inputMethodListenerK, isInc, isPacked, itemListenerK, keyListener, keyListenerK, LEFT_ALIGNMENT, locale, LOCK, minSize, mouseListener, mouseListenerK, mouseMotionListener, mouseMotionListenerK, name, nameExplicitlySet, newEventsOnly, ownedWindowK, parent, peer, peerFont, popups, prefSize, RIGHT_ALIGNMENT, serialVersionUID, textListenerK, TOP_ALIGNMENT, valid, visible, width, windowListenerK, x, y
 
Constructor Summary
Diffusion()
           
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent ae)
          Subclasses should at least provide an empty implementation of this method.
 void animate()
          Toggles the animation.
 void doPaint(java.awt.Graphics g)
          Called by forcePaint() to actually perform the painting.
protected  double gaussian()
          Returns a gaussian-distributed random number, using the Box-Muller transform.
 int getCount()
          Returns the number of electrons
 double getT()
          Returns the selected temperature
 void init()
          Performs extra initialisation, including adding a panel to the bottom of the applet.
 void reset()
          Stops any running animation, and generates a new set of electrons with random momentum.
 void run()
          This method loops through an update/repaint cycle.
 void setCount(int i)
          Sets the number of electrons, resetting the simulation if necessary.
 void setT(double t)
          Sets the selected temperature
 void spawnElectrons(int count)
          Destroys any electrons present in the simulation, and replaces them with a new set of electrons, arranged in a square, and with (approximately) gaussian momentum distribution.
 void spawnElectrons(int w, int n, double space)
          Adds electrons to the simulation, arranged in a rectangle.
 void start()
          Applets should use this method to perform any final initialisation necessary to "activate" the applet
 void startAnim()
          Starts the animation.
 void stop()
          When this method is called, the applet should cease any user interaction.
 void stopAnim()
          Stops the animation.
 void updateInput()
          Reads in (and validates) input from the text fields.
 void updateSimulation(double dt)
          Steps through the simulation logic by a specified time step.
 
Methods inherited from class BaseApplet2
add, add, addButton, addCheckbox, addField, addField, addField, addListeners, focusGained, focusLost, getDouble, getGraphHeight, getInt, lockControls, makeButton, makePanel, paintDashedLineH, paintDashedLineV, register, removeListeners, setComponentsEnabled, setLayout, setPromptEnabled, textValueChanged, toString, unlockControls
 
Methods inherited from class BaseApplet
changeFont, forcePaint, getAppletInfo, getParameterInfo, itemStateChanged, paint, refresh, update
 
Methods inherited from class java.applet.Applet
destroy, getAppletContext, getAudioClip, getAudioClip, getCodeBase, getDocumentBase, getImage, getImage, getLocale, getParameter, isActive, newAudioClip, play, play, resize, resize, setStub, showStatus
 
Methods inherited from class java.awt.Panel
, addNotify, constructComponentName
 
Methods inherited from class java.awt.Container
add, add, add, add, addContainerListener, addImpl, applyOrientation, countComponents, deliverEvent, dispatchEventImpl, dispatchEventToSelf, doLayout, eventEnabled, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents_NoClientCode, getComponents, getCursorTarget, getInsets, getLayout, getMaximumSize, getMinimumSize, getMouseEventTarget, getPreferredSize, getWindow, initIDs, insets, invalidate, invalidateTree, isAncestorOf, layout, lightweightPrint, list, list, locate, minimumSize, nextFocus, paintComponents, paramString, postProcessKeyEvent, postsOldMouseEvents, preferredSize, preProcessKeyEvent, print, printComponents, printOneComponent, processContainerEvent, processEvent, proxyEnableEvents, proxyRequestFocus, readObject, remove, remove, removeAll, removeContainerListener, removeNotify, setCursor, setFocusOwner, setFont, transferFocus, updateCursor, validate, validateTree, writeObject
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addPropertyChangeListener, addPropertyChangeListener, areInputMethodsEnabled, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, getBackground, getBounds, getBounds, getColorModel, getComponentOrientation, getCursor, getDropTarget, getFont_NoClientCode, getFont, getFontMetrics, getForeground, getGraphics, getHeight, getInputContext, getInputMethodRequests, getIntrinsicCursor, getLocation, getLocation, getLocationOnScreen, getName, getNativeContainer, getParent_NoClientCode, getParent, getPeer, getSize, getSize, getToolkit, getToolkitImpl, getTreeLock, getWidth, getWindowForObject, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isDisplayable, isDoubleBuffered, isEnabled, isEnabledImpl, isFocusTraversable, isLightweight, isOpaque, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, remove, removeComponentListener, removeFocusListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, reshape, setBackground, setBounds, setBounds, setComponentOrientation, setDropTarget, setEnabled, setForeground, setLocale, setLocation, setLocation, setName, setSize, setSize, setVisible, show, show, size, toString, transferFocus
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, registerNatives, wait, wait, wait
 

Field Detail

sliderW

protected int sliderW

sliderX

protected int sliderX

hSpace

protected int hSpace

vSpace

protected int vSpace

electronCount

protected int electronCount
The number of electrons

thr

protected java.lang.Thread thr
The animation thread, or null if no animation is in progress.

killed

protected boolean killed
true if the animation should terminate at the next available opportunity, otherwise false.

electrons

protected java.util.Vector electrons
A Vector containing all electrons present in the simulation.

electronSize

protected int electronSize
The size (in pixels) of circle to draw for an electron

w

protected int w
Local copy of the width of this applet

h

protected int h
Local copy of the height of the display area

simW

protected double simW
Width of the box, in simulation units

simH

protected double simH
Width of the box, in simulation units

dt

protected double dt
The time step to use (default 0.001)

temp

protected double temp
The temperature

vMultiplier

protected double vMultiplier
The velocity multiplier. Rather than adjusting the momentum of every electron whenever the temperature is changed, a constant multiplier is applied to all velocities. If the velocities were modified directly, inaccuracies would creep in quite rapidly (temperature changes every time slider is "seen" in a different position).

minT

protected double minT
The minimum temperature permitted

maxT

protected double maxT
The maximum temperature permitted

animButton

protected java.awt.Button animButton

resetButton

protected java.awt.Button resetButton

tempField

protected java.awt.TextField tempField

countField

protected java.awt.TextField countField

tempListener

protected Diffusion.TemperatureListener tempListener

tPlotter

protected Plotter tPlotter

xvPlotter

protected Plotter xvPlotter

yvPlotter

protected Plotter yvPlotter

xHist

protected Histogram xHist

yHist

protected Histogram yHist
Constructor Detail

Diffusion

public Diffusion()
Method Detail

init

public void init()
Description copied from class: BaseApplet2
Performs extra initialisation, including adding a panel to the bottom of the applet.
Overrides:
init in class BaseApplet2

start

public void start()
Description copied from class: BaseApplet
Applets should use this method to perform any final initialisation necessary to "activate" the applet
Overrides:
start in class BaseApplet2

stop

public void stop()
Description copied from class: BaseApplet
When this method is called, the applet should cease any user interaction. In particular, any threads explicitly started should be stopped, any external resources should be closed. This method should negate the action of start().
Overrides:
stop in class BaseApplet2

startAnim

public void startAnim()
Starts the animation. This method will have no effect if the animation is already in progress.

stopAnim

public void stopAnim()
Stops the animation. This method will have no effect if the animation is not in progress.

run

public void run()
This method loops through an update/repaint cycle. It is intended to execute in a separate thread, so should not be invoked directly. Instead, the startAnim() method should be used, which will start this method in a new thread.
Specified by:
run in interface java.lang.Runnable

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent ae)
Description copied from class: BaseApplet
Subclasses should at least provide an empty implementation of this method.
Overrides:
actionPerformed in class BaseApplet

updateInput

public void updateInput()
Reads in (and validates) input from the text fields.
Throws:
java.lang.IllegalArgumentException - if any input fields are invalid

animate

public void animate()
Toggles the animation. If the animation is running, it will be stopped, otherwise a new animation will be started.

reset

public void reset()
Stops any running animation, and generates a new set of electrons with random momentum. The momentum components of the electrons will follow an approximate gaussian distribution; the positions will be so as to arrange the particles in an approximate square.

doPaint

public void doPaint(java.awt.Graphics g)
Description copied from class: BaseApplet
Called by forcePaint() to actually perform the painting. Subclasses should implement this method as if it were the standard paint() method; buffering will then take place transparently.
Overrides:
doPaint in class BaseApplet
Tags copied from class: BaseApplet
Parameters:
g - The Graphics object on which to paint

updateSimulation

public void updateSimulation(double dt)
Steps through the simulation logic by a specified time step. Any size of step can be chosen, with the proviso that it should be sufficiently small that no particle can travel the entire distance between two opposite walls within that time.
Parameters:
dt - the size of the time interval to consider

spawnElectrons

public void spawnElectrons(int count)
Destroys any electrons present in the simulation, and replaces them with a new set of electrons, arranged in a square, and with (approximately) gaussian momentum distribution.
Parameters:
count - the number of electrons to create

spawnElectrons

public void spawnElectrons(int w,
                           int n,
                           double space)
Adds electrons to the simulation, arranged in a rectangle.
Parameters:
n - The number of electrons to add
w - The number of electrons per row
space - The spacing (simulation units) between electrons

gaussian

protected double gaussian()
Returns a gaussian-distributed random number, using the Box-Muller transform.

getT

public double getT()
Returns the selected temperature

setT

public void setT(double t)
Sets the selected temperature

getCount

public int getCount()
Returns the number of electrons

setCount

public void setCount(int i)
Sets the number of electrons, resetting the simulation if necessary.