Friday, 7 September 2012

Java Card Layout Tutorial


Introduction of Java Card Layout Tutorial


Programm

Save MyWindowAdapter.java

import java.awt.event.*;
public class MyWindowAdapter extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame implements ActionListener
{
	Panel mainPanel, card1, card2, card3, card4, card5, card6;
	Panel buttonPanel;
	Button b1, b2, b3, b4, b5, b6, btnFirst, btnPrevious, btnNext, btnLast;
	CardLayout cl;
	
	MyFrame()
	{
		super("Card Layout Demo");
		setSize(600,400);
		addWindowListener(new MyWindowAdapter());
		addControls();
		setResizable(false);
		setVisible(true);
	}
	
	private void addControls()
	{
		buttonPanel = new Panel();
		
		b1 = new Button("Card 1");
		b2 = new Button("Card 2");
		b3 = new Button("Card 3");
		b4 = new Button("Card 4");
		b5 = new Button("Card 5");
		b6 = new Button("Card 6");
		
		btnFirst = new Button("First");
		btnPrevious = new Button("Previous");
		btnNext = new Button("Next");
		btnLast = new Button("Last");
		
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		b4.addActionListener(this);
		b5.addActionListener(this);
		b6.addActionListener(this);
		
		btnFirst.addActionListener(this);
		btnPrevious.addActionListener(this);
		btnNext.addActionListener(this);
		btnLast.addActionListener(this);
		
		buttonPanel.add(b1);
		buttonPanel.add(b2);
		buttonPanel.add(b3);
		buttonPanel.add(b4);
		buttonPanel.add(b5);
		buttonPanel.add(b6);
		
		buttonPanel.add(btnFirst);
		buttonPanel.add(btnPrevious);
		buttonPanel.add(btnNext);
		buttonPanel.add(btnLast);
		
		add(buttonPanel, BorderLayout.NORTH);
		
		cl = new CardLayout();
		mainPanel = new Panel();
		mainPanel.setLayout(cl);
		
		card1 = new Panel();
		card1.setBackground(Color.RED);
		
		
		card2 = new Panel();
		card2.setBackground(Color.GREEN);
		
		
		card3 = new Panel();
		card3.setBackground(Color.BLUE);
		
		
		card4 = new Panel();
		card4.setBackground(Color.MAGENTA);
		
		
		card5 = new Panel();
		card5.setBackground(Color.YELLOW);
		
		
		card6 = new Panel();
		card6.setBackground(Color.CYAN);
		
		
		mainPanel.add("card1",card1);
		mainPanel.add("card2",card2);
		mainPanel.add("card3",card3);	
		mainPanel.add("card4",card4);
		mainPanel.add("card5",card5);
		mainPanel.add("card6",card6);
		
		add(mainPanel, BorderLayout.CENTER);
		
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		if (ae.getSource() == b1)
			cl.show(mainPanel,"card1");
			
		else if (ae.getSource() == b2)
			cl.show(mainPanel,"card2");
			
		else if (ae.getSource() == b3)
			cl.show(mainPanel,"card3");
			
		else if (ae.getSource() == b4)
			cl.show(mainPanel,"card4");
			
		else if (ae.getSource() == b5)
			cl.show(mainPanel,"card5");
			
		else if (ae.getSource() == b6)
			cl.show(mainPanel,"card6");
			
		else if (ae.getSource() == btnFirst)
			cl.first(mainPanel);
			
		else if (ae.getSource() == btnPrevious)
			cl.previous(mainPanel);
			
		else if (ae.getSource() == btnNext)
			cl.next(mainPanel);
		
		else if (ae.getSource() == btnLast)
			cl.last(mainPanel);
	}		
}


Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Border Layout Tutorial


Introduction of Java Border Layout Tutorial


Programm

Save MyWindowAdapter.java

