1

I have a JPanel 200x200.

I trying to create a function that will generate random parabola's with the bounds of the JPanel, with a constraint that the height can't be lower than a 100 (middle of the screen), I basically want to move a shape around these parabolas

parabolas

Here is some code I'm using to get started:

Random random = new Random(); int y; int x;
int size = random.nextInt(10);
int translation = random.nextInt(50);
int height = random.nextInt(100) - 200; //between 100 and 200

//Parabola functions : y = ((x/7 - 30))^2

// x and y are coordiates of where the shape is drawn

while(y != 200){
y = (float)Math.pow((float)xloc / size - translation ,2) + height;
x++;
}

I've been researching about FlatteningPathIterator but not too sure how to use them. my function

y = (float)Math.pow((float)xloc / size - translation ,2) + height;`

prints parabola's sometimes outside the bounds, how would i edit it to print parabola's inside the bounds?

  • *"Any suggestions?"* 1) For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). 2) Add a more specific question. Besides being a lazy question "Any suggestions?" is too broad. – Andrew Thompson Mar 07 '14 at 02:29
  • 1
    This [example](http://stackoverflow.com/a/20107935/230513) scales the result to the enclosing container. – trashgod Mar 07 '14 at 02:58

1 Answers1

1

There is a Java Swing shape generator for this called Quad2dCurve. The getPathIterator call gives you an enumerator for points on the curve.

Here is some example code:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;

final class TestCanvas extends JComponent {

    int size = 200;
    int n = 10;
    float[] ph = new float[n];
    float[] pw = new float[n];
    float[] px = new float[n];
    Random gen = new Random();

    TestCanvas() {
        makeRandomParabolas();
        setFocusable(true);
        addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                makeRandomParabolas();
                repaint();
                float [] coords = new float [6];
                for (int i = 0; i < n; i++) {
                    PathIterator pi = getQuadCurve(i).getPathIterator(null, 0.1);
                    System.out.print(i + ":");
                    while (!pi.isDone()) {
                        switch (pi.currentSegment(coords)) {
                            case PathIterator.SEG_MOVETO:
                                System.out.print(" move to");
                                break;
                            case PathIterator.SEG_LINETO:
                                System.out.print(" line to");
                                break;
                            default:
                                System.out.print(" unexpected");
                                break;
                        }
                        System.out.println(" (" + coords[0] + "," + coords[1]+")");
                        pi.next();
                    }
                    System.out.println();
                }
            }
        });
    }

    QuadCurve2D.Float getQuadCurve(int i) {
        return new QuadCurve2D.Float(px[i] - pw[i], size,
                px[i], size - (2 * ph[i]),
                px[i] + pw[i], size);
    }

    void makeRandomParabolas() {
        for (int i = 0; i < n; i++) {
            float x = 0.2f + 0.6f * gen.nextFloat();
            px[i] = size * x;
            pw[i] = size * (Math.min(x, 1 - x) * gen.nextFloat());
            ph[i] = size * (0.5f + 0.5f * gen.nextFloat());
        }
    }

    @Override
    protected void paintComponent(Graphics g0) {
        Graphics2D g = (Graphics2D) g0;
        for (int i = 0; i < n; i++) {
            g.draw(getQuadCurve(i));
        }
    }
}

public class Main extends JFrame {

    public Main() {
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(new TestCanvas());
        getContentPane().setPreferredSize(new Dimension(200, 200));
        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
}
Gene
  • 46,253
  • 4
  • 58
  • 96
  • 1
    +1 excluding KeyListener (usage of in year 2014) instead of KeyBindings – mKorbel Mar 07 '14 at 07:30
  • @mKorbel Thanks but I'm not sure what you mean. I wanted any key to cause a redraw. Can that be done with key bindings short of binding to all keys on the keyboard? – Gene Mar 07 '14 at 14:48
  • yes exactly, KeyListener are designated for prehistoric AWT Components, search here by using KeyBindings tag ([for example](http://stackoverflow.com/a/7940227/714968)) – mKorbel Mar 07 '14 at 16:34
  • @Gene Suppose I want to use like a shape to translate using the random parabola's, is there a way I can get transform QuadCurve2D into an equation so I can get x and y cooridiates ? – user3390695 Mar 07 '14 at 21:24
  • @user3390695 Just read the docs for `QuadCurve2D`. Its method `getPathIterator` returns an object that will enumerate the segments on the curve. I changed the code so that the key handler prints the path of each parabola to the console. If this meets your needs, it would be good if you accepted the answer. – Gene Mar 07 '14 at 22:10