Java Examples

Util package

Hashtable example to add user defined objects

Contact.java

public class Contact {
	
	private String name, number;

		// www.raviroza.com
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}
	
}

Main.java

import java.util.Enumeration;
import java.util.Hashtable;

public class Main {

	public static void main(String[] args) {
		// www.raviroza.com
		
		Hashtable contacts = new Hashtable();
				
		
		Contact c = new Contact();
		
		c.setName("rahul");
		c.setNumber("123");		
		contacts.put(c.getName(),c);
		c= new Contact();
		
		c.setName("abcd");
		c.setNumber("345");
		contacts.put(c.getName(),c);
		
		c = (Contact) contacts.get("abcd");
							
		//System.out.println(contacts.get("ravi"));
		//System.out.println(contacts.get("rahul"));
		
		//System.out.println(" name = "+c.getName());
		
		Enumeration enumeration = contacts.elements();
		while(enumeration.hasMoreElements())
		{
			c = (Contact) enumeration.nextElement();
			System.out.println("key : "+c.getName());
			System.out.println("value : "+c.getNumber());
			System.out.println("-------------------------");
		}
	
	}
}

String Tokenizer example

public class Main {

	public static void main(String[] args) {
		// www.raviroza.com
		
		//String source = "i, am; a string, with; multiple; delimeters, ok!";
		String source = "i am a string with multiple delimeters ok!";
		StringTokenizer tok = new StringTokenizer(source);	
		
		while(tok.hasMoreElements())
		{
			System.out.println("token : " + tok.nextToken());
		}
	}
}

Vector example to add user defined object

main.java

import java.util.Vector;

public class Main 
{
	public static void main(String[] args) 
	{

                       // www.raviroza.com
		Vector vector = new Vector(3);		
		vector.addElement ("xyz");
		vector.addElement (new Integer("100"));
		vector.addElement (new Integer(102));
		vector.addElement (12);
		vector.addElement (new Student("b101", "bol bachhan"));
		vector.addElement (new Student("b102", "2nd bol bachhan"));
		
		Student s=  new Student("b103", "bye bye");
		vector.addElement(s);
		
		for(Object x :  vector)
		{
			System.out.println(x);
		}
		System.out.println("size : " + vector.size());
		System.out.println("capacity : " + vector.capacity());
		//System.out.println("0 element : " + vector.get(0));
		//System.out.println("1 element : " + vector.get(1));
	}
}

student.java

public class Student {

	private String Id, Name;
	
	public Student(String id, String name) {
		super();
		Id = id;
		Name = name;
	}

	public String getId() {
		return Id;
	}

	public void setId(String id) {
		Id = id;
	}

	public String getName() {
		return Name;
	}

	public void setName(String name) {
		Name = name;
	}

	@Override
	public String toString() {
		return "Student [Id=" + Id + ", Name=" + Name + "]";
	}
	
	
}

Abstract class, abstract methods etc.,

vehicle.java

abstract class vehicle
{
	abstract void start();
	abstract void stop();
	void clean()
	{
		System.out.println("vehicle.clean");
	}
}

bike.java

public class bike extends vehicle 
{

	@Override
	void start() {
		// TODO Auto-generated method stub
		System.out.println("bike.start");

	}

	@Override
	void stop() {
		// TODO Auto-generated method stub
		System.out.println("bike.stop");

	}
	void chargeVehicle()
	{
		// regular method in bike class
	}

}

car.java

class car extends vehicle
{	
	void start() 
	{	
		System.out.println("car.start");
	}
	void stop()
	{
		System.out.println("car.stop");
	}
	void playMusic()
	{
		// regular method in car
	}
}

main.java

public class Main {

	public static void main(String[] args) {

/*
		car c = new car();
		c.start();
		c.stop();
		bike b = new bike();
		b.start();
		b.stop();
	*/	
		vehicle v;
		v = new bike();
		v.start();
		v = new car();
		v.start();		
		v.clean();		
	}

}

Exception handling

try/catch/finally example

