JFighter- A custom 2d Java Game Engine

This is a 2d fighting game that i made entirely using Java 6.Still incomplete.

Download it from the link below,

https://github.com/downloads/indiedev/JFighter/JFighter_2.7z

Controls:

X – Kick, Shift– change direction, Arrow Keys(as usual,movements)…..

Note: If the jar file is not opening on double-click, choose “Open with” and select “Java Platform(something similar)”.

Critics welcomed..

Bouncing ball with collision detection in Java

This program shows the same ball simulation with collision detection using “Rectangle” class of java.
Eg:-It works like this,
“r1.intersects(Rectangle r2)” method checks whether the r1 touches the r2.I have made special conditions for ball deflection based on the side it collides.

Class 1:Base Frame with some UI components

package ball_bounds;
import javax.swing.*;

import ball_bounds.canvas.ball;
import java.awt.*;
import java.awt.event.*;
public class base_frame extends JFrame implements ActionListener
{

	canvas draw_panel;
	JButton b_changebg,b_add,b_remove;
	JPanel ui_panel;
	base_frame()
	{
		super("Ball Bounds");

		//our UI panel which contains gui comps
		ui_panel=new JPanel();
		b_changebg=new JButton("Change Background");
		b_add=new JButton("Add");
		b_remove=new JButton("Remove");

		//add listeners
		b_changebg.addActionListener(this);
		b_add.addActionListener(this);
		b_remove.addActionListener(this);

		setLayout(new FlowLayout());
		draw_panel=new canvas();

		//adding to UI panel
		ui_panel.add(b_changebg);
		ui_panel.add(b_add);
		ui_panel.add(b_remove);

		//adding to our JFrame
		add(draw_panel);
		add(ui_panel);

		setSize(540,470);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public static void main(String[] args)
	{
		new base_frame();
	}
	public void actionPerformed(ActionEvent ae)
	{
		if(ae.getSource()==b_changebg)
		{
				draw_panel.changeBGcolor();
		}
		else
		if(ae.getSource()==b_add)
		{
			//adds a ball of size 20;
			draw_panel.addBall(20);
			System.out.println("Added a ball");
		}
		else
		if(ae.getSource()==b_remove)
		{
				draw_panel.removeBall();
				System.out.println("Removed a ball");
		}
	}
}

Class 2:Our Drawing canvas

package ball_bounds;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class canvas extends JComponent implements KeyListener,MouseMotionListener
{
	//display details
	private final int width=512;
	private final int height=384;
	boolean bg_change=false;
	int color=254,incr=1;

	//a  ball array
	ArrayList ballarray;

	//my custom box
	My_box b1;

	canvas()
	{
		ballarray=new ArrayList(1);
		b1=new My_box(0,0,120,20);

		addKeyListener(this);
		addMouseMotionListener(this);

		setPreferredSize(new Dimension(width,height));
		setFocusable(true);
	}

	//change to background color dynamically(default:white)
	public void changeBGcolor()
	{
		if(bg_change)
		{
			bg_change=false;
		}
		else
		{
			bg_change=true;
		}
	}

	//add a new ball by passing a "ball" class instance
	public void addBall(int size)
	{
		//added to the arraylist
		ballarray.add(new ball(size));
	}

	public void removeBall()
	{
		if(!ballarray.isEmpty())
		{
			ballarray.remove(ballarray.size()-1);
		}
	}
	public int getBallCount()
	{
			return ballarray.size();
	}
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);

		//fill rect
		if(bg_change)
		{
			color=color-incr;

			 if(color<1)                         
                        {
                                    incr=-1;                         
                        }             
                         if(color>250)
			{
				incr=1;
			}
			g.setColor(new Color(color,color,color));
		}
		else
		{
			color=254;
			g.setColor(Color.WHITE);
		}
		g.fillRect(0,0,getWidth(),getHeight());

		//my box
		g.setColor(Color.BLACK);
		b1.drawBox(g);

