Core Java Material 3
Core Java Material 3
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("i value is :"+i);
}
}
public static void main(String[] args)
{
SecondThread st = new SecondThread();
Thread t = new Thread(st);
t.start();
}
}
import java.io.*;
class sequencedemo
{
public static void main(String[] args) throws Exception
{
FileInputStream fis1 = new FileInputStream("abc.txt");
FileInputStream fis2 = new FileInputStream("xyz.txt");
int k;
while((k=sis.read())!=-1)
{
System.out.print((char)k);
}
}
}
class student
{
int sno;
int m1,m2,m3;
public student(int sno,int m1,int m2,int m3){
this.sno=sno;
this.m1=m1;
this.m2=m2;
this.m3=m3;
}
void modify(){
m1++;m2++;m3++;
}
void display(){
System.out.println("sno= "+sno+" m1="+m1+" m2="+m2+" m3="+m3);
}
}
class result
{
int sno;
String result;
public result(int sno,String result){
this.sno=sno;
this.result=result;
}
void modify(String ne){
result=ne;
}
void display(){
System.out.println("sno="+sno+" result="+result);
}
}
student stud;
result res;
public mytest(int sno,int m1,int m2,int m3,String r){
stud=new student(sno,m1,m2,m3);
res=new result(sno,r);
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class test{
public static void main(String args[]) throws Exception {
t1.stud.display();
t1.res.display();
t.stud.modify();
t.res.modify("destention");
System.out.println("after modifictation ");
t.stud.display();
t.res.display();
t1.stud.display();
t.res.display();
}
}
abstract class shape
{
abstract void area();
void behavior()
{
System.out.println("this example show hierarchical inheritance");
}
}
class Rect extends shape
{
int length,breadth;
void getRect()
{
length=20;
breadth=30;
}
void area()
{
int z=length * breadth;
System.out.println("the area of reactangle is :"+z);
}
}
class square extends shape
{
int a;
void getsquare()
{
a=40;
}
void area()
{
int x=a * a;
System.out.println("the area of square is :"+x);
}
}
class shapedemo
{
public static void main(String[] args)
{
//shape s = new shape();
//s.area();
}
}
class Simple
{
public static void main(String args[])
{
System.out.println("original main method");
int x=10;
main(x);
}
public static void main(int x)
{
System.out.println("x value is :"+x);
}
}
class Simple
{
void display()
{
System.out.println("hello");
}
}
class simpledemo
{
public static void main(String[] args)
{
Simple s[]=new Simple[5];
s[0]=new Simple();
s[0].display();
}
}
class sleeptest extends Thread
{
public void run()
{
try
{
for(int i=0;i<10;i++)
{
Thread.sleep(1000);
System.out.println("i value is :"+i);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
sleeptest s1 = new sleeptest();
sleeptest s2 = new sleeptest();
s1.start();
s2.start();
}
}
.
class sortarray
{
public static void main(String[] args)
{
int a[]={50,30,20,60,45};
int n=a.length;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int temp;
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
import java.util.*;
class sorting
{
public static void main(String args[])
{
Arrays.sort(args);
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
class Speed
{
public static void main(String[] args)
{
Speed objref = new Speed();
double s = objref.calcspeed(12.0,-3.0);
System.out.println("speed (km/h):"+s);
}
private double calcspeed(double distance,double time)
{
assert distance >0.0;
assert time >0.0 :"time is not a positive value:"+time;
double sp=distance/time;
assert sp >=0.0;
return sp;
}
}
import java.util.*;
class stackdemo
{
public static void main(String []a)
{
Stack s=new Stack();
s.push(new Integer(33));
s.push(new String("java"));
s.push(new Float(45.67));
s.push(new Integer(67));
s.push(null);
s.push(null);
System.out.println(s);
Object o=s.peek();
System.out.println("PEEK"+o.toString());
System.out.println(s);
Object o1=s.pop();
System.out.println("after deletion"+o1.toString());
System.out.println(s);
}
}
class StackTrace
{
IllegalArgumentException ex;
public static void main(String[] argv)
{
StackTrace st = new StackTrace();
st.makeit();
System.out.println("CONSTRUCTED BUT NOT THROWN");
st.ex.printStackTrace();
st.throwit();
// MAY BE NOTREACHED - THINK ABOUT IT!
System.out.println("CONSTRUCTED BUT NOT THROWN");
st.ex.printStackTrace();
}
class staticoverride
{
public static void main(String args[])
{
AA a1 = new AA();
BB b1 = new BB();
AA x;
x=a1;
x.classmethod();
x.instancemethod();
x=b1;
x.classmethod();
x.instancemethod();
}
}
class ABCD
{
static void one()
{
System.out.println("class ABCD one method");
}
static void one(int x)
{
System.out.println("x vlaue is :"+x);
}
}
class XYZ extends ABCD
{}
class staticinheritdemo
{
public static void main(String[] args)
{
XYZ x1 = new XYZ();
x1.one();
x1.one(10);
}
}
1
class outer
{
int a=10;
static int b=20;
class inner
{
int c=30;
static int d=40;
void display()
{
System.out.println("this is the method in inner class");
System.out.println("the outer a is"+b);
}
}
}
class StaticInner
{
public static void main(String args[])
{
outer ou = new outer();
System.out.println("a value is :"+ou.a);
System.out.println("b value is :"+outer.b);
class inner
{
int c=30;
//static int d=40;
}
}
class StaticInner
{
public static void main(String args[])
{
outer ou = new outer();
System.out.println("a value is :"+ou.a);
System.out.println("b value is :"+outer.b);
class staticoverride
{
public static void main(String args[])
{
AA a1 = new AA();
BB b1 = new BB();
AA x;
x=a1;
x.classmethod();
x.instancemethod();
x=b1;
x.classmethod();
x.instancemethod();
}
}
class stopdemo implements Runnable
{
}
}
class stringdemo1
{
public static void main(String[] args)
{
//String str = new
StringBuffer().append("hello").append("World").toString();
String str="hello"+"world";
System.out.println(str);
}
}
class StringDemo2
{
public static void main(String[] args)
{
String s1 = new String("hello");
String s2 = new String("hello");
String s9="hai";
String s10="hai";
String s11="hello";
// =============================================
if(s1.equals("hello"))
System.out.println("s1 equals hello");
else
System.out.println("s1 not equals hello");
//==============================================
if(s1.equals(s2))
System.out.println("s1 and s2 both are equal");
else
System.out.println("both are not equal");
//==============================================
if(s1=="hello")
System.out.println("s1 and hello both references same");
else
System.out.println("not same reference");
//==============================================
if(s1==s2)
System.out.println("s1 and s2 references are same");
else
System.out.println("s1 and s2 both references are not same");
//==============================================
if(s3==s4)
System.out.println("s3 and s4 references are same");
else
System.out.println("s3 and s4 references are not same");
//==============================================
if(s9==s10)
System.out.println("s9 and s10 references are same");
else
System.out.println("s9 and s10 references are not same");
//==============================================
if(s1==s3)
System.out.println("s1 and s3 references are same");
else
System.out.println("s1 and s3 references are not same");
//==============================================
if(s1==s11)
System.out.println("s1 and s11 references are same");
else
System.out.println("s1 and s11 references are not same");
//==============================================
if(s5.equalsIgnoreCase(s6))
System.out.println("s5 and s6 both contents are same");
else
System.out.println("s5 and s6 contents are different");
//==============================================
String s7="god";
String s8="good";
System.out.println("s1 compare to s2 is :"+s1.compareTo(s2));
System.out.println("s7 compare to s8 is :"+s7.compareTo(s8));
System.out.println("s8 compare to s7 is :"+s8.compareTo(s7));
//==============================================
System.out.println("s1 starts with :"+s1.startsWith("he"));
System.out.println("s1 starts with :"+s1.startsWith("e",1));
System.out.println("s5 ends with :"+s5.endsWith("day"));
//==============================================
String str = "activenetinformaticslimitednet";
System.out.println("t located at :"+str.indexOf('t'));
System.out.println("t located at :"+str.indexOf('t',3));
System.out.println("net located at :"+str.indexOf("net"));
System.out.println("net located at :"+str.indexOf("net",9));
System.out.println("last i located at :"+str.lastIndexOf('i'));
System.out.println("last i located at :"+str.lastIndexOf('i',10));
System.out.println("last net located at :"+str.lastIndexOf("net"));
//==============================================
System.out.println("sub string from index 10 to end is :"+str.substring(10));
System.out.println("sub string from index 0 to 9 is :"+str.substring(0,9));
System.out.println("result of s1.concat(s3) is"+s1.concat(s3));
System.out.println("after concatenation:"+s1);
System.out.println("replace 'l' with 'L' in s1 is :"+s1.replace('l','L'));
System.out.println("s1 to Uppercase is :"+s1.toUpperCase());
System.out.println("s6 to lowercase is :"+s1.toLowerCase());
String str1=" activenet ";
System.out.println("str1 after trim :"+str1.trim());
boolean b = true;
char c = 's';
int i = 9;
double d = 99.99;
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
import java.io.*;
class Student1
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = new FileInputStream("abc.cob");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o= ois.readObject();
Student st =(Student)o;
st.putdata();
}
}
class Student implements Cloneable
{
int sno;
String sname;
public Student(int x,String y)
{
sno=x;
sname=y;
}
void display()
{
System.out.println("the sno is :"+sno);
System.out.println("the sname is :"+sname);
}
void setname(String name)
{
sname=name;
}
public static void main(String[] args) throws Exception
{
Student s1 = new Student(101,"ram");
s1.display();
Student s2=(Student)s1.clone();
s2.display();
System.out.println();
s1.setname("hari");
s1.display();
s2.display();
System.out.println(s1);
System.out.println(s2);
}
}
class Studentdemo
{
public static void main(String[] args) throws MarksOutOfBoundsException
{
Student s1 = new Student(101,"ram",99);
Student s2 = new Student(102,"nikil",120);
// try
//{
s1.findResult();
s2.findResult();
//}
//catch(Exception e)
//{
//System.out.println(e);
// }
System.out.println("out of findresult");
}
}
import java.io.*;
t1.start();
t2.start();
}
}
class syn2 implements Runnable
{
int x;
public static void main(String[] args)
{
syn2 s = new syn2();
t1.start();
t2.start();
}
public void run()
{
int hold;
System.out.println("entered into run method");
System.out.println(Thread.currentThread().getName());
for(int i=0;i<10;i++)
{
synchronized(this)
{
System.out.println("entered into syn block");
System.out.println(Thread.currentThread().getName());
hold=x+1;
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
x=hold;
System.out.println(Thread.currentThread().getName());
System.out.println("syn completed");
}
}
}
}
public class TernaryOperatorsDemo {
public static void main(String args[]){
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : "+z);
}
}
class Test
{
public static void main(String args[])
{
int a=10;
int b=0;
int c=a/b;
System.out.println("the c value i s:"+c);
}
}
import java.io.IOException;
class testExceptions
{
void method1() throws Throwable
{
throw new Throwable("Throwable Exception in method1");
}
void method2() throws Throwable
{
throw new IOException("Exception in method2");
try
{
method1();
}
catch(Throwable th)
{
throw th;
throw th.fillInStackTrace();
}
}
public static void main(String args[]) throws Throwable
{
new testExceptions().method2();
}
}
import java.awt.*;
add(tf1);
add(tf2);
add(ta);
setSize(300,400);
show();
}
public static void main(String[] args)
{
new TextDemo();
}
}
class Third extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
System.out.println("i value is :"+i);
}
}
public static void main(String[] args)
{
Third t1 = new Third();
t1.start();
Third t2 = new Third();
t2.start();
Third t3 = new Third();
t3.start();
}
}
this keyword uses are
================
1. differentiating the local variables and
instance variables
2. constructor chaining(calling local
constructors)
3. function chaining
class simple
{
int a,b,c,d;
simple(int x,int y)
{
a=x;
b=y;
}
simple(int x,int y,int z)
{
this(x,y);
c=z;
}
simple(int p,int q,int r,int s)
{
this(p,q,r);
d=s;
}
}
=======================================
function chain
===================
class simple
{
int a,b;
class Treeset
{
public static void main(String[] args)
{
TreeSet t = new TreeSet();
t.add("20");
t.add("10");
t.add("30");
t.add(null);
System.out.println(t);
}
}
import java.util.*;
class Emp
{}
class Student
{}
class Salary
{}
class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector();
System.out.println("capacity is :"+v.capacity());
v.add("10");
v.add("30");
v.add("20");
v.add("40");
/*
Enumeration e =v.elements();
while(e.hasMoreElements())
{
Object o=e.nextElement();
System.out.println("the object is :"+o);
}
Iterator i = v.iterator();
while(i.hasNext())
{
Object o = i.next();
System.out.println("the object is :"+o);
}
*/
ListIterator li = v.listIterator();
while(li.hasNext())
{
Object o = li.next();
System.out.println("the object is :"+o);
}
while(li.hasPrevious())
{
Object o1 = li.previous();
System.out.println("athe object is :"+o1);
}
}
}
import java.io.*;
StudentExternal st = new
StudentExternal(sno,sname,m1,m2,m3);
oos.writeObject(st);
}
oos.flush();
oos.close();
fos.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Q
{
int n;
synchronized int get()
{
System.out.println("got"+n);
return n;
}
synchronized void put(int n)
{
this.n=n;
System.out.println("put"+n);
}
}
class producer implements Runnable
{
Q q;
producer(Q q)
{
this.q=q;
new Thread(this,"producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class consumer implements Runnable
{
Q q;
consumer(Q q)
{
this.q=q;
new Thread(this,"consumer").start();
}
public void run()
{
int i=0;
while(true)
{
q.get();
}
}
}
class procon
{
public static void main(String[] args)
{
Q q = new Q();
new producer(q);
new consumer(q);
System.out.println("press ctrl -c to stop");
}
}
=============================
modified version
=============================
class Q
{
int n;
boolean valueset=false;
synchronized int get()
{
if(!valueset)
try
{
wait();
}
catch(Exception e)
{
System.out.println("InterruptedException");
}
System.out.println("got"+n);
valueset=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueset)
try
{
wait();
}
catch(Exception e)
{
System.out.println("InterruptedException");
}
this.n=n;
valueset=true;
System.out.println("put"+n);
notify();
}
}
class producer implements Runnable
{
Q q;
producer(Q q)
{
this.q=q;
new Thread(this,"producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class consumer implements Runnable
{
Q q;
consumer(Q q)
{
this.q=q;
new Thread(this,"consumer").start();
}
public void run()
{
int i=0;
while(true)
{
q.get();
}
}
}
class proconfixed
{
public static void main(String[] args)
{
Q q = new Q();
new producer(q);
new consumer(q);
System.out.println("press ctrl -c to stop");
}
}
=============================
deadlockdemo
=============================
class DlDemo implements Runnable
{
DlDemo x;
public static void main(String[] args)
{
DlDemo dd1 = new DlDemo();
DlDemo dd2 = new DlDemo();
System.out.println(dd1);
System.out.println(dd2);
dd1.x=dd2;
System.out.println(dd1.x);
dd2.x=dd1;
System.out.println(dd2.x);
t1.start();
t2.start();
try
{
t1.join();
t2.join();
}
catch(Exception e)
{
System.exit(0);
}
}
public synchronized void run()
{
try
{
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
x.synmethod();
}
public void synmethod()
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("in synmethod");
}
}
class yieldingthread extends Thread
{
int countdown=6;
static int threadcount=0;
yieldingthread()
{
super(""+ ++threadcount);
start();
}
public String toString()
{
return "#"+getName()+" :"+countdown;
}
public void run()
{
while(true)
{
System.out.println(this);
if(--countdown == 0)
return;
yield();
}
}
public static void main(String[] args)
{
for(int i=0;i<5;i++)
{
new yieldingthread();
}
}
}
innerclass
class WithInner
{
class Inner
{
Inner()
{
System.out.println("i am inner class constructor");
}
}
}
class A
{
class B
{
private int i = 11;
public int value()
{
return i;
}
}
class C
{
private String label;
C(String x)
{
label = x;
}
String readLabel()
{
return label;
}
}
class A
{
class B
{
private int i = 11;
public int value()
{
return i;
}
}
class C
{
private String label;
C(String x)
{
label = x;
}
String readLabel()
{
return label;
}
}
public static void main(String[] args)
{
A a = new A();
// Must use instance of outer class
// to create an instances of the inner class:
A.B b = a.new B();
A.C c = a.new C("India");
String s=d.readLabel();
System.out.println(s);
}
} ///:~
/** Demonstrate inner-inner class. A named inner class
* is used to show that it can access non-local variables
* in the enclosing object.
*/
public class abc
{
static String msg = "Hello";
public static void main(String[] av)
{
class xyz
{
public void display()
{
// print member of enclosing class
System.out.println(msg);
}
}
xyz x = new xyz();
x.display();
}
}
// can inner classes can be overriden
class override
{
private abc a;
public class abc
{
public abc()
{
System.out.println("override.abc()");
}
}
public override()
{
System.out.println("new override()");
a=new abc();
}
}
class overridedemo extends override
{
public class abc
{
public abc()
{
System.out.println("overridedemo.abc()");
}
}
public static void main(String[] args)
{
new overridedemo();
}
}
class MyOuter2
{
private String x="outer2";
void doStuff()
{
String y="local variable";
class MyInner
{
public void seeOuter()
{
System.out.println("Outer x is :"+x);
System.out.println("string is :"+y);
}
}
MyInner mi = new MyInner();
mi.seeOuter();
}
public static void main(String[] args)
{
MyOuter2 my = new MyOuter2();
my.doStuff();
}
}
import java.awt.*;
import java.awt.event.*;
class MyDia extends Dialog implements ActionListener
{
Frame fra;
Button b1,b2;
public MyDia(Frame f,String s)
{
super(f,s);
f=new MenuTest();
fra=f;
f.setTitle("New Frame");
b1= new Button("OK");
b2=new Button("Cancel");
Panel p=new Panel();
p.add(b1);
p.add(b2);
f.add(p,"South");
f.setSize(200,200);
f.setVisible(true);
b2.addActionListener(this);
fra.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
fra.setVisible(false);
}
});
}
public void actionPerformed(ActionEvent a)
{
fra.setVisible(false);
}
}
public class MenuTest extends Frame implements ActionListener,ItemListener
{
CheckboxMenuItem cbi1,cbi2,cbi3;
static Frame f;
Color c;
public MenuTest()
{
MenuBar mb= new MenuBar();
setMenuBar(mb);
// is a method in Frame class
Menu m1=new Menu("File");
// creating menu option
MenuItem mi1=new MenuItem("Open",
new MenuShortcut(KeyEvent.VK_O));
//creating menu item
MenuItem mi2=new MenuItem("New",
new MenuShortcut(KeyEvent.VK_N));
MenuItem mi3=new MenuItem("Save",
new MenuShortcut(KeyEvent.VK_S));
MenuItem mi4=new MenuItem("Exit",
new MenuShortcut(KeyEvent.VK_X));
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent a)
{
FileDialog d1=new FileDialog(this,
"Open",FileDialog.LOAD);
FileDialog d2=new FileDialog(this,
"Save",FileDialog.SAVE);
if (a.getActionCommand().equals("Open"))
{
d1.show();
}
if (a.getActionCommand().equals("New"))
{
Frame f2=new Frame();
new MyDia(f2,"New");
}
if (a.getActionCommand().equals("Save"))
{
d2.show();
}
if (a.getActionCommand().equals("Exit"))
{
System.exit(0);
}
}
public void itemStateChanged(ItemEvent i)
{
if(cbi1.getState()==true)
{
c=new Color(255,0,0);
repaint();
}
if(cbi2.getState())
{
c=new Color(0,255,0);
repaint();
}
if(cbi3.getState())
{
c=new Color(0,0,255);
repaint();
}
}
public void paint(Graphics g)
{
f.setBackground(c);
}
public static void main(String[] args)
{
f=new MenuTest();
f.setSize(400,400);
f.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
class MenuTest1 extends Frame implements ActionListener
{
MenuBar mb = new MenuBar();
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
Menu sub = new Menu("Draw");
MenuItem mi1 = new MenuItem("New", new MenuShortcut(KeyEvent.VK_A));
MenuItem mi2 = new MenuItem("Open");
MenuItem mi3 = new MenuItem("Save");
MenuItem mi4 = new MenuItem("Save as");
MenuItem mi5 = new MenuItem("Exit");
MenuItem mi6 = new MenuItem("Copy");
MenuItem smi1 = new MenuItem("Line");
MenuItem smi2 = new MenuItem("Rect");
TextField tf = new TextField(20);
MenuTest1()
{
setSize(200,300);
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi4);
m1.addSeparator();
m1.add(mi5);
m1.add(mi6);
m2.add(sub);
sub.add(smi1);
sub.add(smi2);
mb.add(m1);
mb.add(m2);
setMenuBar(mb);
add(tf,"North");
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);
smi1.addActionListener(this);
smi2.addActionListener(this);
setVisible(true);
}
public static void main(String args[])
{
new MenuTest();
}
public void actionPerformed(ActionEvent ae)
{
tf.setText("u selected"+ae.getActionCommand());
}
}
class MyOuter
{
class MyInner
{ }
}
class outer
{
int a=10;
class inner
{
int b=20;
}
}
class nonstaticouterdemo
{
public static void main(String[] args)
{
outer ou = new outer();
// outer.inner in = new outer().new inner();
outer.inner in =ou.new inner();
System.out.println("outer class variable is "+ou.a);
System.out.println("innerclass variable is :"+in.b);
}
}
import java.awt.*;
import java.awt.event.*;
pm.add(mi1);
pm.add(mi2);
pm.add(mi3);
pm.add(mi4);
add(pm);
addMouseListener(this);
setVisible(true);
setSize(200,200);
addWindowListener(new WindowAdapter()
System.exit(0);
});
}
public void mouseEntered(MouseEvent me)
{}
public void mouseExited(MouseEvent me)
{}
public void mouseClicked(MouseEvent me)
{}
public void mouseReleased(MouseEvent me)
{}
public void mousePressed(MouseEvent me)
{
pm.show(me.getComponent(),me.getX(),me.getY());
}
public static void main(String args[])
{
popupexample pp = new popupexample();
}
}
import java.awt.*;
import java.awt.event.*;
start.x=e.getX();
start.y = e.getY();
end.x = e.getX();
end.y = e.getY();
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
end.x = e.getX();
end.y = e.getY();
repaint();
);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawLine(start.x,start.y,end.x,end.y);
}
public static void main(String args[])
{
new RubberLine();
}
}
class outer
{
static int a=10;
static class inner
{
static int b=20;
int c=30;
}
}
class staticouterdemo
{
public static void main(String[] args)
{
outer ou = new outer();
outer.inner in = new outer.inner();
System.out.println("outer class variable is "+outer.a);
System.out.println("innerclass variable is :"+outer.inner.b);
System.out.println("inner class variable is :"+in.c);
}
}
Packages
package pack1;
class Varprotection
{
int n=1;
private int pri=2;
protected int pro=3;
public int pub =4;
Varprotection()
{
System.out.println("default value is :"+n);
System.out.println("private value is :"+pri);
System.out.println("protected value is :"+pro);
System.out.println("public value is :"+pub);
}
}
package pack1;
class Samediff
{
Samediff()
{
Varprotection v = new Varprotection();
System.out.println("default value is :"+v.n);
//System.out.println("private value is :"+v.pri);
System.out.println("protected value is :"+v.pro);
System.out.println("public value is :"+v.pub);
}
}
package pack1;
class Samesub extends Varprotection
{
Samesub()
{
System.out.println("default value is :"+n);
//System.out.println("private value is :"+pri);
System.out.println("protected value is :"+pro);
System.out.println("public value is :"+pub);
}
}
package pack1;
class MainTest
{
public static void main(String[] args)
{
Varprotection v1 = new Varprotection();
Samesub s1 = new Samesub();
Samediff s2 = new Samediff();
}
}
pack2
package pack2;
import pack1.*;
class OtherDiff
{
OtherDiff()
{
Varprotection v2 = new Varprotection();
System.out.println("default value is :"+v2.n);
System.out.println("private value is :"+v2.pri);
System.out.println("protected value is :"+v2.pro);
System.out.println("public value is :"+v2.pub);
}
}
package pack2;
import pack1.*;
package pack2;
import pack1.*;
class OtherMainTest
{
public static void main(String[] args)
{
OtherSub os = new OtherSub();
OtherDiff od = new OtherDiff();
}
}
Swing Programs
import java.awt.Component;
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public JMenuExample1( ) {
super("DinnerMenu ");
setSize(200, 200);
setLocation(200, 200);
myappli()
{
Container con = this.getContentPane();
con.setLayout(new FlowLayout());
JLabel l1 = new JLabel("first no");
b1 = new JTextField(10);
JLabel l2 = new JLabel("second no");
b2 = new JTextField(10);
JLabel l3 = new JLabel("value ");
b3 = new JTextField(10);
jb1 = new JButton("add");
jb1.addActionListener(this);
con.add(l1);
con.add(b1);
con.add(l2);
con.add(b2);
con.add(l3);
con.add(b3);
con.add(jb1);
setVisible(true);
// setSize(300,400);
pack();
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("add"))
{
String s1 = b1.getText();
int x = Integer.parseInt(s1);
String s2 = b2.getText();
int y = Integer.parseInt(s2);
int z= x+y;
b3.setText(s3);
}
}
mycolor()
{
Container con = getContentPane();
con.setLayout(new FlowLayout());
jt1= new JTextField(10);
con.add(jt1);
con.add(b1);
con.add(b2);
con.add(b3);
b1.addItemListener(this);
b2.addItemListener(this);
b3.addItemListener(this);
setSize(200,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent i)
{
/*
ifb1==i.getSource())
jt1.setBackground(Color.red);
else
if(b2==i.getSource())
jt1.setBackground(Color.blue);
else
if(b3==i.getSource())
jt1.setBackground(Color.green);
*/
String s = i.getActionCommand();
if(s.equals("RED"))
jt1.setBackground(Color.red);
}
public static void main(String[] args)
{
new mycolor();
}
}
// OverlayTest.java
// A test of the OverlayLayout manager allowing experimentation.
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public OverlayTest() {
super("OverlayLayout Test");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jb1.setMinimumSize(b1);
jb1.setMaximumSize(b1);
jb1.setPreferredSize(b1);
jb2.setMinimumSize(b2);
jb2.setMaximumSize(b2);
jb2.setPreferredSize(b2);
jb3.setMinimumSize(b3);
jb3.setMaximumSize(b3);
jb3.setPreferredSize(b3);
p1.add(jb1);
p1.add(jb2);
p1.add(jb3);
p2.add(x1);
p2.add(y1);
p2.add(x2);
p2.add(y2);
p2.add(x3);
p2.add(y3);
constraints.gridx = 1;
JButton updateButton = new JButton("Update");
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jb1.setAlignmentX(
Float.valueOf(x1.getText().trim()).floatValue());
jb1.setAlignmentY(
Float.valueOf(y1.getText().trim()).floatValue());
jb2.setAlignmentX(
Float.valueOf(x2.getText().trim()).floatValue());
jb2.setAlignmentY(
Float.valueOf(y2.getText().trim()).floatValue());
jb3.setAlignmentX(
Float.valueOf(x3.getText().trim()).floatValue());
jb3.setAlignmentY(
Float.valueOf(y3.getText().trim()).floatValue());
p1.revalidate();
}
});
c.add(updateButton, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
c.add(p2, constraints);
}
g.setColor(Color.red);
g.drawRect(0,0,w-1,h-1);
g.drawLine(w/2,0,w/2,h);
g.drawLine(0,h/2,w,h/2);
}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public OverlayTest1() {
super("OverlayLayout Test");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new GridBagLayout());
/* jb1.setMinimumSize(b1);
jb1.setMaximumSize(b1);
jb1.setPreferredSize(b1);
jb2.setMinimumSize(b2);
jb2.setMaximumSize(b2);
jb2.setPreferredSize(b2);
jb3.setMinimumSize(b3);
jb3.setMaximumSize(b3);
jb3.setPreferredSize(b3);
jb4.setMinimumSize(b4);
jb4.setMaximumSize(b4);
jb4.setPreferredSize(b4);
*/
p1.add(jb1);
p1.add(jb2);
p1.add(jb3);
p1.add(jb4);
GridBagConstraints constraints = new GridBagConstraints();
c.add(p1, constraints);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="popupmenudemo.class" width=400 height=500>
</applet>
*/
pop.add(new JMenuItem("cut"));
pop.add(new JMenuItem("copy"));
pop.add(new JMenuItem("paste"));
con.addMouseListener(new MouseAdapter()
showPopup(me);
);
}
void showPopup(MouseEvent e)
{
if(e.isPopupTrigger())
pop.show(e.getComponent(),e.getX(),e.getY());
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="scrollpane.class" width=400 height=400>
</applet>
*/
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
jp.add(new JButton("button"+j));
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
f.setVisible(true);
}
}
import javax.swing.SpringLayout;
import javax.swing.Spring;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Container;
import java.awt.Component;
public TabbedPaneExample()
{
/*
<applet code=TJTable width=500 height=600>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.util.*;
Object[][] rowdata = {
{"autoexec.bat","149","09-11-07",new Boolean(false)},
{"real","dir","12-11-07",new Boolean(true)},
};
System.exit(0);
}
});
con.setLayout(new FlowLayout());
JButton b1 = new JButton("ok");
con.add(b1);
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/*f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});*/
}
public swing2()
{ Icon i1=new ImageIcon("paste.gif");
Icon i2=new ImageIcon("web.gif");
JButton b1=new JButton();
JButton b2=new JButton("second");
JButton b3=new JButton(i1);
JButton b4=new JButton("fourth",i2);
Container con=getContentPane();
FlowLayout fl=new FlowLayout(FlowLayout.LEFT);
//FlowLayout fl=new FlowLayout(FlowLayout.RIGHT);
//con.setLayout(fl);
con.setLayout(new FlowLayout(FlowLayout.RIGHT));
con.add(b1);
con.add(b2);
con.add(b3);
con.add(b4);
b1.setText("first");
System.out.println(b2.getText());
b1.setIcon(b4.getIcon());
b1.setBackground(Color.yellow);
b1.setForeground(Color.red);
}
}
import javax.swing.*;
import java.awt.*;
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing4()
{
JButton b1=new JButton("red");
JButton b2=new JButton("blue");
JButton b3=new JButton("green");
JPanel p1=new JPanel();
p1.add(b1);p1.add(b2);p1.add(b3);
//p1.setBackground(Color.pink);
Container con=getContentPane();
con.add("South",p1);
con.add("North",p2);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing5 extends JFrame
{
public static void main(String args[])
{
swing5 f=new swing5();
f.setSize(700,500);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing5()
{
Icon i1=new ImageIcon("alice.gif");
JButton b1=new JButton("welcome",i1);
//b1.setForeground(Color.magenta);
b1.setHorizontalTextPosition(SwingConstants.LEFT);
b1.setVerticalTextPosition(SwingConstants.TOP);
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);
Dimension d1=b1.getPreferredSize();
System.out.println(d1.width+" "+d1.height);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing6 extends JFrame
{
public static void main(String args[])
{
swing6 f=new swing6();
f.setSize(700,500);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing6()
{
Icon i1=new ImageIcon("save.gif");
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class swing7 extends JFrame
{
public static void main(String args[])
{
swing7 f=new swing7();
f.setSize(700,500);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing7()
{
Container con=getContentPane();
con.setLayout(new FlowLayout());
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing8 extends JFrame
{
public static void main(String args[])
{
System.out.println("execution of main method..");
swing8 f=new swing8();
f.setSize(800,600);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
System.out.println("execution of paint method..");
g.setColor(Color.red);
g.drawLine(30,30,150,30);
g.drawRect(30,50,100,50);
g.fillRoundRect(150,50,100,50,20,20);
g.fill3DRect(30,130,100,50,true);
g.fill3DRect(150,130,100,50,false);
g.setColor(Color.magenta);
g.drawOval(30,220,100,100);
g.fillArc(30,350,100,100,90,90);
Font f1=new Font("Arial",Font.BOLD+Font.ITALIC,30);
g.setFont(f1);
g.drawString("java by rami reddy",300,50);
int x[]=new int[]{500,600,550,450,400};
int y[]=new int[]{200,250,300,300,250};
g.setColor(Color.blue);
//g.drawPolyline(x,y,3);
//g.drawPolygon(x,y,3);
g.fillPolygon(x,y,5);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="swing8a" width=400 height=200>
</applet>
*/
/*
<applet code="swing9.class" width=200 height=200>
</applet>
*/
public class swing9 extends Applet
{
public void init()
{
Button b1 = new Button("ok");
add(b1);
System.out.println("init method..");
}
public void stop()
{
System.out.println("stop method..");
}
public void start()
{
//Button b1 = new Button();
//add(b1);
System.out.println("start method..");
}
public void destroy()
{
System.out.println("destroy method..");
}
public void paint(Graphics g)
{
System.out.println("paint method..");
g.drawString("core java by rami reddy",70,80);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="swing10" width=300 height=200>
</applet>
*/
Container con=getContentPane();
FlowLayout fl=new FlowLayout();
con.setLayout(fl);
con.add(b1);con.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{ JButton b=(JButton)a.getSource();
if(b==b1)
System.out.println("first button is clicked..");
else if(b==b2)
System.out.println("second button is clicked...");
/*String str=a.getActionCommand();
if(str.equals("first button"))
System.out.println("first button is clicked..");
else if(str.equals("second button"))
System.out.println("second button is clicked...");
*/
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="swing11" width=300 height=200>
</applet>
*/
con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);con.add(b2);con.add(b3);con.add(b4);
b1.addFocusListener(this);
b2.addFocusListener(this);
b3.addFocusListener(this);
b4.addFocusListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
int r=(int)(Math.random() * 255);
int g=(int)(Math.random() * 255);
int b=(int)(Math.random() * 255);
Color c1=new Color(r,g,b);
con.setBackground(c1);
}
public void focusGained(FocusEvent f)
{
JButton b=(JButton)f.getSource();
b.setBackground(Color.yellow);
b.setForeground(Color.red);
}
public void focusLost(FocusEvent f)
{
JButton b=(JButton)f.getSource();
b.setBackground(Color.red);
//b.setForeground(Color.black);
}
}
import javax.swing.*;
import java.awt.*;
/*
<applet code="swing12" width=300 height=200>
</applet>
*/
public class swing12 extends JApplet
{
public void init()
{
JTextField tf1=new JTextField();
JTextField tf2=new JTextField(30);
JTextField tf3=new JTextField("welcome");
JTextField tf4=new JTextField("welcome",20);
JPasswordField tf5=new JPasswordField(20);
tf5.setEchoChar('&');
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(tf1);con.add(tf2);con.add(tf3);
con.add(tf4);con.add(tf5);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
System.exit(0);
}
});
}
//JPasswordField tf1;
JTextField tf1,tf2,tf3;
public swing13()
{
tf1=new JTextField();
tf2=new JTextField();
tf3=new JTextField();
tf1.setBounds(25,30,200,30);
tf2.setBounds(25,80,200,30);
tf3.setBounds(25,130,200,30);
Container con=getContentPane();
con.setLayout(null);
con.add(tf1);con.add(tf2);con.add(tf3);
tf2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String s1=tf1.getText();
String s2=tf2.getText();
int n1=Integer.parseInt(s1);
int n2=Integer.parseInt(s2);
int n3=n1 +n2;
String s3=String.valueOf(n3);
tf3.setText(s3);
// tf3.setText(String.valueOf( Integer.parseInt(tf1.getText()) +
Integer.parseInt(tf2.getText())));
}
}
import javax.swing.*;
import java.awt.*;
/*
<applet code="swing14.class" width=200 height=300>
</applet>
*/
public class swing14 extends JApplet
{
public void init()
{
JButton b[]=new JButton[13];
Container con=getContentPane();
//GridLayout gl=new GridLayout(3,4);
GridLayout gl=new GridLayout(3,4,20,10);
con.setLayout(gl);
for(int i=0;i<b.length;i++)
{
b[i]=new JButton("button"+i);
con.add(b[i]);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="swing15.class" width=200 height=300>
</applet>
*/
public class swing15 extends JApplet implements MouseListener, MouseMotionListener
{
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent m)
{
System.out.println(" mouse entered at :"+m.getX()+","+m.getY());
}
public void mouseExited(MouseEvent m)
{
System.out.println(" mouse exited at :"+m.getX()+","+m.getY());
}
public void mousePressed(MouseEvent m)
{
System.out.println(" mouse pressed at :"+m.getX()+","+m.getY());
}
public void mouseReleased(MouseEvent m)
{
System.out.println(" mouse released at :"+m.getX()+","+m.getY());
}
public void mouseClicked(MouseEvent m)
{
System.out.println(" mouse clicked at :"+m.getX()+","+m.getY());
}
public void mouseMoved(MouseEvent m)
{
System.out.println(" mouse moved at :"+m.getX()+","+m.getY());
}
public void mouseDragged(MouseEvent m)
{
System.out.println(" mouse dragged at :"+m.getX()+","+m.getY());
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=swing17.class width=200 height=300>
</applet>
*/
b3.setRolloverIcon(i3);
b3.setPressedIcon(i2);
b3.setDisabledIcon(i1);
b1.setToolTipText("enable button");
b2.setToolTipText("disable button");
b1.setMnemonic('e');
b2.setMnemonic('d');
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);con.add(b2);con.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
JButton b=(JButton)a.getSource();
if(b==b1)
{
b3.setEnabled(true);
b1.setEnabled(false);
b2.setEnabled(true);
}
else if(b==b2)
{
b3.setEnabled(false);
b2.setEnabled(false);
b1.setEnabled(true);
}
}
}
import javax.swing.*;
import java.awt.*;
/*
<applet code="swing18" width=300 height=300>
</applet>
*/
public class swing18 extends JApplet
{
public void init()
{
JRadioButton r1=new JRadioButton("radio1");
JRadioButton r2=new JRadioButton("radio2");
JRadioButton r3=new JRadioButton("radio3");
Box h1=Box.createHorizontalBox();
h1.add(r1);h1.add(r2);h1.add(r3);
Box h2=Box.createHorizontalBox();
h2.add(c1);h2.add(c2);h2.add(c3);
Box h3=Box.createHorizontalBox();
h3.add(t1);h3.add(t2);h3.add(t3);
Box v1=Box.createVerticalBox();
v1.add(h1);v1.add(h2);v1.add(h3);
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(v1);
ButtonGroup bg1=new ButtonGroup();
bg1.add(r1);bg1.add(r2);bg1.add(r3);
//ButtonGroup bg2=new ButtonGroup();
//bg2.add(c1);bg2.add(c2);bg2.add(c3);
//ButtonGroup bg3=new ButtonGroup();
//bg3.add(t1);bg3.add(t2);bg3.add(t3);
}
}
import javax.swing.*;
import java.awt.*;
/*
<applet code="swing19" width=300 height=300>
</applet>
*/
public class swing19 extends JApplet
{
public void init()
{ Icon i1=new ImageIcon("copy.gif");
Icon i2=new ImageIcon("paste.gif");
JCheckBox c1=new JCheckBox();
JCheckBox c2=new JCheckBox("bold");
JCheckBox c3=new JCheckBox("bold",true);
JCheckBox c4=new JCheckBox(i1);
JCheckBox c5=new JCheckBox(i1,true);
JCheckBox c6=new JCheckBox("bold",i1);
JCheckBox c7=new JCheckBox("bold",i1,true);
c5.setSelectedIcon(i2);
c6.setSelectedIcon(i2);
c7.setSelectedIcon(i2);
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(c1);con.add(c2);con.add(c3);
con.add(c4);con.add(c5);con.add(c6);con.add(c7);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Box v1=Box.createVerticalBox();
v1.add(r1);v1.add(r2);v1.add(r3);
//Container con = getContentPane();
//con.add(v1);
Box v2=Box.createVerticalBox();
v2.add(r4);v2.add(r5);v2.add(r6);
//con.add(v2);
Box hb=Box.createHorizontalBox();
hb.add(Box.createHorizontalGlue());
hb.add(v1);
hb.add(Box.createHorizontalGlue());
hb.add(v2);
hb.add(Box.createHorizontalGlue());
Container con=getContentPane();
con.add("North",hb);
con.add(l1);
r1.addItemListener(this);
r2.addItemListener(this);
r3.addItemListener(this);
r4.addItemListener(this);
r5.addItemListener(this);
r6.addItemListener(this);
}
public void itemStateChanged(ItemEvent i)
{
String str="";
if( r1.isSelected())
str+=r1.getLabel()+" ";
if( r2.isSelected())
str+=r2.getLabel()+" ";
if( r3.isSelected())
str+=r3.getLabel()+" ";
if( r4.isSelected())
str+=r4.getLabel()+" ";
if( r5.isSelected())
str+=r5.getLabel()+" ";
if( r6.isSelected())
str+=r6.getLabel()+" ";
l1.setText(str);
}
}
import javax.swing.*;
import java.awt.*;
public class swing21 extends JApplet
{
public void init()
{
JTextArea ta1=new JTextArea();
JTextArea ta2=new JTextArea(6,40);
JTextArea ta3=new JTextArea("welcome to satya");
JTextArea ta4=new JTextArea("java by rami reddy",6,40);
JScrollPane jsp=new JScrollPane(ta4);
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(ta1);con.add(ta2);
con.add(ta3);con.add(jsp);
}
}
/*
<applet code=swing21 width=800 height=600>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing22 extends JFrame
implements ActionListener
{
public static void main(String args[])
{ swing22 f=new swing22();
f.setSize(700,500);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JLabel l1,l2,l3;
JButton b1,b2,b3,b4,b5,b6,b7;
JTextField tf1,tf2,tf3;
JTextArea ta;
public swing22()
{
l1=new JLabel("String :");
l2=new JLabel("St. index :");
l3=new JLabel("End index :");
tf1=new JTextField(15);
tf2=new JTextField(4);
tf3=new JTextField(4);
JPanel p1=new JPanel();
p1.add(l1);p1.add(tf1);
p1.add(l2);p1.add(tf2);
p1.add(l3);p1.add(tf3);
ta=new JTextArea();
ta.setForeground(Color.blue);
tf1.setForeground(Color.red);
tf2.setForeground(Color.red);
tf3.setForeground(Color.red);
Font f1=new Font("Arial",Font.BOLD,20);
tf1.setFont(f1); tf2.setFont(f1);
tf3.setFont(f1); ta.setFont(f1);
JScrollPane jsp=new
JScrollPane(ta,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZ
ONTAL_SCROLLBAR_ALWAYS);
b1=new JButton("insert");
b2=new JButton("replace");
b3=new JButton("append");
b4=new JButton("cut");
b5=new JButton("copy");
b6=new JButton("paste");
b7=new JButton("get info");
JPanel p2=new JPanel();
p2.add(b1);p2.add(b2);p2.add(b3);
p2.add(b4);p2.add(b5);p2.add(b6);p2.add(b7);
Container con=getContentPane();
con.add("North",p1);
con.add(jsp);
con.add("South",p2);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String str=a.getActionCommand();
if(str.equals("insert"))
{
ta.insert(tf1.getText(),ta.getCaretPosition());
}
else if(str.equals("replace"))
{
ta.replaceSelection(tf1.getText());
ta.replaceRange(tf1.getText(),Integer.parseInt(tf2.getText()),Integer.parseInt(tf3.g
etText()));
}
else if(str.equals("append"))
{
ta.append(tf1.getText());
}
else if(str.equals("cut"))
{
ta.cut();
}
else if(str.equals("copy"))
{
ta.copy();
}
else if(str.equals("paste"))
{
ta.paste();
}
else if(str.equals("get info"))
{
System.out.println(ta.getText());
System.out.println(ta.getSelectedText());
System.out.println(ta.getSelectionStart());
System.out.println(ta.getSelectionEnd());
System.out.println(ta.getCaretPosition());
System.out.println(ta.getTabSize());
System.out.println(ta.getLineWrap());
ta.setLineWrap(true);
ta.setTabSize(20);
ta.setSelectionColor(Color.yellow);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing23 extends JFrame
implements ComponentListener,MouseListener
{
public static void main(String args[])
{ swing23 f=new swing23();
f.setBounds(200,100,300,300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing23()
{
addComponentListener(this);
addMouseListener(this);
}
public void componentShown(ComponentEvent c)
{
System.out.println("component shown...");
}
public void componentHidden(ComponentEvent c)
{
System.out.println("component hidden...");
}
public void componentMoved(ComponentEvent c)
{
System.out.println("component moved...");
}
public void componentResized(ComponentEvent c)
{
System.out.println("component resized...");
}
public void mouseClicked(MouseEvent m)
{
setVisible(false);
try{
Thread.sleep(5000);
}catch(InterruptedException e){ System.out.println(e); }
setVisible(true);
}
public void mouseReleased(MouseEvent m){}
public void mousePressed(MouseEvent m){}
public void mouseExited(MouseEvent m){}
public void mouseEntered(MouseEvent m){}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
public class swing24 extends JPanel implements ActionListener
{
public static void main(String args[])
{
JFrame f=new JFrame();
Container con=f.getContentPane();
con.add(new swing24());
f.setSize(700,400);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing24()
{
JButton b1=new JButton("show dialog..");
setBackground(Color.cyan);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str="";
int r =JOptionPane.showConfirmDialog(this,"do you wish to display time
also?","confirmation",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MES
SAGE);
if(r == 0)
{
DateFormat
df=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);
str=df.format(new Date());
}
else if(r==1)
{
DateFormat df=DateFormat.getDateInstance(DateFormat.FULL);
str=df.format(new Date());
}
JOptionPane.showMessageDialog(this,str,"date &
time",JOptionPane.INFORMATION_MESSAGE);
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
public class swing25 extends JFrame
implements ActionListener
{
public static void main(String args[])
{
swing25 f=new swing25();
f.setSize(700,400);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
public swing25()
{
JButton b1=new JButton("show dialog..");
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String msg=(String)JOptionPane.showInputDialog(this,"enter your name :");
JOptionPane.showMessageDialog(this,"hello "+msg);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing26 extends JFrame
implements ActionListener
{
public static void main(String args[])
{
swing26 f=new swing26();
f.setSize(700,400);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
Container con;
public swing26()
{
JButton b1=new JButton("show dialog..");
con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ String colors[]={"red","blue","green","yellow","magenta","pink"};
String msg=(String)JOptionPane.showInputDialog(this,"enter your name
:","colors",JOptionPane.WARNING_MESSAGE,null,colors,colors[2]);
if(msg !=null)
{
if(msg.equals("red"))
con.setBackground(Color.red);
else if(msg.equals("blue"))
con.setBackground(Color.blue);
else if(msg.equals("green"))
con.setBackground(Color.green);
else if(msg.equals("magenta"))
con.setBackground(Color.magenta);
else if(msg.equals("yellow"))
con.setBackground(Color.yellow);
else if(msg.equals("pink"))
con.setBackground(Color.pink);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing27 extends JFrame
implements ActionListener,ContainerListener
{
public static void main(String args[])
{
swing27 f=new swing27();
f.setSize(700,500);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JButton b1,b2,b3;
Container con;
public swing27()
{
b1=new JButton("add");
b2=new JButton("remove");
b3=new JButton("welcome",new ImageIcon("alice.gif"));
con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);con.add(b2);con.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
con.addContainerListener(this);
}
public void actionPerformed(ActionEvent a)
{
String str=a.getActionCommand();
if(str.equals("add"))
con.add(b3);
else
con.remove(b3);
repaint();
}
public void componentAdded(ContainerEvent c)
{
con.setBackground(Color.pink);
}
public void componentRemoved(ContainerEvent c)
{
con.setBackground(Color.orange);
}
}
import javax.swing.*;
import java.awt.event.*;
public class swing28 extends JApplet
implements KeyListener
{
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
System.out.println("key pressed :"+k.getKeyCode());
}
public void keyReleased(KeyEvent k)
{
System.out.println("key released..");
}
public void keyTyped(KeyEvent k)
{
System.out.println("key typed :"+k.getKeyChar());
}
}
/*
<applet code=swing28 width=200 height=200>
</applet>
*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class swing29 extends JFrame
{
Box vb=Box.createVerticalBox();
vb.add(Box.createVerticalGlue());
vb.add(s1);
vb.add(Box.createVerticalGlue());
vb.add(s2);
vb.add(Box.createVerticalGlue());
tf=new JTextField();
tf.setForeground(Color.red);
tf.setFont(new Font("Arial",Font.BOLD,20));
setLayout(new BorderLayout());
add(vb);
add("South",tf);
s2.addChangeListener(this);
}
public void stateChanged(ChangeEvent c)
{
tf.setText(String.valueOf(s2.getValue()));
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class swing32 extends JPanel
implements ActionListener
{ public static void main(String args[])
{
JFrame f1=new JFrame();
f1.getContentPane().add(new swing32());
f1.setSize(600,400);
f1.setVisible(true);
f1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JButton b1,b2,b3;
JLabel l1;
javax.swing.Timer t1;
public swing32()
{
l1=new JLabel(new Date().toString(),JLabel.CENTER);
b1=new JButton("start");
b2=new JButton("stop");
b3=new JButton("restart");
JPanel p1=new JPanel();
p1.add(b1);p1.add(b2);p1.add(b3);
setLayout(new BorderLayout());
add(l1);
add("South",p1);
setLayout(new BorderLayout());
add(tf1);
add("South",b1);
jc=new JColorChooser();
jd=jc.createDialog(this,"color dialog",
true,jc,this,this);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String str=a.getActionCommand();
if(str.equals("OK"))
{
tf1.setForeground(jc.getColor());
jd.dispose();
}
else if(str.equals("Cancel"))
{
jd.dispose();
}
else if(str.equals("show color dialog.."))
{
jd.show();
}
}
}
import javax.swing.*;
import java.awt.*;
public class swing34 extends JApplet
{
public void init()
{ swing24 p1=new swing24();
swing31 p2=new swing31();
swing32 p3=new swing32();
swing33 p4=new swing33();
//JTabbedPane jt=new JTabbedPane();
JTabbedPane jt=new JTabbedPane(JTabbedPane.LEFT);
jt.addTab("dialogs",new ImageIcon("paste.gif"),p1,"dialogs demo");
jt.addTab("sliders",null,p2,"sliders demo");
jt.addTab("timer",null,p3,"timer demo");
jt.insertTab("colors",null,p4,"color chooser demo",1);
Container con=getContentPane();
con.add(jt);
}
}
/*
<applet code=swing34 width=600 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
public class swing35 extends JApplet
{
public void init()
{ swing24 p1=new swing24();
swing31 p2=new swing31();
swing32 p3=new swing32();
JSplitPane jsp=new JSplitPane(JSplitPane.VERTICAL_SPLIT,p1,p2);
JSplitPane jsp1=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
jsp1.setLeftComponent(p3);
jsp1.setRightComponent(jsp);
Container con=getContentPane();
con.add(jsp1);
}
}
/*
<applet code=swing35 width=600 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class swing36 extends JFrame
implements ActionListener
{
public static void main(String args[])
{
swing36 f=new swing36();
f.setSize(800,550);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JMenuItem m11,m12,m13,m14,m21,m22,m23;
JCheckBoxMenuItem m31,m32;
JRadioButtonMenuItem f1,f2,f3,b1,b2,b3;
JTextArea ta;
JFileChooser fc;
public swing36()
{
JMenu m1=new JMenu("File");
m1.setIcon(new ImageIcon("help.gif"));
m1.setMnemonic('f');
m11=new JMenuItem("New");
m12=new JMenuItem("Open",new ImageIcon("open.gif"));
m13=new JMenuItem("Save",new ImageIcon("save.gif"));
m14=new JMenuItem("Exit",'e');
m1.add(m11);
m1.addSeparator();
m1.add(m12);m1.add(m13);
m1.addSeparator();
m1.add(m14);
ta=new JTextArea();
ta.setFont(new Font("Arial",Font.BOLD,20));
ta.setForeground(Color.blue);
JScrollPane jsp=new
JScrollPane(ta,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZ
ONTAL_SCROLLBAR_ALWAYS);
Container con=getContentPane();
con.add("North",mb);
con.add(jsp);
m11.addActionListener(this);
m12.addActionListener(this);
m13.addActionListener(this);
m14.addActionListener(this);
fc=new JFileChooser();
}
public void actionPerformed(ActionEvent a)
{ try{
JMenuItem m=(JMenuItem)a.getSource();
if(m==m11)
ta.setText("");
else if(m==m14)
System.exit(0);
else if(m==m12)
{
int r=fc.showOpenDialog(this);
if(r==JFileChooser.APPROVE_OPTION)
{
File f1=fc.getSelectedFile();
BufferedReader br=new BufferedReader(new FileReader(f1));
String str="";
while((str=br.readLine())!= null)
{
ta.append(str+"\n");
}
br.close();
}
else if(r==JFileChooser.CANCEL_OPTION)
{
JOptionPane.showMessageDialog(this,"cancel button is clicked..");
}
}
else if(m==m13)
{
int r=fc.showSaveDialog(this);
if(r==JFileChooser.APPROVE_OPTION)
{
File f1=fc.getSelectedFile();
FileWriter fp=new FileWriter(f1);
fp.write(ta.getText());
fp.close();
JOptionPane.showMessageDialog(this,"file saved");
}
else if(r==JFileChooser.CANCEL_OPTION)
{
JOptionPane.showMessageDialog(this,"cancel button is clicked..");
}
}
}catch(IOException e)
{
System.out.println(e);
}
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class swing37 extends JFrame
implements ActionListener
{
public static void main(String args[])
{
swing37 f=new swing37();
f.setSize(700,450);
f.setVisible(true);
}
JButton b1,b2,b3;
JTextArea ta;
JMenuItem m1,m2,m3;
JPopupMenu pm;
public swing37()
{
addWindowListener(new mywindow());
ta=new JTextArea();
ta.setFont(new Font("Arial",Font.BOLD,20));
ta.setForeground(Color.blue);
JScrollPane jsp=new
JScrollPane(ta,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZ
ONTAL_SCROLLBAR_ALWAYS);
JToolBar jt=new JToolBar();
jt.setFloatable(false);
jt.add(b1=new JButton(new ImageIcon("cut.gif")));
jt.add(b2=new JButton(new ImageIcon("copy.gif")));
jt.addSeparator();
jt.add(b3=new JButton(new ImageIcon("paste.gif")));
Container con=getContentPane();
con.add("South",jt);
con.add(jsp);
pm=new JPopupMenu();
m1=new JMenuItem("cut");
m2=new JMenuItem("copy");
m3=new JMenuItem("paste");
pm.add(m1);pm.add(m2);pm.add(m3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
ta.addMouseListener(new mymouse());
}
public void actionPerformed(ActionEvent a)
{
Object obj=a.getSource();
if( obj instanceof JButton)
{
JButton b=(JButton)obj;
if(b==b1)
ta.cut();
else if(b==b2)
ta.copy();
else if(b==b3)
ta.paste();
}else if( obj instanceof JMenuItem)
{
JMenuItem m=(JMenuItem)obj;
if(m==m1)
ta.cut();
else if(m==m2)
ta.copy();
else if(m==m3)
ta.paste();
}
}
public class mymouse extends MouseAdapter
{
public void mouseReleased(MouseEvent m)
{
if(m.isPopupTrigger())
{
pm.show(m.getComponent(),m.getX(),m.getY());
}
}
}
public class mywindow extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing38 extends JApplet
{ Canvas c1;
JButton b1;
public void init()
{
b1=new JButton("demo button");
c1=new Canvas();
c1.setBackground(Color.white);
c1.setSize(300,300);
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(b1);con.add(c1);
}
}
/*
<applet code=swing38 width=600 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing39 extends JApplet
implements AdjustmentListener
{ JScrollBar s1,s2;
JTextField tf;
public void init()
{
s1=new JScrollBar();
s2=new JScrollBar(JScrollBar.HORIZONTAL,200,0,0,1000);
s2.setUnitIncrement(10);
s2.setBlockIncrement(50);
s1.setBounds(20,50,30,200);
s2.setBounds(50,20,200,30);
tf=new JTextField();
tf.setBounds(100,100,100,30);
Container con=getContentPane();
con.setLayout(null);
con.add(s1);con.add(s2);con.add(tf);
s1.addAdjustmentListener(this);
s2.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent a)
{
JScrollBar s=(JScrollBar)a.getSource();
tf.setText(String.valueOf(s.getValue()));
}
}
/*
<applet code=swing39 width=500 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing40 extends JApplet
{ JTable jt;
public void init()
{
String columns[]={"student number","student name","student courses"};
String data[][]={{"1001","ram","java,oracle"},
{"1002","sam","c,c++,java"},
{"1003","sita","j2ee,j2me"},
{"1004","raju","java,dba,d2k"}};
jt=new JTable(data,columns);
jt.setSelectionForeground(Color.red);
jt.setSelectionBackground(Color.yellow);
JScrollPane jsp=new JScrollPane(jt);
Container con=getContentPane();
con.add(jsp);
jt.addMouseListener(new mymouse());
}
public class mymouse extends MouseAdapter
{
public void mouseClicked(MouseEvent m)
{
int rows=jt.getRowCount();
int cols=jt.getColumnCount();
int r=jt.getSelectedRow();
int c=jt.getSelectedColumn();
System.out.println("rows :"+rows);
System.out.println("columns :"+cols);
System.out.println("selected row :"+r);
System.out.println("selected column :"+c);
System.out.println("COLUMN NAMES :");
for(int i=0;i<cols;i++)
System.out.println(jt.getColumnName(i));
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class swing41 extends JApplet
implements TreeSelectionListener
{ JTree jt;
JTextField tf;
public void init()
{
DefaultMutableTreeNode n=new DefaultMutableTreeNode("java topics");
DefaultMutableTreeNode n1=new DefaultMutableTreeNode("coretopics");
DefaultMutableTreeNode n2=new DefaultMutableTreeNode("adv.topics");
DefaultMutableTreeNode n11=new DefaultMutableTreeNode("interfaces");
DefaultMutableTreeNode n12=new DefaultMutableTreeNode("packages");
DefaultMutableTreeNode n13=new DefaultMutableTreeNode("exceptions");
DefaultMutableTreeNode n14=new DefaultMutableTreeNode("iostreams");
DefaultMutableTreeNode n15=new DefaultMutableTreeNode("threads");
DefaultMutableTreeNode n21=new DefaultMutableTreeNode("swings");
DefaultMutableTreeNode n22=new DefaultMutableTreeNode("jdbc");
DefaultMutableTreeNode n23=new DefaultMutableTreeNode("servlets");
DefaultMutableTreeNode n24=new DefaultMutableTreeNode("jsp");
DefaultMutableTreeNode n25=new DefaultMutableTreeNode("rmi");
DefaultMutableTreeNode n26=new DefaultMutableTreeNode("sockets");
n1.add(n11);n1.add(n12);n1.add(n13);n1.add(n14);n1.add(n15);
n2.add(n21);n2.add(n22);n2.add(n23);n2.add(n24);n2.add(n25);n2.add(n26);
n.add(n1);n.add(n2);
jt=new JTree(n);
JScrollPane jsp=new JScrollPane(jt);
//jt.setRowHeight(50);
//jt.setEditable(true);
DefaultTreeCellRenderer r=(DefaultTreeCellRenderer)jt.getCellRenderer();
r.setLeafIcon(new ImageIcon("bullet.gif"));
r.setOpenIcon(new ImageIcon("open.gif"));
r.setClosedIcon(new ImageIcon("paste.gif"));
r.setTextSelectionColor(Color.red);
r.setTextNonSelectionColor(Color.blue);
r.setBackgroundSelectionColor(Color.yellow);
tf=new JTextField();
Container con=getContentPane();
con.add(jsp);
con.add("South",tf);
jt.addTreeSelectionListener(this);
}
public void valueChanged(TreeSelectionEvent e)
{
TreePath tp=e.getPath();
tf.setText(tp.toString());
Object obj[]=tp.getPath();
for(int i=0;i<obj.length;i++)
System.out.println(obj[i]);
}
}
/*
<applet code=swing41 width=500 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing42 extends JApplet
implements ActionListener
{ JComboBox jc;
JButton b1;
public void init()
{ String weeks[]={"Sunday","Monday","Wednesday","Thursday","Friday"};
jc=new JComboBox(weeks);
jc.addItem("Saturday");
jc.insertItemAt("Tuesday",2);
jc.setMaximumRowCount(4);
b1=new JButton("remove");
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(jc);con.add(b1);
jc.addActionListener(this);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
Object obj=a.getSource();
if(obj instanceof JComboBox)
{
System.out.println(jc.getItemCount());
System.out.println(jc.getSelectedIndex());
System.out.println(jc.getSelectedItem());
System.out.println(jc.getItemAt(4));
System.out.println(jc.getMaximumRowCount());
}
else if(obj instanceof JButton)
{
jc.removeAllItems();
// jc.removeItem("Tuesday");
// jc.removeItemAt(2);
}
}
}
/*
<applet code=swing42 width=500 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing43 extends JApplet
{ JComboBox jc;
Icon icons[]={new ImageIcon("cut.gif"),new ImageIcon("copy.gif"),new
ImageIcon("paste.gif"),new ImageIcon("new.gif"),new ImageIcon("open.gif"),new
ImageIcon("save.gif"),new ImageIcon("help.gif")};
public void init()
{ String
weeks[]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
};
jc=new JComboBox(weeks);
jc.setMaximumRowCount(4);
jc.setPreferredSize(new Dimension(200,40));
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(jc);
jc.setRenderer(new democlass());
}
public class democlass extends JLabel implements ListCellRenderer
{
public democlass()
{
setOpaque(true);
}
public Component getListCellRendererComponent(JList j1,Object value,int
index,boolean isSelected,boolean hasfocus)
{
if( value !=null)
setText((String)value);
if( index >= 0 && index <= icons.length)
setIcon(icons[index]);
if(isSelected)
{
setBackground(Color.yellow);
setForeground(Color.red);
}
else
{
setBackground(Color.cyan);
setForeground(Color.blue);
}
return this;
}
}
}
/*
<applet code=swing43 width=500 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing44 extends JApplet
{ JList list1;
Icon icons[]={new ImageIcon("cut.gif"),new ImageIcon("copy.gif"),new
ImageIcon("paste.gif"),new ImageIcon("new.gif"),new ImageIcon("open.gif"),new
ImageIcon("save.gif"),new ImageIcon("help.gif")};
public void init()
{ String
weeks[]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
};
list1=new JList(weeks);
JScrollPane jsp=new JScrollPane(list1);
jsp.setPreferredSize(new Dimension(200,150));
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(jsp);
list1.setCellRenderer(new democlass());
}
public class democlass extends JLabel implements ListCellRenderer
{
public democlass()
{
setOpaque(true);
}
public Component getListCellRendererComponent(JList j1,Object value,int
index,boolean isSelected,boolean hasfocus)
{
if( value !=null)
setText((String)value);
if( index >= 0 && index <= icons.length)
setIcon(icons[index]);
if(isSelected)
{
setBackground(Color.yellow);
setForeground(Color.red);
}
else
{
setBackground(Color.cyan);
setForeground(Color.blue);
}
return this;
}
}
}
/*
<applet code=swing44 width=500 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing45 extends JApplet
{ JList list1; JCheckBox c1;
JButton b1;
public void init()
{
String
courses[]={"oracle","java","j2ee","j2me","dba","c++","vc++","d2k","vb.net","asp.net"};
list1=new JList(courses);
JScrollPane jsp=new JScrollPane(list1);
jsp.setPreferredSize(new Dimension(200,150));
list1.setFont(new Font("Arial",Font.BOLD,20));
list1.setForeground(Color.blue);
c1=new JCheckBox("multiple",true);
b1=new JButton("get item(s)");
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(jsp);con.add(c1);con.add(b1);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
if( c1.isSelected())
{
Object items[]=list1.getSelectedValues();
int n[]=list1.getSelectedIndices();
System.out.println("MULTIPLE SELECTIONS..");
for(int i=0;i<items.length;i++)
System.out.println(n[i]+" : "+items[i]);
}
else
{
System.out.println("SINGLE SELECTION...");
System.out.println(list1.getSelectedIndex()+" :
"+list1.getSelectedValue());
}
}
});
c1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent i)
{
if(c1.isSelected())
{
list1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
else
{
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
list1.clearSelection();
}
});
}
}
/*
<applet code=swing45 width=600 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing46 extends JFrame
implements ActionListener
{
public static void main(String args[])
{
swing46 f=new swing46();
f.setSize(700,450);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JButton b1,b2,b3,b4;
JComboBox c;
JPanel mp;
CardLayout cl;
public swing46()
{
b1=new JButton("first");
b2=new JButton("previous");
b3=new JButton("next");
b4=new JButton("last");
String items[]={"card1","card2","card3","card4"};
c=new JComboBox(items);
JPanel tp=new JPanel();
tp.add(b1);tp.add(b2);tp.add(b3);tp.add(b4);tp.add(c);
mp=new JPanel();
cl=new CardLayout();
mp.setLayout(cl);
swing24 c1=new swing24();
swing31 c2=new swing31();
swing32 c3=new swing32();
swing33 c4=new swing33();
mp.add(c1,"card1");
mp.add(c2,"card2");
mp.add(c3,"card3");
mp.add(c4,"card4");
Container con=getContentPane();
con.add("North",tp);
con.add(mp);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
c.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
Object obj=a.getSource();
if(obj instanceof JButton)
{
JButton b=(JButton)obj;
if(b==b1)
cl.first(mp);
else if(b==b2)
cl.previous(mp);
else if(b==b3)
cl.next(mp);
else if(b==b4)
cl.last(mp);
}
else
{
cl.show(mp, (String)c.getSelectedItem() );
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing47 extends JFrame
implements ActionListener
{
public static void main(String args[])
{ swing47 f=new swing47();
f.setSize(220,150);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JProgressBar p1;
JButton b1,b2;
public swing47()
{
p1=new JProgressBar();
b1=new JButton("start");
b2=new JButton("stop");
p1.setBounds(10,10,200,40);
b1.setBounds(10,70,90,30);
b2.setBounds(110,70,90,30);
Container con=getContentPane();
con.setLayout(null);
con.add(p1);con.add(b1);con.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
demothread t1;
public void actionPerformed(ActionEvent a)
{
JButton b=(JButton)a.getSource();
if(b==b1)
{
if( t1 ==null || ! t1.isAlive())
{
t1=new demothread();
t1.start();
}
}
else if(b==b2)
{
t1.flag=true;
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing48 extends JFrame
implements ActionListener
{
public static void main(String args[])
{ swing48 f=new swing48();
f.setSize(220,150);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JButton b1,b2;
Container con;
public swing48()
{
b1=new JButton("start");
b2=new JButton("stop");
b1.setBounds(10,70,90,30);
b2.setBounds(110,70,90,30);
con=getContentPane();
con.setLayout(null);
con.add(b1);con.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
demothread t1;
public void actionPerformed(ActionEvent a)
{
JButton b=(JButton)a.getSource();
if(b==b1)
{
if( t1 ==null || ! t1.isAlive())
{
t1=new demothread();
t1.start();
}
}
else if(b==b2)
{
t1.flag=true;
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing49 extends JFrame
implements ActionListener
{
public static void main(String args[])
{ swing49 f=new swing49();
f.setSize(700,550);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.exit(0);
}
});
}
JMenuItem m1,m2,m3,m4;
JInternalFrame f1;
JDesktopPane jd;
public swing49()
{
JMenu m=new JMenu("Demos");
m.add(m1=new JMenuItem("dialogs"));
m.add(m2=new JMenuItem("slider"));
m.add(m3=new JMenuItem("timer"));
m.add(m4=new JMenuItem("colos"));
jd=new JDesktopPane();
Container con=getContentPane();
con.add("North",mb);
con.add(jd);
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
m4.addActionListener(this);
}
JMenuItem m1,m2,m3;
public swing50()
{
JMenu m=new JMenu("Look & Feel");
m.add(m1=new JMenuItem("Windows"));
m.add(m2=new JMenuItem("Motif"));
m.add(m3=new JMenuItem("Metal"));
Container con=getContentPane();
con.add("North",mb);
con.add(p1);
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
filemenu.add(new JMenuItem("New"));
filemenu.add(new JMenuItem("Open"));
filemenu.addSeparator();
filemenu.add(new JMenuItem("Save"));
filemenu.add(new JMenuItem("Save as"));
filemenu.addSeparator();
filemenu.add(new JMenuItem("New"));
filemenu.add(new JMenuItem("Open"));
filemenu.addSeparator();
filemenu.add(new JMenuItem("Save"));
filemenu.add(new JMenuItem("Save as"));
filemenu.addSeparator();
Object[][] rowdata = {
{"autoexec.bat","149","09-11-07",new Boolean(false)},
{"real","dir","12-11-07",new Boolean(true)},
};
root.add(col11);
root.add(col12);
col11.add(col21);
col11.add(col22);
col21.add(col31);
col31.add(col41);
col31.add(col42);
col31.add(col43);
jdk1.5
class argstest
{
public static void main(String[] args)
{
int x=Integer.parseInt(args[0]);
System.out.println("x value is :"+x);
int y=Integer.parseInt(args[1]);
System.out.println("x value is :"+y);
}
}
class autobox1
{
static int m(Integer v)
{
return v;
}
public static void main(String[] args)
{
int i=10;
Integer ival=m(100);
System.out.println(ival);
}
}
class autobox2
{
public static void main(String[] args)
{
Integer ival =100;
Double dval=98.5;
dval = dval+ival;
System.out.println("dval value is!"+dval);
}
}
enum Apple
{
goldendel,reddel,cortland,kashmiri,london
}
class enumdemo
{
public static void main(String[] args)
{
Apple ap;
ap=Apple.kashmiri;
System.out.println("value of ap is :"+ap);
ap=Apple.london;
if(ap==Apple.london)
System.out.println("ap contains london ");
switch(ap)
{
case goldendel: System.out.println("goldendel is yellow");
break;
import java.io.*;
class simple
{
public static void main(String[] args)
{
try
{
new class1().meth01();
}
catch(exp1 e)
{
System.out.println("Cause is:\n" + e.getCause());
System.out.println("Print StackTrace"+e.printStackTrace());
}
}
}
//===================================//
//This is a new exception class
class exp1 extends Exception
{
public exp1() { }
public exp1(String message)
{
super(message);
}
public exp1(Throwable throwable)
{
super(throwable);
}
public exp1(String message,Throwable throwable)
{
super(message, throwable);
}
}//end exp1
//===================================//
class Class1
{
void meth01() throws exp1
{
try
{
meth02();
}
catch(exp2 e)
{
System.out.println("Cause is:\n" + e.getCause());
throw new exp1("Msg from meth01",e);
}
}
//---------------------------------//
void meth03()
{
try
{
int x = 3/0;
}
catch(ArithmeticException e)
{
IndexOutOfBoundsException ex = new IndexOutOfBoundsException("Msg from
metho03");
ex.initCause(e);
throw ex;
}
}
}
import java.io.*;
class simple
{
public static void main(String[] args)
{
try
{
new Class1().meth01();
}
catch(exp1 e)
{
System.out.println("Cause is:\n" + e.getCause());
// e.printStackTrace();
}
}
}
//===================================//
class Class1
{
void meth01() throws exp1
{
try
{
meth02();
}
catch(exp2 e)
{
System.out.println("Cause is:\n" + e.getCause());
throw new exp1("Msg from meth01",e);
}
}
//---------------------------------//
void meth03()
{
try
{
int x = 3/0;
}
catch(ArithmeticException e)
{
IndexOutOfBoundsException ex = new IndexOutOfBoundsException("Msg from
metho03");
ex.initCause(e);
throw ex;
}
}
}
port java.util.*;
class formatdemo
{
public static void main(String[] args)
{
int a=20,b=30;
Formatter fmt =new Formatter();
fmt.format("formatting %s is easy %d %f ", "with java",10,98.6);
System.out.println(fmt);
}
}
class Gen<T>
{
T ob;
Gen( T o)
{
ob=o;
}
T getob()
{
return ob;
}
void showType()
{
System.out.println("The type of T is "+ob.getClass().getName());
}
}
class Gendemo
{
public static void main(String[] args)
{
Gen<Integer> iob=new Gen<Integer>(66);
iob.showType();
int v= iob.getob();
System.out.println("value is :"+v);
class Avgnum
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int count =0;
double sum=0.0;
System.out.println("enter numbers to find the average");
while(sc.hasNext())
{
if(sc.hasNextDouble())
{
sum +=sc.nextDouble();
count++;
}
else
{
String str =sc.next();
if(str.equals("done")) break;
else
{
System.out.println("the data format error");
return;
}
}
}
System.out.println("the average is :"+sum/count);
}
}
import static java.lang.System.*;
class Test
{
public static void main(String[] args)
{
out.println("Hello World!");
out.println("hello this is core class");
out.println("how r u ");
out.println("hyd");
}
}
class passarray
{
static void vatest(int ... v)
{
System.out.print("number of args:"+v.length+"contents");
for(int x : v)
System.out.print(x+" ");
System.out.println();
}
public static void main(String[] args)
{
//int n1[ ] = {10};
//int n2[ ] = {1,2,3};
//int n3[ ] ={ };
vatest(10);
vatest(10,20);
vatest();
}
}
class passarray2
{
static void vatest(int ... v)
{
System.out.print("number of args:"+v.length+"contents");
for(int x : v)
System.out.print(x+" ");
System.out.println();
}
public static void main(String[] args)
{
vatest(10);
vatest(1,2,3);
vatest();
}
}
sliptest
class NFE
{
public static void main(String[] args)
{
String s="22";
try
{
s=s.concat(".5");
double d = Double.parseDouble(s);
s=Double.toString(d);
int x = (int)(Double.valueOf(s).doubleValue());
System.out.println(x);
}
catch(NumberFormatException e)
{
System.out.println("bad number");
}
}
}
/*
what is the result?
A. 22
B. 22.5
C. 23
D. bad number
E. Compilation fails
F. An uncaught exception is thrown at runtime.
*/
class C extends A
{
int getNum()
{
return num;
}
}
class B
{
public int name;
}
class A
{
B b = new B();
public int num;
}
class Over
{
int doStuff(int a,float b)
{
return 7;
}
}
class Over2 extends Over
{
// insert code here
}
/*
which two methods if inserted independently at line 10 will compile(choose two)
A. private int doStuff(int x,float y) { return 4;}
B. protected int doStuff(int x,float y) { return 4;}
C. Integer doStuff(int d,float e) { return 4;}
D. long doStuff(int x,float y) { return 4;}
E. int doStuff(float x,int y) { return 4;}
*/
class A
{
public void m1()
{
System.out.print("ma");
}
}
class B extends A
{
public static void main(String args[])
{
A a = new B();
a.m1();
}
public void m1()
{
System.out.print("mb");
}
}
/*
what is the result?
A. ma
B. mb
C. mamb
D. Compilation fails
E. An exception is thrown at runtime
*/
class test
{
public static void main(String args[])
{
char ch;
String test2 = "abcd";
String test = new String("abcd");
if(test.equals(test2))
{
if(test == test2)
ch=test.charAt(0);
else
ch=test.charAt(1);
}
else
{
if(test == test2)
ch=test.charAt(2);
else
ch=test.charAt(3);
}
System.out.println(ch);
}
}
class CommandArgs
{
public static void main(String args[])
{
//String [] argh;
int x;
x=args.length;
for(int y=0;y<=x;y++)
{
System.out.print(args[y]);
}
}
}
/*
class TestStr
{
public static void main(String args[])
{
String s1 ="1";
String s2 = "2";
String s3 = s1;
s1="3";
System.out.println(s1 + s2 + s3);
}
}
/*
what is the result?
A. 6
B. 123
C. 321
D. 323
E. compilation fails.
F. An exception is thrown at runtime.
*/
class test
{
public static void main(String args[])
{
int [] arr = {1,2,3,4};
call_array(arr[0],arr);
System.out.println(arr[0]+ ", "+arr[1]);
}
static void call_array(int i,int arr[])
{
arr[i]=6;
i=5;
}
}
A. 1,2
B. 5,2
C. 1,6
D. 5,6
class LoopTest
{
public static void main(String args[])
{
int a =1;
while(a++<=1)
while(a++<=2)
while(a++<=3);
System.out.println("a value is :"+a);
}
}
class TestDogs
{
public static void main(String args[])
{
Dog [][][] theDogs = new Dog[3][2][];
System.out.println(theDogs[2][0][0].toString());
}
}
class Dog{ }
/*
what is the result
A. null
B. the dogs
C. Compilation fails
D. an exception is throwing a t run time;
*/
//what gets printed when the following code is compiled and run with the following
command
//java test 2
class test
{
public static void main(String args[])
{
Integer intObj = Integer.valueOf(args[args.length-1]);
int i = intObj.intValue();
if(args.length >1)
System.out.println(i);
if(args.length >0)
System.out.println(i-1);
else
System.out.println(i-2);
}
}
/*
Select the correct answer
A. test
B. test -1
C. 0
D. 1
E. 2
*/