Java Program for Engine Piston Movement Animation

This program simulates the motion of the components of a two stroke engine. It shows the movement of piston, connecting rod and crank by animating them in java. The program override the paint method of a JFrame to simulate the piston movement in two stroke engine. This can be computer graphics lab (CG lab) problem. The program is as given below. The program uses sin and cos functions to simulate the crank. Also it uses the equation to find the distance between to points.


import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;


public class JavaApplication3 extends JFrame{

    int midx,midy;
    int radius=40,rodlength=150;
    int degree=0;
    int jointx,jointy;
    float radian;
    int px;
    float rodlengthsquared;
    
    public JavaApplication3()
    {
        setSize(800,600);
        setLayout(null);
        setResizable(false);
        midx=getWidth()/2;
        midy=getHeight()/2;
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        rodlengthsquared=rodlength*rodlength;
        ttt.start();
    }


    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawOval(midx-radius,midy-radius,2*radius,2*radius);
        radian=(float) (degree*Math.PI/180);
        jointx=(int) (midx+radius*Math.sin(radian));
        jointy=(int) (midy+radius*Math.cos(radian));
        g.drawLine(midx, midy, jointx,jointy);
        float t=(float) Math.pow(jointy-midy,2);
        int tt=(int) Math.sqrt(rodlengthsquared-t);
        px=jointx-tt;
        g.drawLine(jointx,jointy, px,midy);
        g.setColor(Color.BLACK);
        g.fillRect(px-30,midy-10,50, 20);
        g.fillRect(px-45,midy-35,15, 70);
        g.drawRect(midx-240,midy-35, 150,70);
        degree=(degree+7)%361;
    }
    
    Thread ttt=new Thread()
    {
        public void run()
        {
            while(true)
            {
                try {
                    Thread.sleep(60);
                } catch (InterruptedException ex) {}
                repaint();
            }
        }
    };
    
    public static void main(String[] args) {
        new JavaApplication3().setVisible(true);
    }
    
}

Related Posts:

Java Program to Simulate Motion of Simple Pendulum
Animated Clock Java Program - Classic Clock using Java Code

No comments:

Post a Comment