public class Main 
{
	public static void main(String[] args) 
	{
		System.out.println("start");
		int x=10;
		int n=2;
		System.out.println("process");
		try
		{			
			//System.out.println(args[0]);
			System.out.println(x/n);
			//System.out.println("another print");
		}
		catch(ArithmeticException ae)
		{
			//ae.printStackTrace();
			System.out.println("Error : divide by 0 "+ae.toString());
		}
		catch(ArrayIndexOutOfBoundsException aiof)
		{
			System.out.println("Error : array boundry "+aiof.toString());
		}
		catch(Exception e)
		{
			System.out.println("Error general : array boundry "+e.toString());
		}
		finally {
			System.out.println("finally block");
		}
		System.out.println("end");		
	}
}

Throws example

import java.io.IOException;

class Student 
{	
	public void xyz() throws IOException
	{
		System.out.println("student.xyz() called");
	}
}
public class ThrowsMain 
{
	public static void main(String[] args) 
	{

		Student s = new Student();
		try 
		{
			s.xyz();
		} 
		catch (IOException e) 
		{	
			e.printStackTrace();
		}
	}
}

throw example

public class ThrowMain 
{
	public static void main(String[] args) 
	{
		System.out.println("start");
		int x=10;
		int n=2;
		System.out.println("process");
		try
		{			
			if(n<0)
			{
				ArithmeticException ae = new ArithmeticException ("number is negative");
				throw ae;					
			}
		}
		catch(ArithmeticException ae)
		{		
			System.out.println("Error : " + ae.toString());
		}		
		System.out.println("end");		
	}
}

Custom Exceptions example

class UserInputError extends Exception 
{
	String ErrDesc = "";
	public UserInputError(String ErrDesc) 
	{
		this.ErrDesc = ErrDesc;
	}
	public String toString()
	{
		return ErrDesc;
	}
}
public class TestMyErrors 
{
	public static void main(String[] args) {
		int n = -1;
		try
		{
			if(n<0)
			{
				throw new UserInputError("value is negative");
			}			
		}
		catchUserInputError e)
		{
			System.out.println(e.toString());
		}		
	}
}

Swing GUI application

Arithmetic operation of two numbers

package GUIApplication;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Main 
{

	public static void main(String[] args) 
        {

		new Arithmetic();
		//new Arithmatictable();
		//new LoginApp();
		//new CheckBoxExample();

	}

}

class Arithmetic extends JFrame	implements ActionListener
{
	JLabel lblNum1,lblNum2,lblResult;	
	JTextField txtNum1,txtNum2;
	JButton btnAdd,btnSub,btnMul,btnDiv;
	
	public Arithmatic() {
		// TODO Auto-generated constructor stub
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		setTitle("Arithmatic Operation");
		setLayout(new FlowLayout());
		setSize(400,400);
		setVisible(true);
				
		
		lblNum1 = new JLabel("enter number 1 :");
		lblNum2 = new JLabel("enter number 2 :");
		lblResult = new JLabel("0");
		
		txtNum1 = new JTextField(3);
		txtNum2 = new JTextField(3);
		
		btnAdd = new JButton("+");
		btnSub = new JButton("-");
		btnMul = new JButton("*");
		btnDiv = new JButton("/");
		
		add(lblNum1); add(txtNum1);
		add(lblNum2); add(txtNum2);
				
		add(btnAdd);  add(btnSub);
		add(btnMul);  add(btnDiv);
		
		add(lblResult);
		
		btnAdd.addActionListener(this);
		btnSub.addActionListener(this);
		btnMul.addActionListener(this);
		btnDiv.addActionListener(this);
                pack();	
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		int n1=0,n2=0,result=0;
		
		try
		{
			n1 = Integer.parseInt(txtNum1.getText());
			n2 = Integer.parseInt(txtNum2.getText());
		}
		catch(NumberFormatException nfe)
		{
			
			JOptionPane.showMessageDialog 
				(this, "enter proper number", "Error !",
			JOptionPane.ERROR_MESSAGE);
			txtNum1.requestFocus();
		}
		
		if(e.getSource() == btnAdd)
		{
			
			result = n1 + n2;			
		}
		else if(e.getSource() == btnDiv)
		{
			
			result = n1 / n2;			
		}
		else if(e.getSource() == btnSub)
		{
			result = n1 - n2;			
		}
		else if(e.getSource() == btnMul)
		{
			result = n1 * n2;			
		}
		lblResult.setText(result+"");			
	}		
}

