how to randomly open up lines for maze in java - java

I am making a maze and I would like to use the recursive method as defined here. However, I need some help as to how to randomly open up the lines once I randomly draw them. Right now I'm creating the lines (walls of the maze) simply by drawing them with their beginning and end x- and y-coordinates. I just can't seem to find a simple way to "erase" (or "open up") parts of the lines.
EDIT: Okay I need to be slightly more specific. How could I randomly select places on each line to "open up?"
EDIT 2: Here is some code of what I'm trying to do:
public static void draw() {
// picks a random spot in the rectangle
Random r = new Random();
int x0 = r.nextInt(w)
int y0 = r.nextInt(h)
// draws the 4 lines that are perpendicular to each other and meet
// at the selected point
StdDraw.line(x0, 0, x0, y0);
StdDraw.line(0, y0, x0, y0);
StdDraw.line(x0, h, x0, y0);
StdDraw.line(w, y0, x0, y0);
}
public static void main(String[] args) {
// set up the walls of the maze
// given w = width and h = height
StdDraw.setXscale(0, w);
StdDraw.setYscale(0, h);
StdDraw.line(0, 0, 0, h);
StdDraw.line(0, h, w, h);
StdDraw.line(w, h, w, 0);
StdDraw.line(w, 0, 0, 0);
draw();
}
Now I just need to figure out how to randomly select 3 of these lines, and for each line randomly erase a portion.

Assuming you're using swing and the paintComponent method, you would set the Graphic's color to the background color and draw over the line again. Here's an example:
public class DrawTest extends JPanel{
public static void main(String[] args)
{
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public Dimension getPreferredSize(){
return new Dimension(400,300);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(10, 10, 100, 10);
g.setColor(getBackground());
g.drawLine(50, 10, 60, 10);
}
}
EDIT
I suppose you're not creating the Maze in the paintComponent method (or you'd end up with a new maze every time you repainted). So, I'd recommend creating a sub-class similar to below and storing instances of it in an ArrayList field of your main class. Then you can iterate through your ArrayList when you're doing your panting.
public static class MazeWall{
public static final int OpeningWidth = 10;
Point start;
Point end;
Point opening;
public MazeWall(Point start, Point end, boolean hasOpening){
this.start = start;
this.end = end;
if(hasOpening){
int range;
if(start.x == end.x){
range = end.x - start.x - OpeningWidth;
int location = (int)(Math.random() * range + start.x);
opening = new Point(location, start.y);
} else{
range = end.y - start.y - OpeningWidth;
int location = (int)(Math.random() * range + start.y);
opening = new Point(location, start.x);
}
}
}
}

Related

Baking the arrays on screen with Processing

