Jump to content

[Snippet] Marching Ants


Botre

Recommended Posts

b9696f04c71b846b7d7d1c088d7b50da.gif

 

Class:

package temp;

import java.awt.BasicStroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import javax.swing.Timer;

public class MarchingAnts extends Observable {

	private BasicStroke stroke;

	private float dashPhase = 0f;
	private float dash[] = {5.0f,5.0f};

	private ActionListener listener = new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent ae) {
			dashPhase += 9.0f;
			stroke = new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 1.5f,  dash, dashPhase);
			setChanged();
			notifyObservers();
		}
	};

	public MarchingAnts() {
		stroke = new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 1.5f,  dash, dashPhase);
	}

	private Timer timer = new Timer(40, listener);

	public BasicStroke getStroke() {
		return stroke;
	}

	public void startAnimation() {
		timer.start();
	}

	public void stopAnimation() {
		timer.stop();
	}

}

Example:

//Declare
private MarchingAnts ants = new MarchingAnts();

...

//Start animation
ants.startAnimation();

...

//Add observers
ants.addObserver((obj, obs) -> repaint()); //repaint() method from a painting component

...

//Use stroke
g2d.setStroke(ants.getStroke());
Edited by Botre
  • Like 5
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...