import java.awt.event.*;
public class MyWindowAdapter extends WindowAdapter
{
 public void windowClosing(WindowEvent we)
 {
  System.exit(0);
 }
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame
{
 Button b1, b2, b3, b4, b5;
 Button aBtn[];
 
 MyFrame()
 {
  super("Sample Java Frame");
  setSize(600,300);
  addWindowListener(new MyWindowAdapter());
  addControls();
  setVisible(true);
 }
 
 
 private void addControls()
 {
  setLayout(new FlowLayout(FlowLayout.RIGHT,20,40));
  
  b1 = new Button("North");
  b2 = new Button("South");
  b3 = new Button("West");
  b4 = new Button("East");
  b5 = new Button("Center Button");
  
  
  add(b1, BorderLayout.NORTH);
  add(b2, BorderLayout.SOUTH);
  add(b3, BorderLayout.WEST);
  add(b4, BorderLayout.EAST);
  add(b5, BorderLayout.CENTER);
}


Save GUI1.java

public class GUI1
{
 public static void main(String args[])
 {
  MyFrame mf = new MyFrame();
 }
}

Thursday, 6 September 2012

Java Image Tutorial


Introduction of Java Image Tutorial


Programm

Save MyWindowAdapter.java

import java.awt.event.*;
public class MyWindowAdapter extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
public class MyFrame extends Frame implements ActionListener, ItemListener, TextListener, Runnable
{
	
	Label lblExplore, lblImages, lblStatus;
	TextField txtDirectory;
	Button btnSearch, btnCancelSearch;
	List lstImage;
	MyCanvas mc;
	Thread searchThread;
	boolean stopSearch;
	
	MyFrame()
	{
		super("Image Preview");
		setSize(800,600);
		addWindowListener(new MyWindowAdpater());
		setResizable(false);
		addControls();
		setVisible(true);
	}
	
	private void addControls()
	{
		int x,y;
		x = 10;
		y = 35;
		
		
		setLayout(null);
		lblExplore = new Label("Look Into : ");
		lblExplore.setSize(55,18);
		lblExplore.setLocation(x,y);
		add(lblExplore);
		
		txtDirectory = new TextField();
		txtDirectory.setSize(140,20);
		txtDirectory.setLocation(x+lblExplore.getSize().width + 5,y);
		txtDirectory.addTextListener(this);
		add(txtDirectory);
		
		y += txtDirectory.getSize().height + 3;
		
		btnSearch = new Button("Search");
		btnSearch.setLocation(txtDirectory.getLocation().x, y);
		btnSearch.setSize(65,24);
	
		btnSearch.addActionListener(this);
		btnSearch.setEnabled(false);
		add(btnSearch);
		
		btnCancelSearch = new Button("Stop");
		btnCancelSearch.setSize(btnSearch.getSize());
		btnCancelSearch.setLocation(btnSearch.getLocation().x + btnSearch.getSize().width + 10,y);
		btnCancelSearch.addActionListener(this);
		btnCancelSearch.setEnabled(false);
		add(btnCancelSearch);
		
		y += btnSearch.getSize().height + 5;
		
		lblImages = new Label("Images Found...");
		lblImages.setLocation(x,y);
		lblImages.setSize(200,18);
		add(lblImages);
		
		y += lblImages.getSize().height + 3;
		
		lstImage = new List();
		lstImage.setSize(200,465);
		lstImage.setLocation(x,y);
		lstImage.addItemListener(this);
		add(lstImage);
		
		mc = new MyCanvas();
		mc.setLocation(lstImage.getLocation().x + lstImage.getSize().width + 10, txtDirectory.getLocation().y);
		mc.setSize(getSize().width - (lstImage.getSize().width + 30), lstImage.getSize().height+73);
		add(mc);
		
		lblStatus = new Label();
		lblStatus.setSize(getSize().width - 6,18);
		lblStatus.setLocation(3,getSize().height - 18);
		lblStatus.setBackground(new Color(235,235,235));
		add(lblStatus);
			
	}
	
	private void searchDirectory(File dir)
	{
		File aFile[] = dir.listFiles();
		if (stopSearch)
			return;
		
		lblStatus.setText("Exploring : " + dir.getAbsolutePath());
		
		int i;
		
		//search for image files in the directory dir.
		for (i=0;i<aFile.length;i++)
		{
			try
			{
				if (aFile[i].isFile())
				{
					String temp = aFile[i].getName().toLowerCase();
					if (stopSearch)
						return;
					if (temp.endsWith(".jpg") || temp.endsWith(".gif") || temp.endsWith(".bmp") || temp.endsWith(".png") || temp.endsWith(".jpeg"))
						lstImage.add(aFile[i].getAbsolutePath());
				}
			}
			catch (NullPointerException exp){}
		}
		
		//now search for the images in the subdirectories in dir
		for (i=0;i<aFile.length;i++)
		{
			if (aFile[i].isDirectory())
			{
				if (stopSearch)
					return;
				try
				{
					searchDirectory(aFile[i]);
				}
				catch (NullPointerException exp){}
				
			}
		}
		
		
		
		
	}
	
	public void textValueChanged(TextEvent te)
	{
		boolean flag = false;
		if (txtDirectory.getText().trim().length() > 0)
		{
			String dirName = txtDirectory.getText().trim();
			File fileObject = new File(dirName);
			flag = fileObject.isDirectory();
		}
		btnSearch.setEnabled(flag);
	}
	
	public void itemStateChanged(ItemEvent ie)
	{
		if (lstImage.getSelectedIndex() != -1)
		{
			String imageFileName = lstImage.getSelectedItem();
			mc.showImage(imageFileName);
		}
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		if (ae.getSource() == btnSearch)
		{
			btnSearch.setEnabled(false);
			stopSearch = false;
			txtDirectory.setEditable(false);
			searchThread = new Thread(this);
			btnCancelSearch.setEnabled(true);
			searchThread.start();
		}
		else if (ae.getSource() == btnCancelSearch)
		{
			stopSearch = true;
			txtDirectory.setEditable(true);
			btnSearch.setEnabled(true);
			btnCancelSearch.setEnabled(false);
			lblStatus.setText("");
			if (searchThread != null)
			{
				searchThread.stop();
				searchThread = null;
			}
		}
	}
	
	
	
	public void run()
	{
		lstImage.clear();
		File dir = new File(txtDirectory.getText().trim());
		searchDirectory(dir);
		btnSearch.setEnabled(true);
		txtDirectory.setEditable(true);
		btnCancelSearch.setEnabled(false);
		lblStatus.setText("");
	}
}


Save MyCanvas.java


import java.awt.*;
import java.awt.event.*;

public class MyCanvas extends Canvas
{
	private String imageFileName;
	MyCanvas()
	{
		setBackground(new Color(235,235,235));
		imageFileName = "";
	}
	
	void showImage(String imageFileName)
	{
		this.imageFileName = imageFileName;
		repaint();
	}
	
	public void paint(Graphics g)
	{
		if (imageFileName.length() > 0)
		{
			Image img = Toolkit.getDefaultToolkit().getImage(imageFileName);
			int imgWidth, imgHeight, canvasWidth, canvasHeight;
			int x, y, width, height;
			//System.out.println("Width : " + img.getWidth(this));
			//System.out.println("Height: " + img.getHeight(this));
			imgWidth = img.getWidth(this);
			imgHeight = img.getHeight(this);
			canvasWidth = getSize().width;
			canvasHeight = getSize().height;
			
			x = y = width = height = 0;
			
			if (imgWidth >= imgHeight)
			{
				if (canvasWidth >= imgWidth)
				{
					x = (canvasWidth - imgWidth) / 2;
					y = (canvasHeight - imgHeight) / 2;
					width = imgWidth;
					height = imgHeight;
				}
				else
				{
					width = canvasWidth;
					height = (canvasWidth * imgHeight) / imgWidth;
					x = 0;
					y = (canvasHeight - height) / 2;
				}
			}
			else
			{
				if (canvasHeight >= imgHeight)
				{
					x = (canvasWidth - imgWidth) / 2;
					y = (canvasHeight - imgHeight) / 2;
					width = imgWidth;
					height = imgHeight;
				}
				else
				{
					height = canvasHeight;
					width = (canvasHeight * imgWidth) / imgHeight;
					x = (canvasWidth - width) / 2;
					y = 0;
				}
			}
			
			
			g.drawImage(img,x,y,width,height,this);
		}
	}
}

Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Animation


Introduction of Java Animation


Programm

Save MyWindowAdapter.java

import java.awt.event.*;
public class MyWindowAdapter extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
public class MyFrame extends Frame implements Runnable
{
	int x, y, oldX, oldY, width, height, xdir, ydir;
	Thread t;
	
	MyFrame()
	{
		super("Animation Demo");
		setSize(600,400);
		addWindowListener(new MyWindowAdapter());
		setResizable(false);
		setBackground(Color.GRAY);
		setVisible(true);
		
		t = new Thread(this);
		t.start();
	}
	
	private void drawBall()
	{
		Graphics g = getGraphics();
		g.setXORMode(getBackground());
		
		/*
		if (oldX != -1 && oldY != -1)
			g.drawOval(oldX, oldY, width, height);
		*/	
		g.setColor(Color.BLUE);
		g.drawOval(x, y, width, height);
	}
	
	public void run()
	{
		width = 30/2;
		height = 30/2;
		
		x = (getSize().width - width) / 2;
		y = (getSize().height - height) / 2;
		oldX = oldY = -1;
		
		Random r = new Random();
		
		if (r.nextInt(5) % 2 == 0)
			xdir = 1;
		else
			xdir = -1;
			
			
		if (r.nextInt(5) % 2 == 0)
			ydir = 1;
		else
			ydir = -1;
		
		boolean flag = true;
		
		while (flag)
		{
			drawBall();
			try
			{
				Thread.sleep(5);
			}
			catch (InterruptedException exp){}
			
			oldX = x;
			oldY = y;
			
			x = x + (1*xdir);
			y = y + (1*ydir);
			
			if (x <= 0 || x >= getSize().width - width)
				xdir *= -1;
			if (y <= 0 || y >= getSize().height - height)
				ydir *= -1;
		}
	}
}


Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Mouse


Introduction of Java Mouse Tutorial


Programm

Save MyWindowAdapter.java

import java.awt.event.*;
public class MyWindowAdapter extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
public class MyFrame extends Frame implements ActionListener, ItemListener, MouseListener, MouseMotionListener
{
	MenuBar menubar;
	Menu mnuShape, mnuColor;
	CheckboxMenuItem itmLine, itmBox, itmOval;
	CheckboxMenuItem itmRed, itmGreen, itmBlue, itmMagenta, itmYellow, itmSilver, itmBlack;
	MenuItem itmExit;
	String currentShape;
	Color color;
	
	ArrayList alShape;
	
	int x, y, x1, y1, x2, y2, width, height, oldX, oldY, oldWidth, oldHeight;
		
	MyFrame()
	{
		super("Mouse Demo");
		setSize(800,600);
		addWindowListener(new MyWindowAdapter());
		addMouseListener(this);
		addMouseMotionListener(this);
		setResizable(false);
		addMenu();
		setVisible(true);
		currentShape = "line";
		color = Color.BLACK;
		setCursor(Cursor.CROSSHAIR_CURSOR);
		alShape = new ArrayList();
	}
	
	private void addMenu()
	{
		int i;
		menubar = new MenuBar();
		
		mnuShape = new Menu("Shape");
		
		
		itmLine = new CheckboxMenuItem("Line",true);
		itmBox = new CheckboxMenuItem("Box",false);
		itmOval = new CheckboxMenuItem("Oval",false);
		
		itmLine.addItemListener(this);
		itmBox.addItemListener(this);
		itmOval.addItemListener(this);
		
		itmLine.setShortcut(new MenuShortcut(KeyEvent.VK_L));
		itmBox.setShortcut(new MenuShortcut(KeyEvent.VK_B));
		itmOval.setShortcut(new MenuShortcut(KeyEvent.VK_O));
		
		itmExit = new MenuItem("Exit",new MenuShortcut(KeyEvent.VK_X,true));
		itmExit.addActionListener(this);
		
		mnuShape.add(itmLine);
		mnuShape.add(itmBox);
		mnuShape.add(itmOval);
		mnuShape.addSeparator();
		mnuShape.add(itmExit);
		
		menubar.add(mnuShape);
		
		mnuColor = new Menu("Colour");
		
		itmRed = new CheckboxMenuItem("Red",false);
		itmGreen = new CheckboxMenuItem("Green",false);
		itmBlue = new CheckboxMenuItem("Blue",false);
		itmMagenta = new CheckboxMenuItem("Magenta",false);
		itmYellow = new CheckboxMenuItem("Yellow",false);
		itmSilver = new CheckboxMenuItem("Silver",false);
		itmBlack = new CheckboxMenuItem("Black",true);
		
		itmRed.addItemListener(this);
		itmGreen.addItemListener(this);
		itmBlue.addItemListener(this);
		itmMagenta.addItemListener(this);
		itmYellow.addItemListener(this);
		itmSilver.addItemListener(this);
		itmBlack.addItemListener(this);
		
		mnuColor.add(itmRed);
		mnuColor.add(itmGreen);
		mnuColor.add(itmBlue);
		mnuColor.add(itmYellow);
		mnuColor.add(itmMagenta);
		mnuColor.add(itmSilver);
		mnuColor.add(itmBlack);
		
		menubar.add(mnuColor);
		
		setMenuBar(menubar);
	}
	
	private void uncheckAllShapes()
	{
		itmLine.setState(false);
		itmBox.setState(false);
		itmOval.setState(false);
	}
	
	private void uncheckAllColours()
	{
		itmRed.setState(false);
		itmGreen.setState(false);
		itmBlue.setState(false);
		itmMagenta.setState(false);
		itmYellow.setState(false);
		itmSilver.setState(false);
		itmBlack.setState(false);
	}
	
	
	public void itemStateChanged(ItemEvent ie)
	{
		int state = ie.getStateChange();
		if (ie.getSource() == itmLine || ie.getSource() ==itmBox || ie.getSource() ==itmOval)
		{
			uncheckAllShapes();
			if (state == 2)
				currentShape = "";
			else
			{
				if (ie.getSource() == itmLine)			
				{
					itmLine.setState(true);
					currentShape = "line";
				}				
				else if (ie.getSource() == itmBox)
				{
					itmBox.setState(true);
					currentShape = "box";
				}
				else if (ie.getSource() == itmOval)
				{
					itmOval.setState(true);
					currentShape = "oval";
				}				
			}
			if (currentShape.length() == 0)
				setCursor(Cursor.DEFAULT_CURSOR);
			else
				setCursor(Cursor.CROSSHAIR_CURSOR);
		}
		else
		{
			uncheckAllColours();
			if (ie.getSource() == itmRed)
			{
				color = Color.RED;
				itmMagenta.setState(true);
			}
			else if (ie.getSource() == itmGreen)
			{
				color = Color.GREEN;
				itmGreen.setState(true);
			}
			else if (ie.getSource() == itmBlue)
			{
				color = Color.BLUE;
				itmBlue.setState(true);
			}
			else if (ie.getSource() == itmMagenta)
			{
				color = Color.MAGENTA;
				itmMagenta.setState(true);
			}
			else if (ie.getSource() == itmYellow)
			{
				color = Color.YELLOW;
				itmYellow.setState(true);
			}
			else if (ie.getSource() == itmSilver)
			{
				color = Color.GRAY;
				itmSilver.setState(true);
			}
			else if (ie.getSource() == itmBlack)
			{
				color = Color.BLACK;
				itmSilver.setState(true);
			}
			
		}
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		if (ae.getSource() == itmExit)
			System.exit(0);
	}
	
	//methods in MouseListener interface
	public void mouseClicked(MouseEvent me){}
	public void mouseEntered(MouseEvent me){/*setBackground(Color.RED);*/}
	public void mouseExited(MouseEvent me){/*setBackground(Color.WHITE);*/}
	public void mousePressed(MouseEvent me)
	{
		if (currentShape.equals("line"))
		{
			if (me.getButton() == MouseEvent.BUTTON1)
			{
				x1 = me.getX();
				y1 = me.getY();
				oldX = oldY = -10;
			}
		}
		else if(currentShape.equals("box") || currentShape.equals("oval"))
		{
			if (me.getButton() == MouseEvent.BUTTON1)
			{
				x1 = me.getX();
				y1 = me.getY();
				oldWidth = oldHeight = 0;
			}
		}

	}
	public void mouseReleased(MouseEvent me)
	{
		if (currentShape.equals("line"))
		{
			x2 = me.getX();
			y2 = me.getY();			
			MyLine ml = new MyLine(x1,y1,x2,y2,color);
			alShape.add(ml);
		}
		else if (currentShape.equals("box"))
		{
			MyBox mb = new MyBox(x,y,width,height,color);
			oldX = oldY = -10;
			oldWidth = oldHeight = 0;
			alShape.add(mb);
		}
		else if (currentShape.equals("oval"))
		{
			MyOval mo = new MyOval(x,y,width,height,color);
			oldX = oldY = -10;
			oldWidth = oldHeight = 0;
			alShape.add(mo);
		}
		repaint();
	}
	
	
	
	//methods in MouseMotionListener interface
	public void mouseDragged(MouseEvent me)
	{
		Graphics g;
		g = getGraphics();
		g.setColor(color);
		g.setXORMode(getBackground());
		
		if (currentShape.equals("line"))	
		{
			//first erase the old line
			if (oldX != -10 && oldY != -10)
				g.drawLine(x1,y1,oldX,oldY);
			
			//draw the new line
			x2 = me.getX();
			y2 = me.getY();
			g.drawLine(x1,y1,x2,y2);
			
			
			//store the current coordinates
			oldX = x2;
			oldY = y2;
		}
		else if (currentShape.equals("box") || currentShape.equals("oval"))
		{
			
			x2 = me.getX();
			y2 = me.getY();
			
			if (x1 <= x2)
			{
				width = x2 - x1;
				x = x1;
			}
			else
			{
				width = x1 - x2;
				x = x1 - width;
			}
			
			if (y1 <= y2)
			{
				height = y2 - y1;
				y = y1;
			}
			else
			{
				height = y1 - y2;
				y = y1 - height;
			}
			
			//first erase the old box
			if (currentShape.equals("box"))
			{
				if (oldWidth != 0 && oldHeight != 0)
					g.drawRect(oldX,oldY,oldWidth,oldHeight);
			}
			else 
			{
				if (oldWidth != 0 && oldHeight != 0)
					g.drawOval(oldX,oldY,oldWidth,oldHeight);
			}					
				
			//draw the new box
			if (currentShape.equals("box"))
				g.drawRect(x,y,width,height);
			else
				g.drawOval(x,y,width,height);
			
			//store the x, y, widht and height
			oldX = x;
			oldY = y;
			oldWidth = width;
			oldHeight = height;
				
		}
	}
	
	public void mouseMoved(MouseEvent me){}
	
	public void paint(Graphics g)
	{
		int i;
		for (i=0;i<alShape.size();i++)
		{
			MyShape ms = (MyShape)alShape.get(i);
			ms.draw(g);
		}
	}
}

Save MyShape.java

import java.awt.*;

abstract class MyShape
{
	private String shapeName;
	private Color color;
	
	MyShape(String shapeName){this.shapeName = shapeName;}
	
	void setShapeName(String shapeName){this.shapeName = shapeName;}
	
	String getShapeName(){return shapeName;}
	
	void setColor(Color color){this.color = color;}
	Color getColor(){return color;}
	
	abstract void draw(Graphics g);
}

Save MyOval.java

import java.awt.*;

class MyOval extends MyShape
{
	private int x, y, width, height;
		
	MyOval(int x, int y, int width, int height, Color color)
	{
		super("Oval");
		setColor(color);
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
	
	void draw(Graphics g)
	{
		Color currentColor = g.getColor();
		g.setColor(getColor());
		g.drawOval(x,y,width,height);
		g.setColor(currentColor);
	}
}

Save MyLine.java

import java.awt.*;

class MyLine extends MyShape
{
	private int x1, y1, x2, y2;
	
	MyLine(int x1, int y1, int x2, int y2, Color color)
	{
		super("line");
		setColor(color);
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
	}
	
	void draw(Graphics g)
	{
		Color currentColor = g.getColor();
		g.setColor(getColor());
		g.drawLine(x1,y1,x2,y2);
		g.setColor(currentColor);
	}
}

Save MyBox.java

import java.awt.*;

class MyBox extends MyShape
{
	private int x, y, width, height;
		
	MyBox(int x, int y, int width, int height, Color color)
	{
		super("Box");
		setColor(color);
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
	
	void draw(Graphics g)
	{
		Color currentColor = g.getColor();
		g.setColor(getColor());
		g.drawRect(x,y,width,height);
		g.setColor(currentColor);
	}
}

Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Menu


Introduction of Java Menu


Programm

Save MyFrameListener.java

import java.awt.event.*;
class MyFrameListener extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame implements ActionListener
{
	MenuBar menubar;
	Menu mnuFile;
	MenuItem itmNew, itmOpen, itmSave, itmSaveAs, itmExit;
	
	TextArea txtEditor;
	
	
	MyFrame()
	{
		super("Menu Demo");
		setSize(600,400);
		addMenu();
		addControls();
		addWindowListener(new MyWindowAdapter());
		setVisible(true);
	}
	
	private void addMenu()
	{
		menubar = new MenuBar();
		
		mnuFile = new Menu("File");
		
		itmNew = new MenuItem("New", new MenuShortcut(KeyEvent.VK_N));
		itmOpen = new MenuItem("Open", new MenuShortcut(KeyEvent.VK_O));
		itmSave = new MenuItem("Save", new MenuShortcut(KeyEvent.VK_S));
		itmSaveAs = new MenuItem("Save As");
		itmExit = new MenuItem("Exit", new MenuShortcut(KeyEvent.VK_X, true));
		
		mnuFile.add(itmNew);
		mnuFile.add(itmOpen);
		mnuFile.addSeparator();
		mnuFile.add(itmSave);
		mnuFile.add(itmSaveAs);
		mnuFile.addSeparator();
		mnuFile.add(itmExit);
				
		for (int i = 0;i<mnuFile.getItemCount(); i++)
			mnuFile.getItem(i).addActionListener(this);
		
		menubar.add(mnuFile);
		
		setMenuBar(menubar);
	}
	
	private void addControls()
	{
		txtEditor = new TextArea();
		add(txtEditor);
	}
	
	private boolean saveFile()
	{
		String fileName = "c:\\Sample.txt";
		boolean flag;
		
		String matter = txtEditor.getText();
		byte aByte[] = matter.getBytes();
		
		try
		{
			FileOutputStream fos = new FileOutputStream(fileName);
			fos.write(aByte);
			fos.flush();
			fos.close();
			flag = true;
		}
		catch (IOException exp){flag = false;}
		
		return flag;
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		if (ae.getSource() == itmExit)
			System.exit(0);
		else if (ae.getSource() == itmSave)
			saveFile();
	}
}


Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Button


Introduction of Java Button


Button is used to perform some task.We can use following method for this purpose.
  1. Constructors
    
    Button(String matter);
    
    
  2. Foreground color method
    
    void setForeground(Color);
    Color getForeground();
    
    
  3. Background color method
    
    void setBackground(Color);
    Color getBackground();
    
    
  4. Location method
    
    void setLocation(int x, int y);
    void setLocation(Point);
    Point getLocation();
    
    
  5. Labe Size method
    
    void setSize(int width, int height);
    void setSize(Dimension);
    Dimension getSize();
    
Programm

Save MyFrameListener.java

import java.awt.event.*;
class MyFrameListener extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame implements ActionListener, TextListener, FocusListener
{
	Label l1, l2, l3;
	TextField t1, t2, t3;
	Button btnAdd, btnSubtract, btnMultiply, btnDivide;
	MyFrame()
	{
		super("Simple Math Calculator");
		setSize(350,200);
		addWindowListener(new MyWindowAdapter());
		setResizable(false);
		addControls();
		setVisible(true);
		enableDisableButtons(false);
	}
	
	private void addControls()
	{
		setLayout(null);
		
		int x, y, hgap, vgap, lblWidth, txtWidth, temp, btnWidth;
		
		y = 35;
		hgap = 3;
		vgap = 3;
		lblWidth = 120;
		txtWidth = 150;
		btnWidth = 80;
		
		temp = (getSize().width - (lblWidth + hgap + txtWidth)) / 2;
		x = temp;
		
		l1 = new Label("Enter first number");
		l1.setSize(lblWidth, 18);
		l1.setLocation(x,y);
		add(l1);
		
		x += lblWidth + hgap;
		
		t1 = new TextField();
		t1.setSize(txtWidth, 20);
		t1.setLocation(x,y);
		add(t1);
		
		x = temp;
		y += 20 + vgap;
		
		l2 = new Label("Enter second number");
		l2.setSize(lblWidth, 18);
		l2.setLocation(x,y);
		add(l2);
		
		x += lblWidth + hgap;
		
		t2 = new TextField();
		t2.setSize(txtWidth, 20);
		t2.setLocation(x,y);
		add(t2);
		
		
		y += 20 + vgap + 20;
		x = (getSize().width - (4*btnWidth + 3*hgap)) / 2;
		
		btnAdd = new Button("Add");
		btnAdd.setSize(btnWidth, 24);
		btnAdd.setLocation(x,y);
		add(btnAdd);
		
		x += btnWidth + hgap;
		
		btnSubtract = new Button("Subtract");
		btnSubtract.setSize(btnWidth, 24);
		btnSubtract.setLocation(x,y);
		add(btnSubtract);
		
		x += btnWidth + hgap;
		
		btnMultiply = new Button("Multiply");
		btnMultiply.setSize(btnWidth, 24);
		btnMultiply.setLocation(x,y);
		add(btnMultiply);
		
		x += btnWidth + hgap;
		
		btnDivide = new Button("Divide");
		btnDivide.setSize(btnWidth, 24);
		btnDivide.setLocation(x,y);
		add(btnDivide);
		
		x = temp;
		y += 24 + vgap + 20;
		
		l3 = new Label("Result");
		l3.setSize(lblWidth, 18);
		l3.setLocation(x,y);
		add(l3);
		
		x += lblWidth + hgap;
		
		t3 = new TextField();
		t3.setSize(txtWidth, 20);
		t3.setLocation(x,y);
		t3.setEditable(false);
		add(t3);
		
		btnAdd.addActionListener(this);
		btnSubtract.addActionListener(this);
		btnMultiply.addActionListener(this);
		btnDivide.addActionListener(this);
		
		t1.addTextListener(this);
		t2.addTextListener(this);
		t1.addFocusListener(this);
		t2.addFocusListener(this);
	}
	
	private void enableDisableButtons(boolean flag)
	{
		btnAdd.setEnabled(flag);
		btnSubtract.setEnabled(flag);
		btnMultiply.setEnabled(flag);
		btnDivide.setEnabled(flag);
	}
	
	public void focusGained(FocusEvent fe)
	{
		TextField tf = (TextField)fe.getSource();
		tf.setSelectionStart(0);
		tf.setBackground(Color.YELLOW);
	}
	public void focusLost(FocusEvent fe)
	{
		TextField tf = (TextField)fe.getSource();
		tf.setBackground(Color.WHITE);
	}
	
	public void textValueChanged(TextEvent te)
	{
		float n1, n2;
		boolean flag = false;
		try
		{
			n1 = Float.parseFloat(t1.getText());
			n2 = Float.parseFloat(t2.getText());
			flag = true;
		}
		catch (NumberFormatException exp)
		{
			flag = false;
		}
		finally
		{
			enableDisableButtons(flag);
		}
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		float n1, n2, n3;
		n1 = Float.parseFloat(t1.getText());
		n2 = Float.parseFloat(t2.getText());
		n3 = 0;
		
		if (ae.getSource() == btnAdd)
			n3 = n1 + n2;
		else if (ae.getSource() == btnSubtract)
			n3 = n1 - n2;
		else if (ae.getSource() == btnMultiply)
			n3 = n1 * n2;
		else if (ae.getSource() == btnDivide)
			n3 = n1 / n2;
			
		t3.setText(Float.toString(n3));
	}
}


Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Text Field


Introduction of Java Text Field


TextField in java used for input purpose.We can use following method for this purpose.
  1. Constructors
    
    TextField()
    TextField(String matter);
    TextField(int width);
    TextField(String matter, int width);
    
    
  2. Text method
    void setText(String matter);
    String getText();
    
    
  3. Foreground color method
    
    void setForeground(Color);
    Color getForeground();
    
    
  4. Background color method
    
    void setBackground(Color);
    Color getBackground();
    
    
  5. Location method
    
    void setLocation(int x, int y);
    void setLocation(Point);
    Point getLocation();
    
    
  6. Labe Size method
    
    void setSize(int width, int height);
    void setSize(Dimension);
    Dimension getSize();
    
  7. Visibility method 
    
    void setVisible(boolean)
    boolean isVisible()
    
  8. Enable and disable method 
    
    void setEnabled(boolean)
    boolean isEnabled()
    
Programm

Save MyFrameListener.java

import java.awt.event.*;
class MyFrameListener extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame
{
	TextField t1, t2, t3, t4;
	
	MyFrame()
	{
		super("Sample Java Frame");
		addWindowListener(new MyWindowAdapter());
		setSize(600,400);
		addControls();
		setVisible(true);
	}
	
	private void addControls()
	{
		setLayout(new FlowLayout());
		
		t1 = new TextField();
		t2 = new TextField("Sample Text Field");
		t3 = new TextField(15);
		t4 = new TextField("Another Text Field",10);
		
		
		t3.setBackground(Color.YELLOW);
		t3.setForeground(Color.RED);
		
		t2.setVisible(true);
		t3.setEnabled(true);
		t4.setEditable(false);
		
		
		
		add(t1);
		add(t2);
		add(t3);
		add(t4);	
	}
}


Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

Java Label


Introduction of Java Label


Label in java used for display static text on frame.We can use following method for this purpose.
  1. Constructors
    
    Label()
    Label(String matter);
    Label(String matter, int alignment)
    
    Value of alignment may be Label.LEFT|Label.RIGHT|Label.CENTER
    
    
  2. Text method
    void setText(String matter);
    String getText();
    
    
  3. Foreground color method
    
    void setForeground(Color);
    Color getForeground();
    
    
  4. Background color method
    
    void setBackground(Color);
    Color getBackground();
    
    
  5. Alignment method
    
    void setAlignment(int)
    int getAlignment()
    
    Value of alignment may be Label.LEFT|Label.RIGHT|Label.CENTER
    
    
  6. Location method
    
    void setLocation(int x, int y);
    void setLocation(Point);
    Point getLocation();
    
    
  7. Labe Size method
    
    void setSize(int width, int height);
    void setSize(Dimension);
    Dimension getSize();
    
Programm

Save MyFrameListener.java

import java.awt.event.*;
class MyFrameListener extends WindowAdapter
{
 public void windowClosing(WindowEvent we)
 {
  System.exit(0);
 }
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame
{
 Label l1, l2, l3;
 
 MyFrame()
 {
  super("Sample Java Frame");
  MyWindowAdapter mwa = new MyWindowAdapter();
  addWindowListener(mwa);
  setSize(500,300);
  addControls();
  setVisible(true);
 }
 
 private void addControls()
 {
  int lblWidth, lblHeight, x, y; 
   
  x = 10;
  y = 50;
  lblWidth = 150;
  lblHeight = 20;
  
  setLayout(null);
  
  l1 = new Label();
  l2 = new Label("I am a sample Label");
  l3 = new Label("Yet one more label", Label.RIGHT);
  
  l1.setText("This is to display static text");
  
  l1.setBackground(Color.YELLOW);
  l2.setBackground(Color.GREEN);
  l3.setBackground(Color.GRAY);
  
  l2.setAlignment(Label.CENTER);
  
  l1.setForeground(Color.RED);
  
  
  l1.setSize(lblWidth, lblHeight);
  l2.setSize(lblWidth, lblHeight);
  l3.setSize(lblWidth, lblHeight);
  
  l1.setLocation(x,y);
  l2.setLocation(x,y+50);
  l3.setLocation(x,y+100);
    
  
  add(l1);
  add(l2);
  add(l3);
 }
}


Save GUI1.java

public class GUI1
{
 public static void main(String args[])
 {
  MyFrame mf = new MyFrame();
 }
}

Java Frame


Introduction of Java Frame



The frame in java works like the main window where your components (controls) are added to develop an application.
Frame in java created by extending Frame class. After this we need to set following things.
  • Title of frame We set title of frame using super() method.
  • Size of frame We set size of frame using setSize(width,height) method.
  • Location of frame We set location of frame using setLocation(x,y) method.
  • Background Color of frame We set Background Color of frame using setBackground() method
  • Visibility of frame We set Visibility of frame using setVisibile() method.
Frame without close button

Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame
{
 MyFrame()
 {
  super("Sample Java Frame");
  setBackground(Color.YELLOW);
  setSize(600,400);
  setUndecorated(true);
  setLocation(50,50);
  setResizable(false);
  setVisible(true);
 }
}


Save GUI1.java

public class GUI1
{
 public static void main(String args[])
 {
  MyFrame mf = new MyFrame();
 }
}

Frame with close button

Save MyFrameListener.java

import java.awt.event.*;
class MyFrameListener extends WindowAdapter
{
 public void windowClosing(WindowEvent we)
 {
  System.exit(0);
 }
}


Save MyFrame.java 
 
import java.awt.*;
class MyFrame extends Frame
{
 MyFrame()
 {
  super("Sample Java Frame");
  setBackground(Color.YELLOW);
  setSize(600,400);
  setUndecorated(true);
  setLocation(50,50);
  setResizable(false);
  setVisible(true);
 }
}


Save GUI1.java

public class GUI1
{
 public static void main(String args[])
 {
  MyFrame mf = new MyFrame();
 }
}

Wednesday, 5 September 2012

Java Thread


Introduction of Java Thread


A thread is a program's path of execution. In other words, a thread is a single sequential flow of control within a program. 
A thread, by definition is a light weight process. They are used to increase functionality and performance by performing multiple tasks at the same time, i.e. concurrently. There are two methods for implementing threads in Java,
  • Extending Thread class
  • Implementing Runnable interface
 By Extending Thread class
 
 Save Job.java
 
 class Job extends Thread
{
 private int start;
 private int stop;
 private String name;
 
 Job(String name, int start, int stop)
 {
  this.name = name;
  this.start = start;
  this.stop = stop;
 }
 
 public void run()
 {
  performJob();
 }
 
 public void doJob()
 {
  start();
 }
 
 private void performJob()
 {
  System.out.println(name + " started...");
  int i;
  for (i=start;i<=stop;i++)
  {
   System.out.println(name + " : " + i);
  }
  System.out.println(name + " terminated...");
 }
}

Save MT1.java

public class MT1
{
 public static void main(String args[])
 {
  System.out.println("Main Thread Started...");
  Job j1, j2, j3;
  j1 = new Job("Job1",1,30);
  j2 = new Job("Job2",60,90);
  j3 = new Job("Job3",180,210);
  j1.doJob();
  j2.doJob();
  j3.doJob();
    }
}

By implementing Runnable interface

Save Job.java
 
 class Job implements Runnable
{
private int start;
 private int stop;
 private String name;
 Thread t;
 
 Job(String name, int start, int stop)
 {
  this.name = name;
  this.start = start;
  this.stop = stop;
  t = new Thread(this);
 }
 
 public void performJob()
 {
  t.start();
 }
 
 public void run()
 {
  doJob();
 }
 
 private void doJob()
 {
  System.out.println(name + " started...");
  for (int i=start; i<=stop; i++)
   System.out.println(name + " : " + i);
  System.out.println(name + " terminated...");   
 }
}

Save MT1.java

public class MT1
{
 public static void main(String args[])
 {
  System.out.println("Main Thread Started...");
  Job j1, j2, j3;
  j1 = new Job("Job1",1,30);
  j2 = new Job("Job2",60,90);
  j3 = new Job("Job3",180,210);
  j1.doJob();
  j2.doJob();
  j3.doJob();
    }
}

Sunday, 19 August 2012

Online Java tutorial


Introduction of Java


The language, initially called Oak. James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects.
Java is an object-oriented language, and this is very similar to C++. Java Programming Language is simplified to eliminate language features that cause common programming errors. Java source code files are compiled into a format called bytecode, which can then be executed by a Java interpreter.
Java is slow in speed due to following reasons.
  • Dynamic Linking Unlike C, linking is done at run-time , every time the program is run in Java.
  • Run-time Interpreter The conversion of byte code into native machine code is done at run-time in Java which furthers slows down the speed
Points to remember
  1. Java states Write Once, Run Anywhere
    This means java is platform independent language.
  2. Java virtual machine (JVM) A Java virtual machine (JVM) is a virtual machine that can execute Java bytecode. It is the code execution component of the Java software platform
  3. Java bytecode Java bytecode is an intermediate language which is typically compiled from Java, but it can also be compiled from other programming languages.
  4. Java execution environment is termed the Java Runtime Environment, or JRE.
  5. Programs intended to run on a JVM must be compiled into a standardized portable binary format, which typically comes in the form of .class files. A program may consist of many classes in different files. For easier distribution of large programs, multiple class files may be packaged together in a .jar file (short for Java archive).
java virtual machine

Java Basic


Introduction of Java Basic



Rules for class declarations
  1. Class Names For all class names the first letter should be in Upper Case.
  2. Method Names All method names should start with a Lower Case letter.
  3. Program File Name Name of the program file should exactly match the class name.
  4. public static void main(String args[]) java program processing starts from the main() method which is a mandatory part of every java program.
Example :

public class DemoProgram{

    public static void main(String []args){
    
        // write your code
    }
} 

Environment Setup
  1. Windows
    • Right-click on 'My Computer' and select 'Properties'.
    • Click on the 'Environment variables' button under the 'Advanced' tab.
    • Click on Path variable
    • Append Path variable's value by adding this line
      ;c:\Program Files\java\jdk\bin
Compile and Run java program
  1. First point to your java bin directory by using cmd
  2. Then use following command to compile

    javac filename.java
  3. Then run program using following command

    java filename.java

Java Output Functions


Introduction of Java Output Function (System.out.println())



Java use print function to display out. It can be used in two way.
  1. Output without new line
    For this purpose we use
    System.out.print('desired output string');
    
  2. Output with new line
    For this purpose we use
    System.out.println('desired output string');
    
  3. Example :
Save this file with Test.java

class CRectangle
 {
  private int length;
  private int breadth;
  
  CRectangle()
  {
   System.out.println("Class CRectangle : Default constructor called...");
   length = 5;
   breadth = 3;
  }
  
  CRectangle(int l, int b)
  {
   System.out.println("Class CRectangle : Parametrized constructor called..");
   length = l;
   breadth = b;
  }
  
  void setLength(int l){length = l;}
  int getLength(){return length;}
  
  void setBreadth(int b){breadth = b;}
  int getBreadth(){return breadth;} 
}
import java.io.*;
class Test
{
 public static void main(String args[])
 {
  CRectangle r;
  r = new CRectangle();
  System.out.println("Length  : " + r.getLength());
  System.out.println("Breadth : " + r.getBreadth());
 }
}

Java Input Functions


Introduction of Java Input (readLine())


To take input in java we use readLine() function. This function takes input inform of string.

Process to take input in java
  1. Include console class in file

    import java.io.Console;
  2. Use System console
    Console con=System.console();
  3. Use readLine() method to take input
    String str=con.readLine('message');
    
Save this file Test.java

class CRectangle
 {
 	private int length;
 	private int breadth;
 	
 	CRectangle()
 	{
 		System.out.println("Class CRectangle : Default constructor called...");
 		length = 5;
 		breadth = 3;
 	}
 	
 	CRectangle(int l, int b)
 	{
 		System.out.println("Class CRectangle : Parametrized constructor called..");
 		length = l;
 		breadth = b;
 	}
 	
 	void setLength(int l){length = l;}
 	int getLength(){return length;}
 	
 	void setBreadth(int b){breadth = b;}
 	int getBreadth(){return breadth;} 
}
import java.io.*;
import java.io.console;
class Test
{
	public static void main(String args[])
	{
	    int length,breadth;
	    Console con=System.console();
	    length=Integer.parseInt(con.readLine('length enter'));
	    breadth=Integer.parseInt(con.readLine('breadth enter'));
		CRectangle r;
		r = new CRectangle(length,breadth);
		System.out.println("Length  : " + r.getLength());
		System.out.println("Breadth : " + r.getBreadth());
	}
}

Java Static Property


Introduction of Java Static property



Java is object based language where each object has it's own variables and functions. But If we want to share a single variable or function we need to make it static. So we can say

The shared members of the class do not get created individually for each and every object/instance of the class. Rather a single copy of them exist in the memory. This single copy is shared by all the instances of the class. To make a member of the class shared, we make use of the keyword static. 

Points to be remember
  1. The static members of the class always exist in the memory. Instance members exist only when an object is created.
  2. The shared members of the class can refer only other shared members of the class. They cannot refer the instance members of the class. However, the instance members can refer all (instance as well as shared) members of the class.
  3. The shared members belong to the entire class not to an individual instance of the class. If one instance updates the value of shared members, then all other instances get the updated values.
  4. Syntex for static variable
    
    static datatype variable-name;
    
  5. Attention : Static variable cann't be initialized in class contructor in java. we can do in following way
    Initialization of static variable
    
    static 
    {
    		variable-name =value;
    }
    
    
  6. Static variable accessed using class name
    Syntex :
    
    classname.staticvariablename;
    
  7. We can use static function for accessing static variables
    Syntext :
    
    static return-type function-name()
    {
    write your code
    }
    
  8. Static function also accessed using class name
    Syntex :
    
    classname.staticfunctionname();
    
Example : Save this file StaticClass.java


class CCircle
{
	private float radius;
	private static float pi;
	
	static 
	{
		pi = 22 / 7.0f;
	}
	CCircle(float r)
	{
		radius = r;
	}
	float getArea()
	{
		return pi * radius * radius;
	}
	
	float getCircumference()
	{
		return 2 * pi * radius;
	}
	
	static void showPi()
	{
		System.out.println("Value of pi = " + pi);
	}
	
	void show()
	{
		System.out.println("Radius        : " + radius);
		System.out.println("Diameter      : " + 2*radius);
		System.out.println("Area          : " + getArea());
		System.out.println("Circumference : " + getCircumference());
	}
}
public class StaticClass
{
	public static void main(String args[])
	{
		CCircle.showPi();
		c1 = new CCircle(4.5f);		
		c1.show();
    }
}

Array in Java

Introduction of Array In Java


Array is used to store similar type of elements. 


Array declaration :
For one dimensional

datatype arrayname[]=new datatype[size];

or

datatype arrayname[]={val1,val2.....valn};

For Two dimensional

datatype arrayname[][]=new datatype[rows][cols];

or

datatype arrayname[][]={
                       {val1,val2.....valn},
                       {val1,val2.....valn},
                       {val1,val2.....valn}
                       
                     };
Note
  1. To check size of array
    Syntex :
    arrayname.length
    
  2. To check size of individual row of array
    Syntex :
    arrayname[row-number].length
    
Save this file ArrayDemo.java

public class ArrayDemo
{
	public static void main(String args[])
	{
		int a[] = {34,345,6,89,76,34,34,56,78,89,56,23,23,45,34};
		int b[][] = 	{
							{1,2,3,4},
							{5,6,7,8}
						};
		int i, j; 
			
			
		System.out.println("Contents of A....");
		for (i=0;i<a.length;i++)
			System.out.println(a[i]);
			
			
		System.out.println("Contents of B....");
		for (i=0;i<b.length;i++)			
		{
			System.out.println();
			for (j=0;j<b[i].length;j++)	
				System.out.print(b[i][j] + "   ");
		}
		
		System.out.println();	
	}
}
Save this file ArrayDemo.java


import java.io.*;

public class ArrayDemo
{
	public static void main(String args[])
	{
		int num[][], i, j;
		num = new int[5][8];
		
		System.out.println(num.length);
		
		for (i=0;i<num.length;i++)
		{
			System.out.println("num[" + i + "] is an array with " + num[i].length + " elements");
		}
		
		Console console = System.console();
		for (i=0;i<num.length;i++)
		{
			System.out.println("Reading row #" + i + "....");
			for (j=0;j<num[i].length;j++)
			{
				System.out.print("Enter value #" + j + " : ");
				num[i][j] = Integer.parseInt(console.readLine());
			}
		}
		
		System.out.println("You entered the following values....");
		for (i=0;i<num.length;i++)
		{
			System.out.println();
			for (j=0;j<"num[i].length";j++)
				System.out.print(num[i][j] + "       ");
		}
	}
}

Jagged Array in Java


Introduction of Jagged Array In Java


Array is which number of colums different in each row called jagged array.

Jagged Array declaration :
datatype arrayname[][]=new datatype[rows][];
         arrayname[row0][]=new datatype[col-value1];
         arrayname[row1][]=new datatype[col-value2];
         arrayname[row2][]=new datatype[col-value3];
or

datatype arrayname[][]={
                       {val1,val2.....valn0},
                       {val1,val2.....valn1},
                       {val1,val2.....valn2}
                       
                     };
Note
  1. To check size of array
    Syntex :
    arrayname.length
    
  2. To check size of individual row of array
    Syntex :
    arrayname[row-number].length
    
Save this file ArrayDemo.java
import java.io.*;

public class ArrayDemo
{
	public static void main(String args[])
	{
		int num[][], i, j;
		 
		num = new int[6][];
		num[0] = new int[7];
		num[1] = new int[14];
		num[2] = new int[12];
		num[3] = new int[8];
		num[4] = new int[3];
		num[5] = new int[13];
		
		for (i=0;i<num.length;i++)
		{
			System.out.println();
			for (j=0;j<num[i].length;j++)
				System.out.print(num[i][j]);
		}
		System.out.println();	
	}
}

String In Java


Introduction of Java String


Java provide String objcect in which we directly store array of character.
Declaration of string object

String string-variable=new String('initial value');

or 

String string-variable='initial value';

String related functions

  1. length() this function determine length of string.
    Syntex :
    String str='initial value';
    
    str.length();
    
  2. toLowerCase() this function convert string to lower case
    Syntex :
    String str='initial value';
    
    str.toLowerCase();
    
  3. toUpperCase() this function convert string to upper case.
    Syntex :
    String str='initial value';
    
    str.toUpperCase();
    
  4. equals() This function check equality of two string. It consider case of both string.
    Syntex :
    String str='initial value';
    String str2='value2';
    str.equals(str2);
    
  5. equalsIgnoreCase() This function check equality of two string. It didn't consider case of both string.
    Syntex :
    String str='initial value';
    String str2='value2';
    str.equalsIgnoreCase(str2);
    
  6. indexOf() this function returns index of search string. This search from left to right and stops after first match string.
    Syntex :
    String str='initial value';
    
    str.indexOf('search value');
    
  7. indexIndexOf() this function returns index of search string. This search from right to left and stops after first match string.
    Syntex :
    String str='initial value';
    
    str.indexIndexOf('search value');
    
    
  8. substring() This function extract string with our specified positions.
    Syntex :
    String str='initial value';
    
    str.substring(string position,end position);
    
  9. trim() This function trims left and right blank spaces from string.
    Syntex :
    String str='  initial value  ';
    
    str.trim();
    
  10. replace() this function replace our search string with our new string.
    Syntex :
    String str='initial value';
    
    str.replace('search string','replace string');
    
Save This file StringDemo.java


public class StringDemo
{
	public static void main(String args[])
	{
		String s1 = "This is some sample string";
		String s2 = new String("This is some sample string");
		
		char aChar[] = {'a','b','c','d','e','f'};
		String s3 = new String(aChar);
		
		
		byte aByte[] = {65,66,67,68,69,70};
		String s4 = new String(aByte);
		
		String s5 ="This is some sample string";
		
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s3);
		System.out.println(s4);
		
		
		//To determine the no. of characters in the string.
		System.out.println("Length of string : " + s1.length());
		
		//to convert the string into lower case
		System.out.println(s1.toLowerCase());
		
		//to convert the string into upper case
		System.out.println(s1.toUpperCase());
		
		//Original string
		System.out.println(s1);
		
		
		aByte = s1.getBytes();
		int i;
		for (i=0;i<aByte.length;i++)
		{
			System.out.println(aByte[i]);
			aByte[i] = (byte)(aByte[i] + 10);
		}
			
		s5 = new String(aByte);
		
		System.out.println("Encrypted String : " + s5);
		
		aByte = s5.getBytes();
		for (i=0;i<aByte.length;i++)
			aByte[i] = (byte)(aByte[i] - 10);
			
		s5 = new String(aByte);
		System.out.println("Decrypted String : " + s5);
		
		
		
		//to compare the contents of two strings
		System.out.println(s1.equals(s2));
		
		s5 = "This is Some Sample String";
		System.out.println(s1.equals(s5));			
		System.out.println(s1.equalsIgnoreCase(s5));
		
		
		//to determine if a sub string exists within the string...
		s1.contains("AMP");
		s1.toLowerCase().contains("AMP".toLowerCase());
		
		
		System.out.println(s1.indexOf("is",3));
		
		
		s1 = "this is some sample string which is being used in this example. 
		it contains is multiple times";
		int position = -1;
		do
		{
			position = s1.indexOf("is",position+1);
			if (position != -1)
			{
				System.out.println("is found at index : " + position);
			}
		} while (position != -1);
		
		
		System.out.println(s1.lastIndexOf("is", 75));
		
		
		
		//to extract a part of string
		System.out.println(s1.substring(13,19));
		
		
		//to remove the leading and tralining spaces
		s1 = "    this    is    string    with    multiple    spaces    ";
		System.out.println("|" + s1.trim() + "|");
		
		
		//to break the string on the basis of some particular token we have
		s1 = "This is some sample string";
		String aWord[] = s1.split(" ");
		for (i=0;i<aWord.length;i++)
			System.out.println(aWord[i]);
			
			
		//to replace a substring within the main string
		System.out.println(s1.replace("s","SSSSSS"));	
			
		
	}
}

Abstract Class In Java


Introduction of Java Abstract Class


Facts for abstract class
  1. Its possible to create a refrence varible of an abstract class. Howerver its not possible to create an object of abstract class.
  2. The object of sub class = object of super class + some new features.
  3. Because of above fact, its possible to store the reference of sub class object into the reference variable of super class.
  4. Although, its possible to have a reference variable of super class, and in it we can store the reference of an object of sub class. However, through such a reference varible(reference is of super class and object is of sub class), we can access only those members of the sub class which the sub class had aquired or inherited from the super class. The new features (new data members, methods) that have been added to the sub class can't be access by the super class reference varible.
Save This file AbstractDemo.java

abstract class CShape
{
	private String shapeName;
	
	CShape(){shapeName = "Undefined";}
	CShape(String shapeName){this.shapeName = shapeName;}
	
	abstract float getArea();
	abstract float getPerimeter();
	abstract void inputDimensions();
	
	void show()
	{
		System.out.println("Shape : " + shapeName);
	}
}
import java.io.*;
class CRectangle extends CShape
{
	private int length;
	private int breadth;
	
	CRectangle()
	{
		super("Rectagle");
	}
	
	void inputDimensions()
	{
		Console console = System.console();
		System.out.print("Enter length : ");
		length = Integer.parseInt(console.readLine());
		System.out.print("Enter breadth : ");
		breadth = Integer.parseInt(console.readLine());	
	}
	
	
	float getArea(){return length * breadth;}
	float getPerimeter(){return 2 * (length + breadth);}
	
	void show()
	{
		super.show();
		System.out.println("Length  : " + length);
		System.out.println("Breadth : " + breadth);
		System.out.println();
	}
	
}
import java.io.*;
class CCircle extends CShape
{
	private float radius;
	private static float pi;
	
	static{pi = 22/7.0f;}
	
	CCircle()
	{
		super("Circle");
		radius = 0;
	}
	
	void inputDimensions()
	{
		Console console = System.console();
		System.out.print("Enter radius : ");
		radius = Float.parseFloat(console.readLine());
	}
	
	float getArea()
	{
		return pi * radius * radius;
	}
	
	float getPerimeter()
	{
		return 2 * pi * radius;
	}
	
	void show()
	{
		super.show();
		System.out.println("Radius : " + radius);
		System.out.println();
	}
	
}
public class AbstractDemo
{
	public static void main(String args[])
	{
		CShape shape;
		CRectangle rect  = new CRectangle();
		CCircle circle = new CCircle();
		
		
		
		shape = circle;
		shape = rect;
		
		shape.inputDimensions();
		shape.show();
		
	}
}

Thursday, 16 August 2012

css cursor property tutorial


Introduction of Css Cursor property


css cursor property is used to set mouse cursor display on webpages.

Css cursor property can set follwing values

  1. default this property value sets normal cursor icon.
        Syntex :
        selector
        {
           cursor:default;
        }
        
  2. wait this property value set some processing cursor icon.
        Syntex :
        selector
        {
           cursor:wait;
        }
        
  3. crosshair this property value sets a cross hair cursor icon.
        Syntex :
        selector
        {
           cursor:crosshair;
        }
        
  4. text this property value sets an I like cursor icon.
        Syntex :
        selector
        {
           cursor:text;
        }
        
  5. pointer this property value set a hand icon.
        Syntex :
        selector
        {
           cursor:pointer;
        }
        
  6. help this property value sets a question mark icon.
        Syntex :
        selector
        {
           cursor:help;
        }
        
  7. Click to practice online example

css text decoration property tutorial


Introduction of Css Text Decoration property


css text decoration property is used to change text display.This property is helpful for removing underline from anchor text.

Css text-decoration property can set follwing values

  1. line-through this property value sets a horizontal line between text.
        Syntex :
        selector
        {
           text-decoration:line-through;
        }
        
  2. overline this property value set horizontal line above text.
        Syntex :
        selector
        {
           text-decoration:overline;
        }
        
  3. underline this property value sets horizontal line below text.
        Syntex :
        selector
        {
           text-decoration:underline;
        }
        
  4. none this property value remove all text-decoration styles.
        Syntex :
        selector
        {
           text-decoration:none;
        }
        
  5. Click to practice online example

css text align property tutorial


Introduction of Css Text Align property


Css text-align property is used to set alignment of text.

Css text-align property can set follwing values

  1. left this property value sets alignment of text to left.
        Syntex :
        selector
        {
           text-align:left;
        }
        
  2. right this property value sets alignment of text to right.
        Syntex :
        selector
        {
           text-align:right;
        }
        
  3. justify this property value sets alignment of text to justify. This way automatically sets lift and right margin for each line.
        Syntex :
        selector
        {
           text-align:justify;
        }
        
  4. Click to practice online example

css text indent property tutorial


Css text-indent property is used to set white space befor any text. This property is helpful for generation of paragraph where we can set white space before starting of paragraph.

Css text-indent property can set follwing values

  1. positive value in pixel this property value sets white space in pixel in right direction.
        Syntex :
        selector
        {
           text-indent:20px;
        }
        
  2. negative value in pixel this property value sets white space in pixel in left direction.
        Syntex :
        selector
        {
           text-indent:-20px;
        }
        
  3. positive value in percentage this property value sets white space in percentage in right direction
        Syntex :
        selector
        {
           text-indent:10%;
        }
        
  4. negative value in percentage this property value sets white space in percentage in left direction
        Syntex :
        selector
        {
           text-indent:-20%;
        }
        
  5. Click to practice online example

css text transform property tutorial


Introduction of Css Text Transform property


Css text-transform property is used to set text from uppercase to lowercase or vice-virca.

Css text-transform property can set follwing values

  1. capitalize this property value sets first letter of each to uppercase.
        Syntex :
        selector
        {
           text-transform:capitalize;
        }
        
  2. uppercase this property value sets each letter to uppercase.
        Syntex :
        selector
        {
           text-transform:uppercase;
        }
        
  3. lowercase this property value sets each letter to lowercase.
        Syntex :
        selector
        {
           text-transform:lowercase;
        }
        
  4. Click to practice online example

Wednesday, 15 August 2012

css padding property tutorial


Introduction of Css Padding property


css padding property is used to set whitespace inside the border of html element.
css padding

We can also implement seperate padding for each(left,top,right,bottom).

  • padding-left :
        Syntex :
        selector
        {
           padding-left:2px;
        }
        
  • padding-top :
        Syntex :
        selector
        {
           padding-top:2px;
        }
        
  • padding-right :
        Syntex :
        selector
        {
           padding-right:2px;
        }
        
  • padding-bottom :
        Syntex :
        selector
        {
           padding-bottom:2px;
        }
        
We can also apply padding in single line.
    Syntex :
    selector
    {
       padding:1px;
    }
    
Click to practice online example

css white space,word spacing,letter spacing property tutorial


Introduction of Css white space,word spacing,letter spacing property



Css white-space,word-spacing,letter-spacing property is used to set white spacing in text.
  1. white-space this property value allow you to prevent text wraping.If you place <br/> then it wrap text.
        Syntex :
        selector
        {
           white-space:nowrap;
        }
        
  2. word spacing this property value sets spacing between words.
        Syntex :
        selector
        {
           word-spacing:10px;
        }
        
  3. letter-spacing this property value sets spacing beween letter.
        Syntex :
        selector
        {
           letter-spacing:10px;
        }
        
  4. Click to practice online example

css margin property tutorial


Introduction of Css Margin property

css margin property is used to set whitespace outside the border of html element.
css margin

We can also implement seperate margin for each(left,top,right,bottom).

  • margin-left :
        Syntex :
        selector
        {
           margin-left:2px;
        }
        
  • margin-top :
        Syntex :
        selector
        {
           margin-top:2px;
        }
        
  • margin-right :
        Syntex :
        selector
        {
           margin-right:2px;
        }
        
  • margin-bottom :
        Syntex :
        selector
        {
           margin-bottom:2px;
        }
        
We can also apply margin in single line.
    Syntex :
    selector
    {
       margin:1px;
    }
    
Click to practice online example

Sunday, 12 August 2012

css border property tutorial


Introduction of Css Border property


css background property is used to set border around html tag. Css border works with cordination of three sub properties.
  1. border-style : This property sets style of border. We can choose some predefined styles.Which are
    • solid
    • double
    • groove
    • dotted
    • dashed
    • inset
    • outset
    • ridge
    • hidden
        Syntex :
        selector
        {
          border-style :solid;
        }
        
  2. border-width : This property sets width of border. Values are in px,thick,medium.
        Syntex :
        selector
        {
          border-width :7px;
        }
     
  3. border-color : This property sets color of border.
        Syntex :
        selector
        {
          border-color :red;
        }
     
  4. Example
        Syntex :
        selector
        {
           border-width:2px;
           border-style:solid;
           border-color:red;
        }
        
    Click to practice online example

We can also implement seperate border for each(left,top,right,bottom).

  • border-left :
        Syntex :
        selector
        {
           border-left-width:2px;
           border-left-style:solid;
           border-left-color:red;
        }
        
  • border-top :
        Syntex :
        selector
        {
           border-top-width:2px;
           border-top-style:solid;
           border-top-color:red;
        }
        
  • border-right :
        Syntex :
        selector
        {
           border-right-width:2px;
           border-right-style:solid;
           border-right-color:red;
        }
        
  • border-bottom :
        Syntex :
        selector
        {
           border-bottom-width:2px;
           border-bottom-style:solid;
           border-bottom-color:red;
        }
        
We can also apply border in single line. In this way first we need to set border width then border style and in last border color.
    Syntex :
    selector
    {
       border:1px solid red;
    }
    
Click to practice online example

css font property tutorial


Introduction of Css Font property


css Font property is used to text display of webpage.css provides several properties related to font.
  Syntex :
    selector
    {
      font-family  : value;
      font-size    : value;
      font-style   : value;
      font-weight  : value;
      font-variant : value;
    }
 
Detailed font properties
  1. font-family : This property change font family of text. We can use common font-family(sans-serif,serif,arial).
        Syntex :
        selector
        {
          font-family : arial;
        }
        
  2. font-size : This property change font-size of text.
        Syntex :
        selector
        {
          font-size : 10px;
        }
        
  3. font-style : This property change font-style of text. Using this we can set italic,oblique,normal values for html text.
        Syntex :
        selector
        {
          font-style : bold;
        }
        
  4. font-weight : This property sets thickness of font. It's value always multiple of 100.
        Syntex :
        selector
        {
          font-weight : 300;
        }
        
  5. font-variant : This property is used to change upper case to lower case or lower case to upper case.we can use small-caps,upper-caps.
        Syntex :
        selector
        {
          font-variant : small-caps;
        }
        
  6. Example
        Syntex :
        selector
        {
           font-family : arial;
           font-size : 10px;
           font-style : bold;
           font-weight : 300;
           font-variant : small-caps;
        }
        
    Click to practice online example

css color property tutorial


Introduction of Css Color property


css color property is used to change foreground-color of html text.
  Syntex :
    selector
    {
      color :color-name or color-value;
    }
 
color value can be in following way
  1. Direct color-name : We can use direct color name(red,green).
        Syntex :
        selector
        {
          color :red;
        }
        
  2. Using Hash value :We can use hash value(#aabbcc)
        Syntex :
        selector
        {
          color :#aabbcc;
        }
        
  3. Using RGB combination : We can built color using rgb cobmination
        Syntex :
        selector
        {
          color :rgb(10,20,30);
        }
        
  4. Example
        Syntex :
        selector
        {
          color :red;
        }
        
    Click to practice online example