Static Login application using swing

package GUIApplication;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Main 
{

	public static void main(String[] args) 
        {

		//new Arithmetic();
		//new Arithmatictable();
		new LoginApp();
		//new CheckBoxExample();

	}

}
class LoginApp extends JFrame implements ActionListener
{
	
	JLabel lbluser, lblpass, lblstatus;
	JTextField txtuser;
	JPasswordField txtpass;
	JButton btnSubmit, btnReset;
	
	public LoginApp() {
	
		setLayout(new FlowLayout());
		setSize(400,400);
		setVisible(true);
		
		lbluser = new JLabel("Username");
		lblpass = new JLabel("Password");
		lblstatus = new JLabel("...");							
		
		txtuser = new JTextField(10); 
		txtpass = new JPasswordField(10);

		btnSubmit = new JButton("Submit");
		btnReset = new JButton("Reset");
		
		btnReset.addActionListener(this);
		btnSubmit.addActionListener(this);
		
		add(lbluser);	add(txtuser);
		add(lblpass);	add(txtpass);
		add(lblstatus);
		
		add(btnSubmit);	add(btnReset);  
		pack();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource() == btnReset)
		{
			txtuser.setText("");
			txtpass.setText("");			
			lblstatus.setText(".");
			pack();
		}
		else if(e.getSource() == btnSubmit)
		{
			if (txtuser.getText().equals("admin") &&
					txtpass.getText().equals("admin"))
			{		
				lblstatus.setText("success");
				pack();
				txtuser.setText("");
				txtpass.setText("");						
			}			
			else
			{				
				lblstatus.setText("not success");						
				pack();
			}
		}
		
	}
}

My Hobbies application using Swing checkbox

package GUIApplication;

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main 
{

	public static void main(String[] args) 
        {

		//new Arithmetic();
		//new Arithmatictable();
		//new LoginApp();
		new MyHobbies ();
	}

}

class MyHobbies extends JFrame 
implements ItemListener
{

	JCheckBox chkCricket, chkBaseball, chkTennis, chkKabbadi;
	JLabel lblResult;
	String s = "";
	public CheckBoxExample() {
		// TODO Auto-generated constructor stub
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		setTitle("Arithmatic Operation");
		setLayout(new FlowLayout());
		setSize(400,400);
		setVisible(true);
		
		chkCricket = new JCheckBox("Cricket");
		chkBaseball = new JCheckBox("Baseball");
		chkKabbadi = new JCheckBox("Kabbadi");
		chkTennis = new JCheckBox("Tennis");
		lblResult = new JLabel("---");
		
		add(chkBaseball);	add(chkCricket);
		add(chkKabbadi);	add(chkTennis);
		add(lblResult);
		
		pack();
		
		chkBaseball.addItemListener(this);
		chkCricket.addItemListener(this);
		chkKabbadi.addItemListener(this);
		chkTennis.addItemListener(this);
	}
	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
	
		if(e.getSource() == chkBaseball)
		{
			if(chkBaseball.isSelected())
				s += chkBaseball.getText() + " ";
			else
				s=s.replace(chkBaseball.getText(), "");
		
		}
		if(e.getSource() == chkCricket)
		{
			if(chkCricket.isSelected())
				s += chkCricket.getText() + " ";
			else
				s=s.replace(chkCricket.getText(), "");
		
		}
		if(e.getSource() == chkKabbadi)
		{
			if(chkKabbadi.isSelected())
				s += chkKabbadi.getText() + " ";
			else
				s=s.replace(chkKabbadi.getText(), "");
		
		}
		if(e.getSource() == chkTennis)
		{
			if(chkTennis.isSelected())
				s += chkTennis.getText() + " ";
			else
				s=s.replace(chkTennis.getText(), "");
		
		}
		
		lblResult.setText(s);
	}
}

Arithmetic table of given number using swing text area