I like working with Processing array functions but when I draw things using this function, I realize it's storing every single drawn shape in the memory, which is causing spikes in CPU. (Especially when it goes up to a few thousands)
How to bake the drawing then remove the array objects on mouserelease? I mean, can Processing behave those objects as a single image after every stroke then I'd clear the array using .remove(0) function?
Here's my code:
ArrayList <Drawing> drawings = new ArrayList <Drawing>();
void setup() {
size(400, 400);
background(255);
colorMode(HSB);
}
void draw() {
background(255);
for (int i=0;i<drawings.size();i++) {
drawings.get(i).display();
}
println(drawings.size());
}
void mouseDragged() {
drawings.add(new Drawing(mouseX, mouseY));
}
class Drawing {
float x, y, r;
color c;
Drawing(float ax, float ay) {
x=ax;
y=ay;
r=random(2, 20);
c=color(random(100, 200), 255, 255, 88);
}
void display() {
noStroke();
fill(c, 100);
ellipse(x,y, r, r);
}
}
If you want to store the objects into the ArrayList only while the mouse is pressed (drawing new objects) and just have all the old objects to be static on the background out of the ArrayList you can do something like this:
ArrayList<Drawing> drawings = new ArrayList();
boolean flag = false;
void setup()
{
size(400, 400);
background(255);
colorMode(HSB);
loadPixels();
}
void draw()
{
updatePixels();
if(flag)
{
for(Drawing drawing : drawings)
{
drawing.display();
}
}
println(drawings.size());
}
void mouseDragged()
{
flag = true;
Drawing drawing = new Drawing(mouseX, mouseY);
drawings.add(drawing);
}
void mouseReleased()
{
flag = false;
loadPixels();
drawings = new ArrayList();
}
class Drawing
{
float x, y, r;
color c;
Drawing(float ax, float ay)
{
x=ax;
y=ay;
r=random(2, 20);
c=color(random(100, 200), 255, 255, 88);
}
public void display()
{
noStroke();
fill(c, 100);
ellipse(x,y, r, r);
}
}
The function loadPixels() stores into the pixels[] array all the pixels of the screen, while updatePixels() draws the pixels in pixels[] on the canvas. This way you can just empty your ArrayList every time the mouse is released and, even though when the ArrayList gets some thousands of elements you still get some CPU spikes, when the mouse is not being dragged or the ArrayList has less than a couple thousands of elements it is less CPU consuming.
If you don't need to access the drawings objects later (say to change properties), you can simply cache the rendering onto a separate PGraphics layer:
PGraphics drawings;
void setup() {
size(400, 400);
colorMode(HSB);
drawings = createGraphics(width, height);
// use drawing commands between beginDraw() / endDraw() calls
drawings.beginDraw();
drawings.background(255);
drawings.colorMode(HSB);
drawings.noStroke();
drawings.endDraw();
}
void draw() {
background(255);
// PGraphics extends PImage so you can render it the same way
image(drawings, 0, 0);
println((int)frameRate);
}
void mouseDragged() {
drawRandomCircle(drawings, mouseX, mouseY);
}
void drawRandomCircle(PGraphics layer, float x, float y){
float diameter = random(2, 20);
layer.beginDraw();
layer.fill(color(random(100, 200), 255, 255, 88));
layer.ellipse(x, y, diameter, diameter);
layer.endDraw();
}
Otherwise you can make use of PShape:
PShape drawings;
void setup() {
size(400, 400, P2D);
smooth();
background(255);
colorMode(HSB);
// create a PShape group to append circles to later
drawings = createShape(GROUP);
}
void draw() {
background(255);
// render PShape
shape(drawings);
println(drawings.getChildCount() + " shapes at ~" + (int)frameRate + "fps");
}
void mouseDragged() {
drawings.addChild(addRandomCircle(mouseX, mouseY));
}
PShape addRandomCircle(float x, float y){
float diameter = random(2, 20);
// create an ellipse PShape with the desired dimensions, position, fill and (no)stroke
PShape circle = createShape(ELLIPSE, x, y, diameter, diameter);
circle.setFill(color(random(100, 200), 255, 255, 88));
circle.setStroke(false);
return circle;
}
As mentioned in my comment check out Processing > Examples > Demos > Performance > StaticParticlesRetained
If you need later access to each added circle/drawing you can iterate over the parent PShape:
// iterate though nested PShapes
for(int i = 0 ; i < drawings.getChildCount(); i++){
// access each PShape
PShape drawing = drawings.getChild(i);
// access PShape properties
println("drawings[" + i + "] has " + drawing.getVertexCount() + " vertices");
}
Should you need extra functionality (like a separate property to animate), you can always extend PShape: re-use what's already there add what you need on top:
PShape drawings;
void setup() {
size(400, 400, P2D);
smooth();
background(255);
colorMode(HSB);
// create a PShape group to append circles to later
drawings = createShape(GROUP);
}
void draw() {
background(255);
// use custom functionality
for(int i = 0 ; i < drawings.getChildCount(); i++){
// cast from PShape superclass to the custom Drawing subclass
Drawing drawing = (Drawing)drawings.getChild(i);
// use the custom functionality
drawing.update(i);
}
// render PShape
shape(drawings);
println(drawings.getChildCount() + " shapes at ~" + (int)frameRate + "fps");
}
void mouseDragged() {
drawings.addChild(new Drawing((PGraphicsOpenGL)g, mouseX, mouseY));
}
class Drawing extends PShapeOpenGL{
float x, y, diameter;
Drawing(PGraphicsOpenGL pg, float x, float y){
// call PShape super constructor setting this as a primitive (e.g. POINT, LINE, RECT, ELLIPSE, etc.)
super(pg, PShape.PRIMITIVE);
setKind(ELLIPSE);
diameter = random(2, 20);
// set (ellipse) shape parameters
setParams(new float[]{x, y, diameter, diameter});
// fill
setFill(color(random(100, 200), 255, 255, 88));
// disable stroke
setStroke(false);
// remember original position
this.x = x;
this.y = y;
}
// a custom functionality on top of PShape
void update(int index){
float offset = map(sin((frameCount + ((index+1) * 10)) * 0.025), -1.0, 1.0, -15, 15);
// reset transformations
this.resetMatrix();
// translate backwards
this.translate(-x, -y);
// translate back + the offset
this.translate(x + offset, y);
}
}
For the full list of functionalities see PShape javadocs
Starting with the simplest thing though. If you want to simply render many shapes without changing them later PGraphics will do the trick

