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();
    }
}