		try{
			Thread.sleep(5);
			for(ball temp_ball:ballarray)
			{
				//drawing the ball using "drawBall(Graphics g,boolean)".
				//boolean is for displaying ball's bounding rectangle which deals with collision
				temp_ball.drawBall(g,false);

				//checking for collision with our movable pad
				temp_ball.collision(b1);
			}
			repaint();//calls the paint method

		}catch(Exception e)
		{
			System.out.println(e);
		}
	}

	//keyboard call-back methods
	public void keyPressed(KeyEvent ke)
	{
		if(ke.getKeyCode()==KeyEvent.VK_RIGHT)//increase x
		{

			b1.translate(10,0);
		}
		else
		if(ke.getKeyCode()==KeyEvent.VK_LEFT)
		{
			b1.translate(-10,0);
		}
       	}
	public void keyReleased(KeyEvent ke)
	{
	}
	public void keyTyped(KeyEvent ke)
	{

	}

	//mouse call-back methods

	public void mouseMoved(MouseEvent me)
	{
		//move the rectangle box too
		b1.setLocation(me.getX(),me.getY());
	}
	public void mouseDragged(MouseEvent me)
	{

	}

	//Ball inner-class
	class ball
	{
		private int x_pos=0;
		private int y_pos=0;
		private int dir_x=1;
		private int dir_y=1;
		private int size=0;

		ball(int size)
		{
			this.size=size;
		}

		private void calculate_direction()
		{
			//move the ball
			x_pos=x_pos-dir_x;
			y_pos=y_pos-dir_y;

			//for X-direction
			if(x_pos<0)
                        { 		       
                            x_pos=0; 	
          		    dir_x=-1;//incr   
                        }
                        else   
                       if(x_pos+size>getWidth())
			{
				 dir_x=1;//decr
			}

			//for Y-direction
			if(y_pos<0)  
                        {  
                                 y_pos=0;     
                             dir_y=-1;//incr                         

                        }                         
                         else                                            
                         if(y_pos+size>getHeight())
			{
				dir_y=1;//decr
			}
		}

		public void changeDirection_Y()
		{
             		if(dir_y==-1)
			{
				dir_y=1;
			}
			else
			{
				dir_y=-1;
			}
		}

		public void changeDirection_X()
		{
			if(dir_x==-1)
			{
				dir_x=1;
			}
			else
			{
				dir_x=-1;
			}
		}

		public void drawBall(Graphics g,boolean bound)
		{
			calculate_direction();
			g.setColor(Color.BLUE);
			g.fillOval(x_pos,y_pos,size,size);

			if(bound)
			{
				g.drawRect(x_pos,y_pos,size,size);
			}
		}

		public Rectangle getRectBounds()
		{
			return new Rectangle(x_pos,y_pos,size,size);
		}

                //this method is called for all balls and checked whether it touches the rect.if so,the ball's direction gets changed accordingly.
		public void collision(My_box rect)
		{
                           //if ball collides with top/bottom part of the rect
			if(this.getRectBounds().intersectsLine(rect.x,rect.y,rect.x+rect.width,rect.y) ||
                           this.getRectBounds().intersectsLine(rect.x,rect.y+rect.height, rect.x+rect.width,rect.y+rect.height))
			{

				changeDirection_Y();//reverses the direction along Y

			}

			  //if ball collides with left/right part of the rect
			if(this.getRectBounds().intersectsLine(rect.x,rect.y    ,    rect.x,rect.y+rect.height) ||
                           this.getRectBounds().intersectsLine(rect.x+rect.width,rect.y  ,   rect.x+rect.width,rect.y+rect.height))
			{
				changeDirection_X();//reverses the direction along X

			}

		}
	}
}

Class 3:Our “My_box ” class.
This class extends Rectangle class.It is written in separate class just for future scalability.nothing specific

package ball_bounds;
import java.awt.*;
import java.awt.event.*;
class My_box extends Rectangle
{
	//default vars
	/*
	 * x,y,width,height
	 */
	My_box(int x1,int y,int width,int height)
	{
		super(x1,y,width,height);
	}

	public void drawBox(Graphics g)
	{
		g.setColor(Color.BLACK);
		g.fillRect(x,y,width,height);
	}
}

This is the Screenshot

Screenshot:

Bouncing balls in Java Swing

This program displays several ball(more precisely “circles”) bouncing off the sides of the enclosing component.