package GUIApplication;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Main 
{

	public static void main(String[] args) 
        {

		//new Arithmetic();
		new ArithmeticTable();
		//new LoginApp();
		//new MyHobbies ();
	}

}
class ArithmeticTable 
extends JFrame
 implements ActionListener
{
	JLabel lblNum1,lblResult;	
	JTextField txtNum1;
	JButton btndisplay;
        JTextArea ta;	
	public Arithmatictable() {
		// TODO Auto-generated constructor stub
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		setTitle("Arithmatic Table");
		setLayout(new FlowLayout());
		setSize(400,400);
		setVisible(true);
				
		
		lblNum1 = new JLabel("enter number  :");
		//lblResult = new JLabel("0");
		ta = new JTextArea(10,5);
		txtNum1 = new JTextField(3);
	
		
		btndisplay = new JButton("Display");
	
	
		add(lblNum1); add(txtNum1);
		
				
		add(btndisplay);  
		
		//add(lblResult);
		add(ta);
		
		btndisplay.addActionListener(this);
				pack();
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		int n1;
		
		n1 = Integer.parseInt(txtNum1.getText());
								
		
		if(e.getSource() == btndisplay)
		{  

			for(int i=1; i<=10;i++)
			{
			     ta.append((i*n1)+"\n");	
							
			}
			
		}
					
	}		
}

GUI application to change the background color using JScrollBar

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;

public class JScrollTest extends JFrame implements AdjustmentListener {

	JScrollBar jsred,jsblue,jsgreen;
	JLabel lbl;
	// www.raviroza.com
	public JScrollTest()  {
		setLayout(new FlowLayout());
		setSize(500,500);
		setVisible(true);
		
		lbl = new JLabel("     sdfsdf                    ");
		jsred = new JScrollBar(JScrollBar.VERTICAL);
		jsgreen = new JScrollBar(JScrollBar.VERTICAL);
		jsblue = new JScrollBar(JScrollBar.VERTICAL);
				
		jsred.setMinimum(0);
		jsred.setMaximum(255);
		
		jsgreen.setMinimum(0);
		jsgreen.setMaximum(255);
		
		jsblue.setMinimum(0);
		jsblue.setMaximum(255);
		
		add(lbl);
		add(jsred);		add(jsgreen);		add(jsblue);
		
		jsred.addAdjustmentListener(this);
		jsblue.addAdjustmentListener(this);
		jsgreen.addAdjustmentListener(this);			
	}
	@Override
	public void adjustmentValueChanged(AdjustmentEvent e) {
		Color c = new Color
						(jsred.getValue(), 						
						jsgreen.getValue(),
						jsblue.getValue());
		setBackground(c);
		this.getContentPane().setBackground(c);
		//lbl.setOpaque(true);
		//lbl.setBackground(c);
	}
	public static void main(String[] args) {
		new JScrollTest();
	}
}

AWT List, Choice and Swing List and Combo example

import java.awt.Choice;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class Main 
	extends 	JFrame
	implements	ActionListener	
{
	List li;
	Choice ch;
	JList 		lstCity;
	JComboBox	cmbCity;
	JRadioButton radAddToList, radAddToCombo, radAddToBoth;
	ButtonGroup group;
	JTextField txtCity;
	JButton btnAddCity;
	Vector jlistdata, jcombodata;
	public Main() {
		setLayout(new FlowLayout());
		radAddToList = new JRadioButton("add to list");
		radAddToCombo = new JRadioButton("add to combo");
		radAddToBoth = new JRadioButton("add to both");				
		
		group = new ButtonGroup();						
		group.add(radAddToBoth);
		group.add(radAddToCombo);;
		group.add(radAddToList);
		
		
		txtCity = new JTextField(15);
		btnAddCity = new JButton("add city");
		
		
		add(txtCity);
		add(radAddToList);
		add(radAddToCombo);
		add(radAddToBoth);
		add(btnAddCity);
		
		jlistdata = new Vector();
		jlistdata.add("first item");
		lstCity = new JList(jlistdata);				
		jcombodata  = new Vector();
		jcombodata.add("1st item");
		cmbCity = new JComboBox(jcombodata);
		
		
		
		li = new List(5);
		li.add("jam");
		li.add("raj");
		li.add("ahm");
		ch = new Choice();
		ch.add("jam");
		ch.add("raj");
		ch.add("ahm");
		
		add(li);
		add(ch);		
		
		add(lstCity);
		add(cmbCity);
		setVisible(true);

		btnAddCity.addActionListener(this);
		pack();	
		
		
	}

		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Main();		
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub

		if(radAddToList.isSelected())
		{
			li.add(txtCity.getText().toString());
			jlistdata.add(txtCity.getText().toString());
			lstCity.updateUI();
		}
		else if(radAddToCombo.isSelected())
		{
			ch.add(txtCity.getText().toString());
			jcombodata.add(txtCity.getText().toString());
		}
		else if (radAddToBoth.isSelected())
		{
			li.add(txtCity.getText().toString());
			ch.add(txtCity.getText().toString());
			jlistdata.add(txtCity.getText().toString());
			jcombodata.add(txtCity.getText().toString());
			lstCity.updateUI();
		}		
	}
}

