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

GUI application in Python using wxPython

This is a simple login application created using wxPython in python.Only the front-end is shown here.The backend working is in another tutorial.

Note:Make sure that you know the Classes  and inheritance concepts of python before reading this.See this tutorial for short intro of the same https://praveenmax.wordpress.com/2011/02/17/creating-class-in-python/

The Source:


import wx; #importing wxpython packages
class myframe(wx.Frame):#Inheriting the "wx.Frame" class into our myframe class
    #our constructor
    def __init__(self,parent,title):
        #calling the constructor of wx.Frame
        wx.Frame.__init__(self,parent,-1,title);
        #Our panel
        basepanel=wx.Panel(self,-1);

        #some custom fonts
        #syntax:wx.Font(size,font_family,font_style,font_weight)
        font1 = wx.Font(12, wx.DEFAULT, wx.FONTSTYLE_NORMAL, wx.LIGHT);
        font = wx.Font(15, wx.DEFAULT, wx.FONTSTYLE_NORMAL, wx.BOLD)

        #this is the BoxSizer
        #syntax:wx.BoxSizer(orientation)
        basebox=wx.BoxSizer(wx.VERTICAL);

        #This is our name field
        ip_box=wx.BoxSizer(wx.HORIZONTAL);#A boxresizer
        ip_label=wx.StaticText(basepanel,label="User name");#Label "Username"
        ip_label.SetFont(font1)#setting custom font to label
        ip_text=wx.TextCtrl(basepanel,-1,"enter text here");#TextField for Username

        #adding Username label & its textfield to ip_box BoxSizer
        #syntax:Add(parent,id,proportion,spacing)
        ip_box.Add(ip_label,-1,wx.ALL,5);#wx.ALL means spacing of 5px in "all direction"
        ip_box.Add(ip_text,-1,wx.ALL,5);

        #password field
        pwd_box=wx.BoxSizer(wx.HORIZONTAL);
        pwd_label=wx.StaticText(basepanel,label="Password");
        pwd_label.SetFont(font1);
        pwd_text=wx.TextCtrl(basepanel,-1);

        pwd_box.Add(pwd_label,-1,wx.ALL,5);
        pwd_box.Add(pwd_text,-1,wx.ALL,5);

        #WELCOME title
        title_box=wx.BoxSizer(wx.HORIZONTAL);
        title_text=wx.StaticText(basepanel,label="Login Frame");#a non-editable text
        title_text.SetFont(font);
        title_box.Add(title_text,-1);

        #OK button
        bt_box=wx.BoxSizer(wx.HORIZONTAL);
        ok_bt=wx.Button(basepanel,-1,"Login");
        cancel_bt=wx.Button(basepanel,-1,"Cancel");
        bt_box.Add(ok_bt,-1,wx.ALL,5);
        bt_box.Add(cancel_bt,-1,wx.ALL,5);

        #adding everything to basebox
        basebox.Add(title_box,0,wx.CENTER,10);
        basebox.Add(wx.StaticLine(basepanel),0,wx.ALL|wx.EXPAND,5);
        basebox.Add(ip_box,0,wx.CENTER,10);
        basebox.Add(pwd_box,0,wx.CENTER,10);
        basebox.Add(bt_box,0,wx.CENTER,10);

        #adding basebox to basepanel
        basepanel.SetSizer(basebox);
        #automatically setting up the frame size
        basebox.Fit(self);

myapp=wx.App();
tempframe=myframe(None,"MyFrame");#our frame instance
tempframe.Show(True);#making frame visible
myapp.MainLoop();

Login Frame using wxPython

The comments in the corresponding lines will explain most of the meanings except the “wx.BoxSizer()” stuff.The image below explains it

BoxSizers revealed

BoxSizer is a layout manager which is used to arrange widgets either vertically or horizontally.It holds the widgets together.
In the image,there are 5 BoxSizer.The blue box shows the main BoxSizer of our Frame and it also contains 4 more BoxSizer.Refer to the colors.

 #WELCOME title
        title_box=wx.BoxSizer(wx.HORIZONTAL);
        title_text=wx.StaticText(basepanel,label="Login Frame");#a non-editable text
        title_text.SetFont(font);
        title_box.Add(title_text,-1);

The above code is the First BoxSizer.This contains a static text “Frame Login” .Similarly,…..

        ip_box=wx.BoxSizer(wx.HORIZONTAL);#A boxresizer 
        ip_label=wx.StaticText(basepanel,label="User name");#Label "Username"
        ip_label.SetFont(font1)#setting custom font to label
        ip_text=wx.TextCtrl(basepanel,-1,"enter text here");#TextField for Username 
        
        #adding Username label & its textfield to ip_box BoxSizer
        #syntax:Add(parent,id,proportion,spacing)
        ip_box.Add(ip_label,-1,wx.ALL,5);#wx.ALL means spacing of 5px in "all direction"
        ip_box.Add(ip_text,-1,wx.ALL,5);

The second BoxSizer contains the “Username” label  and a Textfield.

    #password field
        pwd_box=wx.BoxSizer(wx.HORIZONTAL);
        pwd_label=wx.StaticText(basepanel,label="Password");
        pwd_label.SetFont(font1);
        pwd_text=wx.TextCtrl(basepanel,-1);
        
        pwd_box.Add(pwd_label,-1,wx.ALL,5);
        pwd_box.Add(pwd_text,-1,wx.ALL,5);