Code 1:The JFrame class (Main window)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class base_frame extends JFrame
{
	
	Container c;
	
	//our components
	JPanel b_panel;
	JButton b_add,b_sub;
	JLabel l_counter,l_ballsize;
	JTextField t_ballsize;
	
	//Actionlistener class instance
	handler handle;
	
	//class which contains drawing surface "JComponent"
	canvas ballcanvas;
	
	base_frame()
	{
		super("Ball Simulator");
		c=getContentPane();
		
		//setting to "flowlayout"
		c.setLayout(new FlowLayout());
		
		//all components
		t_ballsize=new JTextField(2);
		l_counter=new JLabel("Ball Count:  ");
		l_ballsize=new JLabel("Ball Size:  ");
		l_counter.setBorder(BorderFactory.createBevelBorder(1));
		b_add=new JButton("Add");
		b_sub=new JButton("Remove");
		handle=new handler();
		//adding actionlistener to buttons
		b_add.addActionListener(handle);
		b_sub.addActionListener(handle);
		
		//button panel 
		b_panel=new JPanel();//panel to hold buttons,textfields..
		b_panel.add(l_ballsize);//label
		b_panel.add(t_ballsize);//textfield to input ball size
		b_panel.add(b_add);//button to add a ball
		b_panel.add(b_sub);//button to del a ball (the most recent one)
		b_panel.add(l_counter);//label displaying total balls being rendered
		
		//ball canvas
		ballcanvas=new canvas(); 
		
		//container details
		c.add(ballcanvas);//adding drawing surface(ballcanvas) to main jframe
		c.add(b_panel);//adding the panel along with its smaller components
		
		//set visuals
		setSize(640,480);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	
	}
	public static void main(String[] args)
	{
		new base_frame();//creating main jframe instance
	}
	
	//an inner class to take care of button events
	class handler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			//if "Add" button clicked
			if(ae.getSource()==b_add)
			{
				if(!t_ballsize.getText().equals(""))
				{
					
					try{
						ballcanvas.addBall(Integer.parseInt(t_ballsize.getText()));
						
						//updates the counter label
						l_counter.setText("Ball Count:"+ballcanvas.countBall());
					}catch(NumberFormatException e)
					{
						System.out.println(e);
						JOptionPane.showMessageDialog(null,"Enter only numbers!","Invalid Input",JOptionPane.INFORMATION_MESSAGE);
						
					}
					
				}
				else
				{
					JOptionPane.showMessageDialog(null,"Enter the ball size!","Input needed",JOptionPane.INFORMATION_MESSAGE);
				}
			}//b_add
			
			//if "Sub" button clicked
			if(ae.getSource()==b_sub)
			{
				ballcanvas.removeBall();
				//updates the counter label
				l_counter.setText("Ball Count:"+ballcanvas.countBall());
			}
		}
	}
}

Code 2:The drawing surface class .JComponent used

import java.awt.*;
import javax.swing.*;
import java.util.*;
public class canvas extends JComponent
{
	//display details	
	private final int width=512;
	private final int height=384;
	
	//ball array
	final private ArrayList<ball> ball_array;
	
	canvas()
	{
		ball_array=new ArrayList<ball>();
		
		setPreferredSize(new Dimension(width,height));
		setBorder(BorderFactory.createEtchedBorder(1));
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		g.setColor(Color.BLACK);
		
		//fill rect
		g.fillRect(0,0,getWidth(),getHeight());
		try
		{
			//draw balls from ball_array
			for(int i=0;i<ball_array.size();i++)
			{
				ball_array.get(i).drawBall(g);
				//System.out.println("Drawing ball");
			}
			Thread.sleep(5);//to control animation speed

		}catch(InterruptedException e)
		{
			System.out.println("cannot control the paint thread!!");
		}
		repaint();//calls the paint method 
	}
	
	//to add a ball
	public void addBall(int size)
	{
		ball_array.add(new ball(size));
	}
	
	//to remove a ball
	public void removeBall()
	{
		if(!ball_array.isEmpty())
		{
			ball_array.remove(ball_array.size()-1);
		}
		
	}
	
	//return total balls from the array
	public int countBall()
	{
		return ball_array.size();
	}
	
	//Ball inner-class
	class ball
	{
		private int x_pos=0;
		private int y_pos=0;
		private int dir_x=1;
		private int dir_y=1;
		private int size;
		
		ball(int size)
		{
			this.size=size;
		}
		
		private void calculate_direction()
		{
			//move the ball
			x_pos=x_pos-dir_x;
			y_pos=y_pos-dir_y;
			
			//for X-direction
			if(x_pos<0)
			{
				x_pos=0;
				dir_x=-1;//incr
			}
			else
			if(x_pos+size>getWidth())
			{
				dir_x=1;//decr
			}
			
			//for Y-direction
			if(y_pos<0)
			{
				y_pos=0;
				dir_y=-1;//incr
			}else
			if(y_pos+size>getHeight())
			{
				dir_y=1;//decr
			}
		}
		
		public void drawBall(Graphics g)
		{
			calculate_direction();
			g.setColor(Color.WHITE);
			g.drawOval(x_pos,y_pos,size,size);
		}
	}
}

Download the jar file : Ball Simulate

Login application using Java Swings and Mysql.

Front-end:Java Swings

Back-end:MySql

Class 1:Login JFrame

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class swing_sample extends JFrame
{
	//declaring our swing components
	JLabel l_name,l_pass;
	JTextField t_name;
	JPasswordField t_pass;     //A special JTextField but hides input text
	JButton button;
	Container c;

	//a inner class to handling ActionEvents
	handler handle;

	//a separate class for processing database connection and authentication
	database db;

	swing_sample()
	{
		super("Login form");

		c=getContentPane();
		c.setLayout(new FlowLayout());

		//extra classes
		db=new database();
	        handle =new handler();

                //swing components
		l_name=new JLabel("Username");
		l_pass=new JLabel("Password");
		t_name=new JTextField(10);
		t_pass=new JPasswordField(10);
		button=new JButton("Login");

		//adding actionlistener to the button
		button.addActionListener(handle);

		//add to contaienr
		c.add(l_name);
		c.add(t_name);
		c.add(l_pass);
		c.add(t_pass);
		c.add(button);
		//visual
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(200,130);

	}
	public static void main(String args[])
	{
		swing_sample sample=new swing_sample();
	}

	//an inner class .You can also write as a separate class
	class handler implements ActionListener
	{
		//must implement method
		//This is triggered whenever the user clicks the login button
		public void actionPerformed(ActionEvent ae)
		{
			//checks if the button clicked
			if(ae.getSource()==button)
			{
				char[] temp_pwd=t_pass.getPassword();
				String pwd=null;
				pwd=String.copyValueOf(temp_pwd);
				System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);

				//The entered username and password are sent via "checkLogin()" which return boolean
				if(db.checkLogin(t_name.getText(), pwd))
				{
					//a pop-up box
					JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
                                        JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					//a pop-up box
					JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
                                        JOptionPane.ERROR_MESSAGE);
				}
			}//if
		}//method

	}//inner class
}//class

Class 2:Database

This is where the validation takesplace.
Connects to mysql and validates the username and pwd.

Note:Make sure you set the classpath to point the mysql_connector.jar file.The program wont work without it.

Download from mysql site by searching “Jconnector”.

import java.sql.*;
public class database 
{
	Connection con;
	PreparedStatement pst;
	ResultSet rs;
	database()
	{
		try{
			
			//MAKE SURE YOU KEEP THE mysql_connector.jar file in java/lib folder
			//ALSO SET THE CLASSPATH
			Class.forName("com.mysql.jdbc.Driver");
			con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ajax","root","");
                        pst=con.prepareStatement("select * from biodata where uname=? and pwd=?");
			
		   }
		catch (Exception e) 
		{
			System.out.println(e);
		}
	}
        //ip:username,password
        //return boolean
	public Boolean checkLogin(String uname,String pwd)
	{
		try {
                       
			pst.setString(1, uname); //this replaces the 1st  "?" in the query for username
			pst.setString(2, pwd);    //this replaces the 2st  "?" in the query for password
			//executes the prepared statement
			rs=pst.executeQuery();
			if(rs.next())
			{
				//TRUE iff the query founds any corresponding data
				return true;
			}
			else
			{
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("error while validating"+e);
			return false;
		}
}

Output Screen:

 

Back:JFrame(Input window) Front:JOptionPane(confirmation window)

 

Scary Application in Java

This  is a scary application made using Java Swings.Will pop an image in front of the screen suddenly(Ghost,in this case) … 🙂

NOTE:This app  is made for fun .U r responsible for using..

Download the jar file and run it once-> myapp.jar.

Here is the  source code :-

Class 1:Base frame

import java.io.InputStream;
import java.io.PrintStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;

public class base_frame
implements Runnable
{
      Thread t;
      img_frame fpanel;  //this is our image(JPanel type) class
      AudioPlayer ap;     //In-built Audioplayer class("import sun.audio.AudioPlayer ")
      InputStream is_scream = null; InputStream is_about = null;

      public base_frame()
      {
              this.t = new Thread(this, "Frame Thread");
              try
              {
                      this.is_scream = getClass().getResourceAsStream("s_0x00");
              }
              catch (Exception e)
             {
                       System.out.println("Error while loading audio file" + e);
                       System.exit(0);
             }

          this.fpanel = new img_frame();
      }

public static void main(String[] args)
 {
      base_frame frame = new base_frame();
      String[] choices = { "Yes,Its a cool OS!!", "No!!,I hate it!" };
      String[] second_choice = { "Hmmmm..Sorry,i clicked wrongly ", "YES!,I HATE Linux!!!!!" };
      int res1 = 10;

      res1 = JOptionPane.showOptionDialog(null,"What do think about Linux OS?????","Hello there!",0,2,null,choices,Integer.valueOf(0));

      int res2 = 10;
      if (res1 == 1)
     {
               System.out.println("User hates Linux.One more chance");
               res2 = JOptionPane.showOptionDialog(null, "Are you sure ?I am warning you!", "Dont like Linux and other                   opensource stuffs????", 0, 2, null, second_choice, Integer.valueOf(1));
     }
     else if (res1 == 0)
     {
             System.out.println("User likes Linux ");
             JOptionPane.showMessageDialog(null, "Very good ,See ya!!", "Great!                 App by \\m/", 1);
     }

    if (res2 == 1)
    {
             System.out.println("Show starts!!!");
             JOptionPane.showMessageDialog(null, "Ok,Goodbye!...You will regret soon", "Errr!", 1);
             frame.t.start();
     }
     else if (res2 == 0)
     {
             JOptionPane.showMessageDialog(null, "Hmmmmm,Ok,Dont tell that again...\nBye ", "ok ok---                App by \\m/", 1);
     }

if ((res1 == -1) || (res2 == -1))
{
            JOptionPane.showMessageDialog(null, "This program wont crash your PC!.\nRun again and choose one",  "Select a choice!!", 1);
}
System.out.println("Main finished");
}

public void run()
{
       try
      {
              Thread.sleep(30000L);
              this.fpanel.setVisible(true);
              AudioPlayer.player.start(this.is_scream);
              Thread.sleep(6000L);
      }
      catch (InterruptedException ie)
     {
              System.out.println("Error in thread!!" + ie);
              System.exit(0);
     }
System.out.println("Author:MaX \nThis program is not for weak hearted ppl.Be careful \\m/");
System.exit(0);
}
}

Class 2:Image Frame:


import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
/*
* this class gets the screen res
* loads the image
* sets the frame based on the screen size
*
*
*
*/
public class img_frame extends JFrame
{
        //img_panel panel;
        JLabel label;

        //graphics device
	GraphicsDevice gdev;
	GraphicsEnvironment genv;

img_frame()
{
	label=new JLabel();
	InputStream f=null;
	ImageIcon icon=null;
	try{
		f= getClass().getResourceAsStream("rock1.gif");
		icon=new ImageIcon(ImageIO.read(f));
	}catch(Exception e)
	{
		System.out.println("error while loading image"+e);
		System.exit(0);
	}
        System.out.println("Image details(w,h):"+icon.getIconHeight()+","+icon.getIconHeight());

	//adding label to this frame
	label.setIcon(icon);
	this.add(label);

	//reading the screen res
	genv=GraphicsEnvironment.getLocalGraphicsEnvironment();
	//access the computer screen
	gdev=genv.getDefaultScreenDevice();
	System.out.println("Screen width:"+gdev.getDisplayMode().getWidth());
	System.out.println("Screen Height:"+gdev.getDisplayMode().getHeight());

        //image panel visual details
	setVisible(false);
	setSize(gdev.getDisplayMode().getWidth(),gdev.getDisplayMode().getWidth());
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setAlwaysOnTop(true);
	setUndecorated(true);
}
}

This is the output:-

This is the output shown in full screen

This is the output shown in full screen

Blurred here only

Note:
  • It also has a screaming audio.Beware ,not for weak ppl!