Applet

Applet with Graphics class

/*
<applet code=App1 width=500 height=500/>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class App1 extends Applet {
		
	public void init() {
		//setBackground(Color.BLUE);
		//setForeground(Color.WHITE);
		showStatus("init called");
	}
	public void paint(Graphics g) 
	{			
		g.drawLine(10, 10, getSize().width, 10);
		//g.drawString("@", 10, 20);
		for(int i=10; i<=getSize().width; i+=20)
		{
			g.drawString("@", i, 20);
		}
		
		g.drawLine(getSize().width/2, 0, getSize().width/2,getSize().height);
		//g.drawLine(127, 47, 200, 231);
		//g.drawString("hi hello", 100, 100);
	}

}

Applet with Current Thread

/*
<applet code=App2 width=500 height=500/>
</applet>
*/

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class App2 
	extends Applet
	implements Runnable
 
{	
	Thread t;
	@Override
	public void init() 
	{
		setBackground(Color.BLACK);
		setForeground(Color.WHITE);
		t = new Thread(this);
		t.start();
	}
	public void paint(Graphics g) 
	{					
		int w = getSize().width;
		int h = getSize().height;			
		int sx = 0;
		int sy = 0;		
		int ex = 0;
		int ey = 0;
		
		Random r = new Random(100);
		for(int i=1; i<=1000; i++)
		{
			sx = Math.abs(r.nextInt()/(w*3000));
			sy = Math.abs(r.nextInt()/(h*3000));
			ex = sx;			
			ey = sy;			
			g.drawLine(sx, sy, ex+20, ey+20);			
		}
		
		showStatus(w+","+h);
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=1; i<=10; i++)
		{					
			System.out.println("hi");
			try{
			Thread.sleep(500); }
			catch(Exception e){}
		}
	}
}

Applet with separate Threads

/*
<applet code=App3 width=500 height=500/>
</applet>
*/

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class App3 
	extends Applet
	implements Runnable
 
{	
	Thread t;
	int w = 0;
	int h = 0;			
	int sx = 0;
	int sy = 0;		
	int ex = 0;
	int ey = 0;
	Random r;
	
	@Override
	public void init() 
	{		
		setBackground(Color.BLACK);
		setForeground(Color.WHITE);
		
		t = new Thread(this);
		r = new Random(100);
		t.start();
	}
	public void paint(Graphics g) 
	{
		g.drawLine(sx, sy, ex+20, ey+20);
		showStatus(sx+","+sy + " : "+getParameter("para1"));		
	}
	@Override
	public void update(Graphics g) {
		paint(g);
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=1; i<=10000; i++)
		{
			sx = Math.abs(r.nextInt(800));
			sy = Math.abs(r.nextInt(600));
			ex = sx;			
			ey = sy;	
			try {			Thread.sleep(250); }
			catch(Exception e) {e.printStackTrace();}
			repaint();
			//repaint(sx, sy, ex+20, ey+20);
		}		
	}
}

Applet example to draw line at random location with random colors

import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Random;