The third BoxSizer contains the “Password” label and a Textfield.

 # button
        bt_box=wx.BoxSizer(wx.HORIZONTAL);
        ok_bt=wx.Button(basepanel,-1,"Login");
        cancel_bt=wx.Button(basepanel,-1,"Cancel");
        bt_box.Add(ok_bt,-1,wx.ALL,5);
        bt_box.Add(cancel_bt,-1,wx.ALL,5);

The fourth BoxSizer contains the “Login” and “Cancel” button.

All these 4 BoxSizers are enclosed by another BoxSizer which is then added to wx.Panel(refer Line 60).

Done! 🙂

Creating Class in Python

class Employee:
    #these are the instance variables
    sal=0;
    name="none";

    #This is a function definition.
        #the keyword "self" is MUST!It is similar to "this" in java.It says that this method belongs to Employee class.(explicitly saying)
    #"__init__() is the constructor in python.

    def __init__(self,name,sal):
        self.name=name;
        self.sal=sal;
        print "instance created";

    #a normal method
    def display(self):
        print "*"*20;
        print "Name:",self.name;
        print "Salary:",self.sal;
        print "*"*20;

#class ends

#creating class instance and storing in variable "temp_var"
temp_var=Employee("max",10000);
#display the values
temp_var.display();

Output:

instance created
********************
Name: max
Salary: 10000
********************

Painting a Circle using TouchListener in Android

This program is used to create a colored circle using a View context whenever the user touch the screen.The color generated is random and changes rapidly when dragged…

Note:A basic knowledge in Android needed .

Project structure:-


Source 1:

This is the Activity class.We simply create an instance of our “drawingView” class(which extends View) and add it to current content view…

package com.android;

import android.app.Activity;
import android.os.Bundle;

public class Activity1 extends Activity{
    /** Called when the activity is first created. */

    drawingView dview;                    //creating the reference

    public void onCreate(Bundle savedInstanceState)
   {
        super.onCreate(savedInstanceState);
        dview=new drawingView(this); //creating the instance
        setContentView(dview);         //adding to the activity
    }
}

Source 2:

This is our “drawingView” class which extends the “View” class from “import android.view.View” package.  This class contains the following logic,

  • Generating a random color value .
  • Implements “OnTouchListener” for generating touch events.
  • Drawing the circle.
package com.android;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class drawingView extends View implements OnTouchListener{

	static int x,y,r=255,g=255,b=255;
	final static int radius=30;
	Paint paint;     //using this ,we can draw on canvas

	public drawingView(Context context)
	{
		super(context);
	        paint=new Paint();
		paint.setAntiAlias(true);       //for smooth rendering
		paint.setARGB(255, r, g, b);    //setting the paint color

		//to make it focusable so that it will receive touch events properly
		setFocusable(true);

		//adding touch listener to this view
		this.setOnTouchListener(this);
	}

	//overriding the View's onDraw(..) method
	public void onDraw(Canvas canvas)
	{
		paint.setARGB(255, r, g, b);

		//drawing the circle
		canvas.drawCircle(x,y,radius,paint);

	}

	//this is the interface method of "OnTouchListener"
	public boolean onTouch(View view,MotionEvent event)
	{
		x=(int)event.getX()-(radius/2);      //some math logic to plot the circle  in exact touch place
		y=(int)event.getY()-(radius/2);
		  //System.out.println("X,Y:"+"x"+","+y);      //see this output in "LogCat"
		randColor();       //calls this method to generate a color before drawing
		invalidate();      //calls onDraw method
		return true;
	}

	//this method sets a random color using Math.random()
	//Note: RGB color values ranges from 0 to 255..
	public void randColor()
	{
		r=(int)(Math.random()*255);
		g=(int)(Math.random()*255);
		b=(int)(Math.random()*255);
		//Toast.makeText(c, "r,g,b="+r+","+g+","+b,Toast.LENGTH_SHORT).show();
	}
}

Output:
Some screenshots in Emulator,

This slideshow requires JavaScript.

Note:The above slideshow(a wordpress plugin) has some bug and so it displays the file structure picture…ignore it

Creating Frame in wxPython

Code:

Note:Use “portable python” IDE since it has wxPython by default.

import wx                      //importing the core package of wxPython

class MyApp(wx.App):           //creating a class "MyApp" instantiating the "wx.App" 
 def OnInit(self):             //constructor for the class
     myframe=wx.Frame(parent=None,title="A sample Frame")  //creating a frame(parent,title)
     myframe.Show()             //set the frame to be visible
     return True               //true if the constructor runs without errors else return false implicitly
//-------------end of the class------------------
myapp=MyApp()                  //creating an instance of MyApp class
myapp.MainLoop()               //starting a loop for dispatching  events.

Output:

This is the output

A simple frame

NOTE:Make sure you indent your python codes properly before running to prevent compilation errors!

Installing Python the easy way


Instead of downloading the Python from the official site,download the portable version of Python 2.6 which comes with several modules such wxPython(GUI programming ) , Iron Python(For C# ) ,pyGame …

 

Download Python IDE from this link

Do not download Python 3.0.1 at least for now.Python 2.6 is enough for most of the tasks.

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!


Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!