Showing posts with label Java Swing Moving Vehicles. Show all posts
Showing posts with label Java Swing Moving Vehicles. Show all posts

Monday, June 10, 2024

Moving Vehicles in Java Swing

 // Moving Vehicles Swing

import java.awt.*;

import javax.swing.*;


public class demo extends JFrame

{

JFrame f;

JPanel p;

        

        public demo()

{

f=new JFrame();

p=new JPanel()

{

int x=0;

int y=100;


int w=250;

int h=140;


int w1=60;

int h1=60;

int w2=60;

int h2=60;

int x1=40;

int y1=200;


int x2=140;

int y2=200;


        int flag=10;

int flag1=10;

int flag2=10; 

int max_x=1300;

int max_y=500;

public void paint(Graphics g)

{

super.paint(g);

g.setColor(Color.ORANGE);

g.fillRect(x,y,w,h);


g.setColor(Color.BLACK);

g.fillOval(x1,y1,w1,h1);  

g.fillOval(x2,y2,w2,h2); 

if(x+w > max_x || x1+w1 > max_x || x2+w2 > max_x || x<0 || x1<0 || x2<0)

{

flag=-flag;

flag1=-flag1;

flag2=-flag2;

}

x=x+flag;

x1=x1+flag1;

x2=x2+flag2;


try

{

Thread.sleep(100);

}

catch(Exception e)

{

}

repaint();

}

};


f.add(p);

f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

f.setVisible(true);

f.setSize(1300,500);

}

public static void main(String args[])

{

new demo();

}

}