public class ThreadAndColorDemo 
	extends 	Applet
	implements	Runnable	
{
	Random	random;
	Thread	thread;
	Color	color;
	int sx = 0;
	int sy = 0;	
	
	public void init() {
		setBackground(Color.BLACK);
		random = new Random();
		thread = new Thread(this);
		thread.start();		
		setFont(new Font("Arial",Font.PLAIN,25));
	}	
	public void run() {
		while(true)
		{							
			try
			{	
				Thread.sleep(500);
				sx = random.nextInt(getWidth());
				sy = random.nextInt(getHeight());
				color = new Color(random.nextFloat(), random.nextFloat(), random.nextFloat());
				repaint();		
			}
			catch(Exception e) {e.printStackTrace();}
		}	
	}	
	public void update(Graphics g) {		
		paint(g);
	}
	public void paint(Graphics g) {
		setForeground(color);
		g.drawLine(sx, sy, sx+25, sy+25);
		g.drawString(sx+","+sy,sx,sy);
	}
}

Event Listeners and Adapter classes

Mouse Adapter and Key Adapter example

import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class KeyAdapterTest extends JFrame {

	public KeyAdapterTest() {		
		setLayout(new FlowLayout());
		setSize(500,500);	
		setVisible(true);
		JTextField t = new JTextField(10);				
		add(t);		
		t.addKeyListener(new MyKeyTest());
		t.addMouseListener(new mhandle());
		pack();
		//addKeyListener(new MyKeyTest());
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			new KeyAdapterTest();
	}

}
class mhandle extends MouseAdapter
{
	@Override
	public void mouseEntered(MouseEvent e) {
		System.out.println("enter");
	 	JTextField jt = (JTextField) e.getSource();	 	
	 	jt.setBackground(Color.YELLOW);	 	
	}
	@Override
	public void mouseExited(MouseEvent e) {
		System.out.println("exit");
		JTextField jt = (JTextField) e.getSource();
	 	jt.setBackground(Color.WHITE);
	}
}
class MyKeyTest extends KeyAdapter
{	
	public void keyTyped(KeyEvent e) {

		//System.out.println("typed "+e.getKeyChar());
		if(e.getKeyChar() == 'E'  || e.getKeyChar() == 'e')
		{
			System.exit(1);
		}
		else
		{
			System.out.println(e.getKeyChar());
		}
	}
}

Mouse Listener example

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;

public class MouseListenerTest extends JFrame implements MouseListener {

	public MouseListenerTest() {
		// TODO Auto-generated constructor stub
		setSize(500,502);
		setVisible(true);
	
		addMouseListener(this);
	}
	
	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("mouse cliekc");
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("mouse enter");
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("mouse exit");
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("mouse press");

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("mouse release");
	}
	public static void main(String[] args) {
		new MouseListenerTest();
	}

}

Windows adapter and mouse adapter example

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class WinAdapterTest extends JFrame {
	
	public WinAdapterTest() { 
		setSize(500,500);	
		setVisible(true);
		addWindowListener(new WinTest());
		addMouseListener (new MouseTest());
	}
	public static void main(String[] args) {
		new WinAdapterTest();
	}	
}
class MouseTest extends MouseAdapter
{
	@Override
	public void mouseClicked(MouseEvent e) {
		
		System.out.println("mouse clicked");
	
	}
}
class WinTest extends WindowAdapter
{
	@Override
	public void windowIconified(WindowEvent e) {
		System.out.println("iconified");	
	}
	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("closed");
	}
	@Override
	public void windowDeactivated(WindowEvent e) {
		System.out.println("deactivated");
	}
}

Window listener example

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class WindowListenerTest 
	extends JFrame
	implements WindowListener
{
	public WindowListenerTest() {
		// TODO Auto-generated constructor stub
		setSize(500,500);
		setVisible(true);
		addWindowListener(this);
	}
	public static void main(String[] args) {
		new WindowListenerTest();
	}
	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("activated");
	}
	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("closed");
	}
	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("closing");
	}
	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("de-activated");
	}
	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("de-iconified");
	}
	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("iconified");
	}
	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
}
%d bloggers like this: