DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published at jsedano.dev on

Lissajous curve Java

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);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

java Lissajous.java
Enter fullscreen mode Exit fullscreen mode

And we should see this:

lissajous-curve-java

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay