Jump to content

[Snippet] Marching Ants


Recommended Posts

Posted (edited)

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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