How to use AffineTransform with very little coordinates?

I have a set of two dimensions points. Their X and Y are greater than -2 and lesser than 2. Such point could be : (-0.00012 ; 1.2334 ).
I would want to display these points on a graph, using rectangles (a rectangle illustrates a point, and has its coordinates set to its point's ones - moreover, it has a size of 10*10).
Rectangles like (... ; Y) should be displayed above any rectangles like (... ; Y-1) (positive Y direction is up). Thus, I must set the graph's origin not at the top-left hand-corner, but somewhere else.
I'm trying to use Graphics2D's AffineTransform to do that.
I get the minimal value for all the X coordinates
I get the minimal value for all the Y coordinates
I get the maximal value for all the X coordinates
I get the maximal value for all the Y coordinates
I get the distance xmax-xmin and ymax-ymin
Then, I wrote the code I give you below.
Screenshots
Some days ago, using my own method to scale, I had this graph:
(so as I explained, Y are inverted and that's not a good thing)
For the moment, i.e., with the code I give you below, I have only one point that takes all the graph's place! Not good at all.
I would want to have:
(without lines, and without graph's axis. The important here is that points are correctly displayed, according to their coordinates).
Code
To get min and max coordinates value:
x_min = Double.parseDouble((String) list_all_points.get(0).get(0));
x_max = Double.parseDouble((String) list_all_points.get(0).get(0));
y_min = Double.parseDouble((String) list_all_points.get(0).get(1));
y_max = Double.parseDouble((String) list_all_points.get(0).get(1));
for(StorableData s : list_all_points) {
if(Double.parseDouble((String) s.get(0)) < x_min) {
x_min = Double.parseDouble((String) s.get(0));
}
if(Double.parseDouble((String) s.get(0)) > x_max) {
x_max = Double.parseDouble((String) s.get(0));
}
if(Double.parseDouble((String) s.get(1)) < y_min) {
y_min = Double.parseDouble((String) s.get(1));
}
if(Double.parseDouble((String) s.get(1)) > y_max) {
y_max = Double.parseDouble((String) s.get(1));
}
}
To draw a point:
int x, y;
private void drawPoint(Cupple storable_data) {
//x = (int) (storable_data.getNumber(0) * scaling_coef + move_x);
//y = (int) (storable_data.getNumber(1) * scaling_coef + move_y);
x = storable_data.getNumber(0).intValue();
y = storable_data.getNumber(1).intValue();
graphics.fillRect(x, y, 10, 10);
graphics.drawString(storable_data.toString(), x - 5, y - 5);
}
To paint the graph:
#Override
public void paint(Graphics graphics) {
this.graphics = graphics;
Graphics2D graphics_2d = ((Graphics2D) this.graphics);
AffineTransform affine_transform = graphics_2d.getTransform();
affine_transform.scale(getWidth()/(x_max - x_min), getHeight()/(y_max - y_min));
affine_transform.translate(x_min, y_min);
graphics_2d.transform(affine_transform);
for(StorableData storable_data : list_all_points) {
graphics_2d.setColor(Color.WHITE);
this.drawPoint((Cupple) storable_data);
}
I suggest you map each data point to a point on the screen, thus avoiding the following coordinate system pitfalls. Take your list of points and create from them a list of points to draw. Take into account that:
The drawing is pixel-based, so you will want to scale your points (or you would have rectangles 1 to 4 pixels wide...).
You will need to translate all your points because negative values will be outside the boundaries of the component on which you draw.
The direction of the y axis is reversed in the drawing coordinates.
Once that is done, use the new list of points for the drawing and the initial one for calculations. Here is an example:
public class Graph extends JPanel {
private static int gridSize = 6;
private static int scale = 100;
private static int size = gridSize * scale;
private static int translate = size / 2;
private static int pointSize = 10;
List<Point> dataPoints, scaledPoints;
Graph() {
setBackground(Color.WHITE);
// points taken from your example
Point p1 = new Point(-1, -2);
Point p2 = new Point(-1, 0);
Point p3 = new Point(1, 0);
Point p4 = new Point(1, -2);
dataPoints = Arrays.asList(p1, p2, p3, p4);
scaledPoints = dataPoints.stream()
.map(p -> new Point(p.x * scale + translate, -p.y * scale + translate))
.collect(Collectors.toList());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(size, size);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// draw a grid
for (int i = 0; i < gridSize; i++) {
g2d.drawLine(i * scale, 0, i * scale, size);
g2d.drawLine(0, i * scale, size, i * scale);
}
// draw the rectangle
g2d.setPaint(Color.RED);
g2d.drawPolygon(scaledPoints.stream().mapToInt(p -> p.x).toArray(),
scaledPoints.stream().mapToInt(p -> p.y).toArray(),
scaledPoints.size());
// draw the points
g2d.setPaint(Color.BLUE);
// origin
g2d.fillRect(translate, translate, pointSize, pointSize);
g2d.drawString("(0, 0)", translate, translate);
// data
for (int i = 0; i < dataPoints.size(); i++) {
Point sp = scaledPoints.get(i);
Point dp = dataPoints.get(i);
g2d.fillRect(sp.x, sp.y, pointSize, pointSize);
g2d.drawString("(" + dp.x + ", " + dp.y + ")", sp.x, sp.y);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new Graph());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
And another:
You might want to have the points aligned on the grid intersections and not below and to the right of them. I trust you will figure this one out.
Also, I ordered the points so that drawPolygon will paint the lines in the correct order. If your points are arbitrarily arranged, look for ways to find the outline. If you want lines between all points like in your example, iterate over all combinations of them with drawLine.

Way to repaint this JPanel after given count

Hello I would like to prevent graphics drawing and drawing again but I don't know how to do, I just want my panel delete all painted graphics and restart with same code. I tried some methods posted here but no one does the job.
public class Main extends JPanel implements ActionListener {
Timer timer;
private double angle = 444;
private double scale = 1;
private double delta = 0.0001;
RoundRectangle2D.Float r = new RoundRectangle2D.Float();
int counter = 0;
public Main() {
timer = new Timer(55, this);
timer.start();
}
public void paint(Graphics g) {
counter++;
int h = getHeight();
int w = getWidth();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(randomNumber(0, 155), randomNumber(0, 255),randomNumber(0, 155), randomNumber(0, 255)));
drawCircles(g2d, getWidth()/2, getHeight()/2, 250);
if(counter > 200){
g2d.clearRect (0, 0, getWidth(), getHeight());
super.paintComponent(g2d);
counter = 0;
}
}
public int randomNumber(int min, int max) {
int c = new Random().nextInt((max - min) + 1);
return c;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setUndecorated(true);
Dimension dim = new Dimension(Toolkit.getDefaultToolkit()
.getScreenSize().width, Toolkit.getDefaultToolkit()
.getScreenSize().height);
frame.setSize(dim);
frame.setLocation(0, 0);
frame.setBackground(new Color(0, 0, 0, 255));
frame.add(new Main());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
void drawCircles(Graphics graphics, int xMid, int yMid, int radius) {
// end recursion
if(radius < 5)
return;
// Draw circle
// start recursion
//left
drawCircles(graphics, xMid-radius, yMid, radius / 2);
((Graphics2D) graphics).rotate(angle);
graphics.drawOval(xMid - radius, yMid - radius, radius * 2, radius * 2);
//right
drawCircles(graphics, xMid+radius, yMid, radius / 2);
graphics.drawOval(xMid - radius, yMid - radius, radius * 2, radius * 2);
((Graphics2D) graphics).rotate(angle);
((Graphics2D) graphics).rotate(angle);
((Graphics2D) graphics).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) graphics).setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
}
public void actionPerformed(ActionEvent e) {
if (scale < 0.01)
delta = -delta;
else if (scale > 0.99)
delta = -delta;
scale += delta;
angle += 0.001;
repaint();
}
}
I am not sure I understand you fully, but you can use a JToggleButton (for example) where is the toggle button is down it prevents drawing. I can see something like this inside your drawCircles() method:
void drawCircles(Graphics graphics, int xMid, int yMid, int radius)
{
if(!toggleBtn.isSelected() // the toggle button is pressed
{
// draw something
}
}
In your example, you are drawing two circles and two ovals. If I understood you correctly, you want to be able to pause in the middle of the method, for example, and only draw the first circle. Then, at some point, you want to continue drawing the two ovals and the remaining circle. Unfortunately, you cannot do that. You cannot stop (or pause) a method in the middle of it.
Methods have to execute to completion (whether to the end, or an exception is thrown). However, you can create some kind of task to draw ONE shape (for example, a circle). If you create multiple tasks, you can draw many circles. To accomplish this, you will need to learn about Concurrency and probably about Java Tasks. You can have these tasks execute in some kind of order and because of concurrency, you could pause and resume these drawing tasks the way I think you would want.

Zooming In On a Java Graphic

I am making a graph of a sound speed profile with java graphics. I have the static graph drawn (the one that pops up when you run the program), but I am trying to implement it such that if the user clicks on either the x or y axis, then it will zoom in so you can look at the sound speed profile more closely. I don't have the sound speed profile in the graph yet (I already know how to do that, I'm just saving the effort of drawing it until I have the zoom feature figured out). Does anyone have any ideas as to how to make this work? I have seen people trying to use the Affine Transform for similar tasks, but I am not sure that's the right thing to do or if I'm even doing this correctly. The particular code to look at is the paint(), zoomIn(), and mouseClicked() method. Ideas would be much apprecaited!
public class SoundSpeedProfile extends JPanel implements MouseListener, ActionListener {
private String title;
private String subTitle;
private JFrame frame;
private Graphics g;
.
.
.
/**Draws the sound speed profile and surrounding graphics
* #param Graphics g - graphics object
*/
public void paint(Graphics g){
this.g = g;
super.paint(g); //the super knows how to draw "standard" components like squares, rectangles, circles, etc
g.setColor(Color.DARK_GRAY);
//1) Set up the graph the sound speed profile lives in
//X-Axis for Speeds
g.drawLine(100, 150, 450, 150);//the graphics display has 0,0 in the upper left corner versus the lower left corner
int i = 120;
int k = 1460;
while (i<440){
g.drawString("|", i, 155);
g.drawString("" + k + "", i-2, 140);
k = k + 20;
i = i + 60;
}
//Y-Axis
g.drawLine(100, 500, 100, 150);
k= 7000;
int j = 500;
while (j>160){
g.drawString("" + k, 60, j);
g.drawString("--", 94, j);
k = k - 1000;
j = j - 50;
}
Font f1 = new Font("Serif", 4, 15);
g.setFont(f1);
g.drawString(this.title, 200,30);//Graph Title
g.drawString(this.subTitle, 225, 50);
Font f2 = new Font("Serif", 2, 15);
g.setFont(f2);
g.drawString("Sound Speed ", 200, 110);//x-axis label
g.drawString("(" + spdUnits + ")", 290, 110); //Units label--taken from input array
g.drawString("Depth", 10, 180); //y-axis label
g.drawString("(" + depUnits + ")", 07, 200); //Units label--taken from input array
//((Graphics2D)g).scale(20, 20);
}
/**Creates and shows the GUI drawing of the sound speed profile in a JFrame
*/
private void createAndShowGUI(){
frame = new JFrame("Sound Speed Profile");
canvas = new Canvas();
frame.add(canvas);
frame.addMouseListener(this);
frame.setBackground(Color.cyan);
frame.setSize(600,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);//add the sound speed profile graphic and set a Border Layout
//frame.pack();
frame.setVisible(true);
}
/**
* Runs test cases
* #param args
*/
public static void main (String [] args){
ssp.setTitle("Sound Speed Profile 1");
ssp.setSubtitle("June 1, 2012");
ssp.createAndShowGUI();
ssp.repaint(); //necessary?
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
int x = arg0.getX();
//System.out.println("x: " + x);
int xMin = x - 50;
int xMax = x + 50;
int y = arg0.getY();
//System.out.println("y: " + y);
int yMin = y-50;
int yMax = y + 50;
//If the user clicked on the x-axis
if ( 160<y && y<180 && 100<x && x<450){
System.out.println("About to zoom in on the x-axis");
zoomIn(x, y);
//System.out.println("zooming in on the x-axis");
}
//If the user clicked on the y-axis
if (90<x && x<110 && 150 <y && y<500){
//System.out.println("zooming in on the y-axis");
}
}
public void zoomIn(int x, int y){
AffineTransform old = ((Graphics2D) g).getTransform();
for (double zoom = 1; zoom >=0.1; zoom=-0.1){
AffineTransform tr2 =AffineTransform.getTranslateInstance(-x, -y);
AffineTransform tr= AffineTransform.getScaleInstance(zoom,zoom);
tr.concatenate(tr2); tr2=tr;
tr =AffineTransform.getTranslateInstance(x, y);
tr.concatenate(tr2); tr2=tr;
tr= new AffineTransform(old);
tr.concatenate(tr2); tr2=tr;
((Graphics2D)g).setTransform(tr2);
((Graphics2D)g).drawRect(x, y, 10, 10);
((Graphics2D)g).setTransform(old);
}
}

How do you move an object in a wavy pattern?

I know the following code will move an object in a straight line. How can I get the object to travel in a wavy line? I know that something extra is required for the x variable.
public void draw(Graphics2D g)
{
g.setColor(Color.WHITE);
g.fillOval ((int) (x - r), (int) (y - r), (int)
(2 * r),
(int) (2 * r));
y++;
if (y - r > height)
y = -r;
}
Use the sine or cosine function to calculate y as a function of x.
Multiply the sine or cosine function to increase the amplitude (how high it goes)
y = 100 * sin(x) // will make it have peaks of -100 and 100
Divide the x to increase the period. (distance between peaks)
y = sin(x/2) // will make it take twice the x distance between peaks.
Something like this:
public void draw(Graphics2D g)
{
g.setColor(Color.WHITE);
g.fillOval ((int) (x - r), (int) (y - r), (int)
(2 * r),
(int) (2 * r));
x++; // Left to right movement
// Example, modify the multipliers as necessary
y = 100 * Math.sin(Math.toDegrees(x/4))
}
Including a sin(x) or cos(x) in your function will provide a regular wave pattern, irregular pattern needs a more sophisticated function
I know you already accepted an answer, but here's something to draw additional inspiration from that I whipped up...
package wavy;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Wavy {
public static void main(String[] args) {
final JFrame frame = new JFrame("Wavy!");
final WavyPanel wp = new WavyPanel();
frame.getContentPane().add(wp, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Ticker t = new Ticker(wp);
final Repainter r = new Repainter(wp);
frame.pack();
frame.setVisible(true);
final Timer tickTimer = new Timer();
final Timer paintTimer = new Timer();
paintTimer.schedule(r, 1000, 50);
tickTimer.schedule(t, 1000, 10);
}
private static class WavyPanel extends JPanel {
private final Dimension size = new Dimension(640, 480);
private int amplitude = 50;
private int frequency = 5;
private int x = 0;
private double y = size.height / 2;
private int yBase = 0;
WavyPanel() {
super(true);
}
#Override
protected void paintComponent(final Graphics g) {
final Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, size.width, size.height);
g2.setColor(Color.BLACK);
g2.fillOval(x, (int)y, 30, 30);
}
#Override
public Dimension getPreferredSize() {
return size;
}
#Override
public Dimension getMinimumSize() {
return size;
}
#Override
public Dimension getMaximumSize() {
return size;
}
public void tick() {
//Move a pixel to the right; loop over to the left when reaching edge
x = (++x) % size.width;
//Length of one full wave = panel width divided by frequency
final int waveLength = size.width / frequency;
//Incrementing yBase; capping off at wavelength
yBase = (++yBase) % waveLength;
//Normalizing to [0..1]
final double normalized = (double)yBase / (double)waveLength;
//Full wave at 2*pi, means...
final double radians = normalized * Math.PI * 2;
//Getting the sine
final double sine = Math.sin(radians);
//Multiplying with amplitude, add to center position and we have our y
y = (int)(sine * amplitude) + size.height/2;
}
}
private static class Ticker extends TimerTask {
private final WavyPanel panel;
Ticker(final WavyPanel panel) {
this.panel = panel;
}
#Override
public void run() {
panel.tick();
}
}
private static class Repainter extends TimerTask {
private final WavyPanel panel;
Repainter(final WavyPanel panel) {
this.panel = panel;
}
#Override
public void run() {
panel.repaint();
}
}
}
This should run at an approximate 20 frames per second. You can increase this by setting the second argument of paintTimer.schedule(r, 1000, 50) lower. The speed of movement can be altered by lowering (speeding up) or increasing (slower) the second argument of tickTimer.schedule(t, 1000, 50).
Changing the amplitude field of WavyPanel will change how high/low the circle moves. Changing the frequency to a higher value will result in shorter waves, while a lower value will produce longer waves.
With some additional work you could add in controls to change the amplitude and frequency on-the-fly. Some additional notes:
You may wish to add some safeguard to the tick() method to make sure that when one invocation is already running, additional ones are skipped until the first one is done. Otherwise the calculations could fail for short tick intervals. A semaphore could be used here.
Since trigonometric calculations aren't exactly the cheapest, you may consider caching some results (e.g. in an array) for re-use if many similar animations are to be played or if there's a lot more drawing going on.
I hope I'm interpreting this right. Could use the sine or cosine of either your x or y coordinate. I'm not at a machine with java so I can't make an example at the moment..
You're right that you need to update both the x and y variables to get a wavy line. Here's the general strategy for a horizontal line that is wavy up and down:
Choose a function f(x) that has the shape you want. This will be used to calculate values for y. (For instance, you can use y = amplitude * Math.sin(frequency * x) to get a regular sine wave of a given amplitude and frequency.)
If necessary, write the code that implements your function.
Set x to some initial value.
In draw, before you paint the oval, calculate y = f(x);. Paint the oval and then increment x. If necessary, reset x so it stays in range.
If you want a vertical line that is wavy left and right, just reverse the roles of x and y in the above. If you want the oval to go in the reverse direction, just decrement instead of increment in step 4.
this sample is for point(Line with one length) on sinus graph and clock using.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RunSwing extends JPanel {
static int x1 = 500;
static int y1 = 500;
static int x2 = x1;
static int y2 = y1;
final static int vectorLength = 100;
final static int sinx2 = x2;
final static int siny2 = y2;
static double count = 0;
private static RunSwing run = new RunSwing();
final Timer print = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
//increaseSinusGraph();
increaseClockVector();
count+=6; //for clock for 1 second
/*count++;//for sinus*/
if (count % 360 == 0)
System.out.println((count / 360) + " minute passed");
}
});
RunSwing() {
print.start();
}
public static void main(String[] args) {
JFrame frame = new JFrame("amir");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(run);
frame.setSize(1100, 700);
frame.setVisible(true);
}
static void increaseClockVector() {
double cos = Math.cos(Math.toRadians(count));
double sin = Math.sin(Math.toRadians(count));
y2 = siny2 + (int) (vectorLength * sin);
x2 = sinx2 + (int) (vectorLength * cos);
}
static void increaseSinusGraph() {
double sin = Math.sin(Math.toRadians(count));
y2 = siny2 + (int) (vectorLength * sin);
x2++;
}
private void createPoint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(x2, y2, x2 + 1, y2 + 1);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0, 0, 0));
g.drawLine(x1, y1, x2, y2);//for clock
/*g.drawLine(x2, y2, x2+1, y2+1);//for sinus*/
repaint();
}
}

Categories

Resources