Just a Lissajous curve on Java displayed on a JFrame.

You can find the complete code for this here: Lissajous.java.

First of all, the code is a complete rip-off from The Go Programming Language book, specifically from this code from chapter 1.

I won’t even pretend to understand the maths on this one, so lets just dive into the code, first we initialize our window:

int size = 100;
JFrame frame = new JFrame("Lissajous");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(2*size+1, 2*size+1));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

With that we have a non resizable JFrame on the middle of the screen, that terminates the program when closed which contains a JPanel where we can draw, in order to do so we only need the Graphics from the JPanel:

Graphics g = panel.getGraphics();

Then we start shamelessly translating the Go code from the link above to Java:

double cycles = 5;
double angularResolution = 0.001;
long delay = 80;
int frames = 64;
for(;;){
    double frequency = Math.random() * 3.0;
    float phase = 0.0f;
    for( int i = 0; i < frames; i++) {
        g.setColor(Color.BLACK);
        g.fillRect(0,0, panel.getWidth(), panel.getHeight());
        g.setColor(Color.GREEN);
        for(double t = 0.0; t < cycles*2*Math.PI; t+= angularResolution){
            double x = Math.sin(t);
            double y = Math.sin(t * frequency + phase);
            g.drawRect( (size + (int)(x*size+0.5)), (size + (int)(y*size+0.5)),1,1);
        }
        phase += 0.1;
        Thread.sleep(delay);
    }
}

Since its a single file, if we have Java 11 or above we can run it without compiling with:

java Lissajous.java

And we should see this:

lissajous-curve-java


Download the complete code for this here: Lissajous.java.