CoreJava Class Assignment
CoreJava Class Assignment
Source class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
Source Imports java.io.*; class IfElseNestedDemo { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the the marks"); int testscore =Integer.parseInt(br.readLine()); char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) grade = 'B'; } else if (testscore >= 70) grade = 'C'; } else if (testscore >= 60) grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = } }
{ { {
" + grade);
Source public class switchCase { public static void main(String arg[]) { int day=3; switch(day) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } }
Source class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } }
Source class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }
Source class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; //process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } }
public RectangleClass(int l, int b) { length=l; breadth=b; } public int getArea() { return length * breadth; } public int getPerimeter() { return 2*(length+breadth); } public static void main (String[] args) { Rectangle obj1=new Rectangle(5,4);
System.out.println("Rectangle 1\n===================="); System.out.println("Length:" + obj1.length); System.out.println("Breadth:" + obj1.breadth); System.out.println("Area:" + obj1.getArea()); System.out.println("Perimeter:" + obj1.getPerimeter()); } }
Source public class Rectangle { public int length, breadth; public Rectangle(int l) { length=l; breadth=l; } public Rectangle(int l, int b) { length=l; breadth=b; } public int getArea() { return length * breadth; } public int getPerimeter() 9
{ return 2*(length+breadth); } public static void main (String[] args) { Rectangle obj1=new Rectangle(5); Rectangle obj2=new Rectangle(5,4); System.out.println("Rectangle 1\n===================="); System.out.println("Length:" + obj1.length); System.out.println("Breadth:" + obj1.breadth); System.out.println("Area:" + obj1.getArea()); System.out.println("Perimeter:" + obj1.getPerimeter());
System.out.println("Rectangle 2\n===================="); System.out.println("Length:" + obj2.length); System.out.println("Breadth:" + obj2.breadth); System.out.println("Area:" + obj2.getArea()); System.out.println("Perimeter:" + obj2.getPerimeter()); } }
10
Source 1. Call by value public class CallByValueExample { public static void main(String args[]) { int x=5,y=8; CallByValueExample obj=new CallByValueExample(); System.out.println("Before swap"); System.out.println("x:" + x); System.out.println("y:" + y); obj.swap(x, y); System.out.println("After swap"); System.out.println("x:" + x); System.out.println("y:" + y); 11
} public void swap(int a,int b) { int temp; temp=a; a=b; b=temp; } } 2. Call by reference public class CallByRefExample { public int a,b; public static void main(String args[]) { CallByRefExample obj=new CallByRefExample(); obj.a=5; obj.b=8; System.out.println("Before swap"); System.out.println("a:" + obj.a); System.out.println("b:" + obj.b); obj.swap(obj); System.out.println("After swap"); System.out.println("a:" + obj.a); System.out.println("b:" + obj.b); } public void swap(CallByRefExample o) { int temp; temp=o.a; o.a=o.b; o.b=temp; } }
12
public Rectangle(int c, int b) { l=c; this.b=b; } public int getArea() { return l*b; } public int getLength() { return l; } public void setLength(int l) { if(l>=0) { this.l=l; } } public int getBreadth() 13
} class Box extends Rectangle { protected int h; public Box(int l,int b, int h) { super(l,b); this.h=h; } public int getHeight() { return h; } public void setHeight(int h) { if(h>=0) { this.h=h; } } public int getVolume() { return l*b*h; } } public class InheritanceExample { public static void main (String[] args) { Box b=new Box(5,6,7); System.out.println("\nBox\n=================="); System.out.println("Length:" + b.getLength()); System.out.println("Breadth:" + b.getBreadth()); System.out.println("Height:" + b.getHeight()); System.out.println("Volume:" + b.getVolume()); } }
14
Source //demo.class class demo { void showCall() { System.out.println("Call to another class object"); } } //app.class class Data { public int intdata = 0; demo sgsc=new demo(); Data() { intdata = 1; sgsc.showCall(); } protected void finalize() { sgsc = null; } } public class app { public static void main(String args[]) { Data d=new Data(); d = null; } } 15
Source class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } } public class superKeyword extends Superclass { public void printMethod() { //overrides printMethod in Superclass super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { superKeyword s = new superKeyword(); s.printMethod(); } }
16
Source class A{ int i,j; A(int a,int b){ i=a; j=b; } void show(){ System.out.println("i and j: "+i+" "+j); } } class B extends A{ int k; B(int a,int b,int c){ super(a,b); k=c; } void show(){ System.out.println("k: "+k); } } class Override{ public static void main(String args[]){ B subob=new B(1,2,3); subob.show(); } }
17
Source abstract class a{ abstract void callme(); void callmetoo() { System.out.println("This is a concrete method"); } } class b extends a{ void callme(){ System.out.println("b implementation of callme."); } } class abstractDemo{ public static void main(String args[]) { b B=new b(); B.callme(); B.callmetoo(); } }
18
Source interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); } class InterfaceDemo implements Bicycle { InterfaceDemo(){ changeCadence(50); speedUp(10); changeGear(2); changeCadence(40); speedUp(20); changeGear(3); } public void changeCadence(int newValue) { System.out.println("Cadence:"+newValue); } public void changeGear(int newValue) { System.out.println("Gear: "+newValue); } public void speedUp(int increment) { System.out.println("Speed: "+increment); } public static void main(String arg[]) 19
{ new InterfaceDemo(); } }
20
Source
//create package as myPackage package myPackage; public class AA { public int Add(int x, int y) { return (x+y); } }
//create class as BB import myPackage.AA; public class BB { static AA aa = new AA(); public static void main(String arg[]) { System.out.println("Addition of 100 and 50 is: " + aa.Add(100,50)); } }
21
Source class Exc2{ public static void main(String args[]){ int d, a; try{ d=0; a=42/d; System.out.println("This will not be printed"); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement"); } }
22
Source class BankAccount { private static int aids=0; private int nAccountId; private double dBalance; BankAccount(double dInitialBalance) { dBalance=dInitialBalance; nAccountId=++aids; } public int Id() { return nAccountId; } public double Balance() { return(int)((dBalance*100.0+0.5))/100.0; } public void Withdrawal(double dAmount) throws InsufficientFundsException { if(dBalance<dAmount) { throw new InsufficientFundsException(this, dAmount); } dBalance=dAmount; }
23
} class InsufficientFundsException extends Exception { private BankAccount ba; private double dWithdrawalAmount; InsufficientFundsException(BankAccount ba, double dAmount) { super("Insufficient funds in account"); this.ba=ba; dWithdrawalAmount=dAmount; } public String toString() { StringBuffer sb=new StringBuffer(); sb.append("Insufficient funds in account"); sb.append(ba.Id()); sb.append("\nBalance was"); sb.append(ba.Balance()); sb.append("\nWithdrawal was"); sb.append(dWithdrawalAmount); return sb.toString(); } } public class test { public static void main(String[] s) { try { BankAccount ba=new BankAccount(500.0); ba.Withdrawal(500.0); //ba.Balance(); System.out.println("Withdrawal successful !"); } catch(Exception e) { System.out.println(e.toString()); } } }
24
Source class FinallyDemo { static void procA() { try { System.out.println("inside proc"); throw new RuntimeException("demo"); } finally { System.out.println("procA finally"); } } static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB finally"); } } static void procC() { try { 25
System.out.println("inside procC"); } finally { System.out.println("procC finally"); } } public static void main(String args[]) { try { procA(); } catch(Exception e) { System.out.println("exception caught"); } procB(); procC(); } }
26
Source class CustomThread extends Thread { CustomThread(String name) { super(name); start(); } public void run() { try { for(int loop_index = 0; loop_index < 4; loop_index++) { System.out.println((Thread.currentThread()).getName() + " thread here..."); Thread.sleep(1000); } 27
} catch (InterruptedException e) {} System.out.println((Thread.currentThread()).getName() + " ending."); } } class multithread { public static void main(String args[]) { CustomThread thread1 = new CustomThread("first"); CustomThread thread2 = new CustomThread("second"); CustomThread thread3 = new CustomThread("third"); CustomThread thread4 = new CustomThread("fourth"); try { for(int loop_index = 0; loop_index < 10; loop_index++) { System.out.println((Thread.currentThread()).getName() + " thread here..."); Thread.sleep(1000); } } catch (InterruptedException e) {} } }
28
Source class NewThread implements Runnable { String name; Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); } public void run() { try { for(int i = 100; i > 95; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); 29
} } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } } class StartThrd { public static void main(String args[]) { new NewThread("1:"); new NewThread("2:"); new NewThread("3:"); try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Parent thread Interrupted"); } System.out.println("Parent thread exiting."); } }
30
Source class Callme { void call(String msg) { System.out.print("**" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Stop..."); } System.out.println("****"); } } class Caller implements Runnable { String ms; Callme target; Thread h; public Caller(Callme targ, String s) { target = targ; ms = s; h = new Thread(this); h.start(); } // synchronize calls to call() public void run() { synchronized(target) { target.call(ms); } } } class Sync { 31
public static void main(String args[]) { Callme target = new Callme(); Caller c1 = new Caller(target, "Your"); Caller c2 = new Caller(target, "JAVA"); Caller c3 = new Caller(target, "Synchronized"); // wait for threads to end try { c1.h.join(); c2.h.join(); c3.h.join(); } catch(InterruptedException e) { System.out.println("Stop..."); } } }
32
Source import java.io.*; class filereader { public static void main(String args[]) throws Exception { FileReader filereader = new FileReader("OutFile.txt"); char data[] = new char[1024]; int charsread = filereader.read(data); System.out.println(new String(data, 0 , charsread)); filereader.close(); } }
33
Source import java.io.*; class filewriter { public static void main(String args[]) throws Exception { char data[] = {'T','h','i','s',' ','i','s',' ','a', ' ','s','t','r','i','n','g',' ','o','f', ' ','t','e','x','t','.'}; FileWriter filewriter1 = new FileWriter("file1.txt"); for (int loop_index = 0; loop_index < data.length; loop_index++) { filewriter1.write(data[loop_index]); } FileWriter filewriter2 = new FileWriter("file2.txt"); filewriter2.write(data); FileWriter filewriter3 = new FileWriter("file3.txt"); filewriter3.write(data, 5, 10); filewriter3.append("Hello there"); filewriter1.close(); filewriter2.close(); 34
filewriter3.close(); } }
35
Source class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[10]; anArray[0] anArray[1] anArray[2] anArray[3] anArray[4] anArray[5] anArray[6] anArray[7] anArray[8] anArray[9] = = = = = = = = = = // allocates memory for 10 integers
100; // initialize first element 200; // initialize second element 300; // etc. 400; 500; 600; 700; 800; 900; 1000; at at at at at at at at at at index index index index index index index index index index 0: 1: 2: 3: 4: 5: 6: 7: 8: 9: " " " " " " " " " " + + + + + + + + + + anArray[0]); anArray[1]); anArray[2]); anArray[3]); anArray[4]); anArray[5]); anArray[6]); anArray[7]); anArray[8]); anArray[9]);
System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element } }
36
Source import java.util.*; class arraylist { public static void main(String args[]) { ArrayList<String> arraylist=new ArrayList<String>(); arraylist.add("Item 0"); arraylist.add("Item 2"); arraylist.add("Item 3"); arraylist.add("Item 4"); arraylist.add("Item 5"); arraylist.add("Item 6"); arraylist.add(1,"Item 1"); System.out.println("\nUsing the add method"); System.out.println(arraylist); arraylist.remove("Item 5"); System.out.println(arraylist); System.out.println("\nUsing the Iterator interface"); String s; Iterator e=arraylist.iterator(); while (e.hasNext()) { s=(String)e.next(); System.out.println(s); } } } 37
Source enum Mango { Brooks, Manilla, Alphanso, Kesar, Maya } class EnumDemo { public static void main (String args[]) { Mango ap; ap = Mango.Maya; System.out.println("value of ap: " + ap); System.out.println(); ap = Mango.Maya; if (ap == Mango.Manilla) { System.out.println ("ap contains Manilla.\n"); } switch(ap) { case Brooks: System.out.println("Brooks is red."); break; case Manilla: System.out.println("Golden Delicious is Yellow."); break; case Alphanso: System.out.println("Red Delicious is red."); break; case Kesar: System.out.println("Kesar is red."); break; case Maya: System.out.println("Brooks is red."); break; } } } 38
Source import java.util.*; class vector { public static void main(String args[]) { Vector vector = new Vector(5); System.out.println("Capacity: " + vector.capacity()); vector.addElement(new Integer(0)); vector.addElement(new Integer(1)); vector.addElement(new Integer(2)); vector.addElement(new Integer(3)); vector.addElement(new Integer(4)); vector.addElement(new Integer(5)); vector.addElement(new Integer(6)); vector.addElement(new Double(3.14159)); vector.addElement(new Float(3.14159)); System.out.println("Capacity: " + vector.capacity()); System.out.println("Size: " + vector.size()); System.out.println("First item: " + (Integer) vector.firstElement()); System.out.println("Last item: " + (Float) vector.lastElement()); if(vector.contains(new Integer(3))) System.out.println("Found a 3."); } }
39
Source public class StringHandling { public static void main (String[] args) { String s="Hello World Java"; System.out.println ("String:" + s); System.out.println ("Length of the string:" + s.length() ); System.out.println ("Chat At position 7:" + s.charAt(7)); System.out.println ("Position of word \'World\':" + s.indexOf("World")); } }
40
Source class equalsDemo { public static void main(String args[]) { String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; System.out.println(s1 + " equals " + s2 + " -> s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " -> s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s1.equalsIgnoreCase(s4)); } }
41
Source // A bubble sort for Strings. class SortString { static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "country" }; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } }
42
Source import java.util.*; public class DateExample { public static void main(String[] args) { Date dt1=new Date(); Date dt2=new Date("12/25/2008"); dt1.setMonth(5); System.out.println("Local Format"); System.out.println("Date1: " + dt1.toLocaleString()); System.out.println("Date2: " + dt2.toLocaleString()); System.out.println("GMT Format"); System.out.println("Date1: " + dt1.toGMTString()); System.out.println("Date2: " + dt2.toGMTString()); System.out.println("Date 1> Date 2 : " + dt1.after(dt2)); System.out.println("Date 2< Date 1 : " + dt2.before(dt1)); System.out.println("Day:" + dt1.getDay()); System.out.println("Date:" + dt1.getDate()); System.out.println("Month:" + dt1.getMonth()); System.out.println("Year:" + dt1.getYear()); System.out.println("Hours" + dt1.getHours()); System.out.println("Minutes" + dt1.getMinutes()); System.out.println("Seconds" + dt1.getSeconds()); } } 43
Source import java.applet.Applet; import java.awt.*; /* <APPLET CODE=applet1.class WIDTH=200 HEIGHT=200 > </APPLET> */ public class applet1 extends Applet { public void init() { setBackground(Color.white); } public void start() { } public void paint(Graphics g) { g.drawString("Hello from Java!", 60, 100); } public void stop() { } 44
45
46
Source import java.awt.*; import java.applet.*; /* <applet code= "FirstApplet.class" width="500" height="300"></applet> */ public class FirstApplet extends Applet { /** Initialization method that will be called after the applet is loaded * into the browser. */ public void init() { // TODO start asynchronous download of heavy resources } public void paint(Graphics g) //drawing the objects on the applet { int[] x={60,10,110}; int[] y={300,400,400};
g.drawRect(10,10,200,100); //g.drawArc(200,100,100,100,0,180); g.drawArc(10,100,100,60,0,-180); g.drawOval(10,200,100,50); g.drawLine(10,280,200,280); g.drawPolygon(x,y,3); g.setColor(Color.RED); g.fillOval(250,25,100,80); g.setColor(Color.BLUE); g.fillRect(250,250,100,50); g.setFont(new Font("Impact",Font.BOLD,30)); g.drawString("Drawing shapes in Applet",50,450); } }
47
Source import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code ="MouseEvents1" width=300 height=100> </applet> */ public class MouseEvents1 extends Applet implements MouseListener,MouseMotionListener { String msg= " "; int mouseX=0, mouseY=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { 48
mouseX=0; mouseY=10; msg="mouse clicked"; repaint(); } public void mouseEntered(MouseEvent me) { mouseX=0; mouseY=10; msg="mouse entered"; repaint(); } public void mouseExited(MouseEvent me) { mouseX=0; mouseY=10; msg="mouse exited"; repaint(); } public void mousePressed(MouseEvent me) { mouseX=me.getX(); mouseY=me.getY(); msg="mouse pressed"; repaint(); } public void mouseReleased(MouseEvent me) { mouseX=me.getX(); mouseY=me.getY(); msg="mouse released"; repaint(); }
public void mouseDragged(MouseEvent me) { mouseX=me.getX(); mouseY=me.getY(); msg="*"; showStatus("dragging mouse at"+mouseX+","+mouseY); repaint(); } public void mouseMoved(MouseEvent me) { showStatus("moving mouse at"+me.getX()+","+me.getY()); } public void paint(Graphics g) { g.drawString(msg,mouseX,mouseY); } } 49
Source import java.awt.*; import java.awt.event.*; import java.applet.Applet; /* <APPLET CODE=key.class WIDTH=300 HEIGHT=200 > </APPLET> */ public class key extends Applet implements KeyListener { String text = ""; public void init() { setBackground(Color.PINK); addKeyListener(this); requestFocus(); } public void paint(Graphics g) { g.drawString(text, 50, 100); } 50
public void keyTyped(KeyEvent e) { text= "Key Character = "; text = text + e.getKeyChar(); repaint(); } public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { text = "Key Location = "; text = text + e.getKeyLocation(); } }
51
Source import java.applet.Applet; import java.awt.*; import java.awt.event.*; /* <APPLET CODE=multiplier.class WIDTH=290 HEIGHT=200 > </APPLET> */ public class multiplier extends Applet implements ActionListener { TextField text1, text2, text3; Label multiplylabel; Button b1; public void init(){ text1 = new TextField(10); add(text1); multiplylabel = new Label("*"); add(multiplylabel); text2 = new TextField(10); add(text2); b1 = new Button("="); add(b1); b1.addActionListener(this); text3 = new TextField(10); add(text3); } 52
public void actionPerformed(ActionEvent e) { if(e.getSource() == b1){ int product = Integer.parseInt(text1.getText()) * Integer.parseInt(text2.getText()); text3.setText(String.valueOf(product)); } } }
53
Source import java.applet.Applet; import java.awt.*; import java.awt.event.*; /* <APPLET CODE=applet7.class WIDTH=200 HEIGHT=200 > </APPLET> */ public class applet7 extends Applet { public TextField text1; public Button button1; public void init() { text1 = new TextField(20); add(text1); button1 = new Button("Click Here!"); add(button1); a obj = new a(this); 54
button1.addActionListener(obj); } } class a implements ActionListener { applet7 c; a(applet7 appletobject) { c = appletobject; } public void actionPerformed(ActionEvent event) { String msg = new String ("Hello from Java!"); if(event.getSource() == c.button1){ c.text1.setText(msg); } } }
55
Source import java.applet.Applet; import java.awt.*; import java.awt.event.*; /* <APPLET CODE=multiplier2.class WIDTH=200 HEIGHT=200 > </APPLET> */ public class multiplier3 extends Applet implements ActionListener { TextField text1, text2, answertext; Label multiplylabel; Button button1; GridLayout g; public void init() { g = new GridLayout(5, 1); g.setVgap(10); setLayout(g); text1 = new TextField(10); add(text1); multiplylabel = new Label("*", Label.CENTER); add(multiplylabel); text2 = new TextField(10); add(text2); 56
button1 = new Button("="); add(button1); button1.addActionListener(this); answertext = new TextField(10); add(answertext); } public void actionPerformed(ActionEvent e) { if(e.getSource() == button1){ int product = Integer.parseInt(text1.getText()) * Integer.parseInt(text2.getText()); answertext.setText(String.valueOf(product)); } } }
57
Source import java.awt.*; import java.applet.Applet; import java.awt.event.*; /* <APPLET CODE=card.class WIDTH=200 HEIGHT=200 > </APPLET> */ class cardPanel extends Panel { Button button; Label label; cardPanel(card applet, String cardnumber) { button = new Button("Next card"); button.addActionListener(applet); add(button); label = new Label("This is card " + cardnumber); add(label); } } public class card extends Applet implements ActionListener { int index = 1; CardLayout cardlayout; cardPanel panel1, panel2, panel3; public void init() { cardlayout = new CardLayout(); 58
setLayout(cardlayout); panel1 = new cardPanel(this, "one"); panel2 = new cardPanel(this, "two"); panel3 = new cardPanel(this, "three"); add("first", panel1); add("second", panel2); add("third", panel3); cardlayout.show(this, "first"); } public void actionPerformed(ActionEvent event) { switch(++index){ case 1: cardlayout.show(this, "first"); break; case 2: cardlayout.show(this, "second"); break; case 3: cardlayout.show(this, "third"); break; } if(index == 3) index = 0; repaint(); } }
59
Source import java.awt.*; import java.awt.event.*; public class applet14 extends Frame implements ItemListener { private Choice choice1; Label label1 = new Label("Make a choice"); applet14() { super("Sample Choice"); add(label1, BorderLayout.SOUTH); choice1 = new Choice(); choice1.addItem("One"); choice1.addItem("Two"); choice1.addItem("Three"); choice1.addItemListener(this); 60
add(choice1, BorderLayout.CENTER); pack(); setSize(170,getPreferredSize().height); setLocation(25,25); setVisible(true); } public void itemStateChanged(ItemEvent ie) { String state = "Deselected"; if(ie.getStateChange() == ItemEvent.SELECTED) state = "Selected"; label1.setText(ie.getItem() + " " + state ); } public static void main(String args[]) { new applet14(); } }
61
Source import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code="buttonclicks" width=300 height=700> 62
</applet> */ public class buttonclicks extends JApplet implements ActionListener { JTextField txtClk; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI(); } } ); } catch (Exception excep) { System.out.println("Sorry! Can't be created " + excep); } } private void makeGUI() { setLayout(new FlowLayout()); ImageIcon Bulge = new ImageIcon("bulg.jpg"); JButton buClk = new JButton(Bulge); buClk.setActionCommand("Optical Illusion - Bulging"); buClk.addActionListener(this); add(buClk); ImageIcon Wheels = new ImageIcon("wheels.jpg"); buClk = new JButton(Wheels); buClk.setActionCommand("Optical Illusion - Wheels Rotating"); buClk.addActionListener(this); add(buClk); ImageIcon Zollner = new ImageIcon("illus.jpg"); buClk = new JButton(Zollner); buClk.setActionCommand("Zollner-illusion"); buClk.addActionListener(this); add(buClk); txtClk = new JTextField(20); add(txtClk); } public void actionPerformed(ActionEvent ae) { txtClk.setText(ae.getActionCommand()); } }
63
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE=checkselected.class WIDTH=500 HEIGHT=90 > </APPLET> */ public class checkselected extends JApplet implements ItemListener { JCheckBox checks[]; JTextField text; public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); checks = new JCheckBox[5]; for(int loop_index = 1; loop_index <= checks.length - 1; loop_index++){ checks[loop_index] = new JCheckBox("Check " + loop_index); checks[loop_index].addItemListener(this); contentPane.add(checks[loop_index]); } text = new JTextField(40); contentPane.add(text); } public void itemStateChanged(ItemEvent e) { String outString = new String("Currently selected:\n"); for(int loop_index = 1; loop_index <= checks.length - 1; loop_index++){ if(checks[loop_index].isSelected()) { outString += " check box " + loop_index; 64
} } text.setText(outString); } }
65
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE=radiogroup.class WIDTH=340 HEIGHT=200 > </APPLET> */ public class radiogroup extends JApplet implements ItemListener { JRadioButton radio1, radio2, radio3, radio4; ButtonGroup group; JTextField text; public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); group = new ButtonGroup(); radio1 = new JRadioButton("Radio 1"); radio2 = new JRadioButton("Radio 2"); radio3 = new JRadioButton("Radio 3"); radio4 = new JRadioButton("Radio 4"); group.add(radio1); group.add(radio2); group.add(radio3); group.add(radio4); radio1.addItemListener(this); radio2.addItemListener(this); radio3.addItemListener(this); radio4.addItemListener(this); contentPane.add(radio1); contentPane.add(radio2); contentPane.add(radio3); 66
contentPane.add(radio4); text = new JTextField(20); contentPane.add(text); } public void itemStateChanged(ItemEvent e) { if (e.getItemSelectable() == radio1) { text.setText("You clicked radio button 1."); } else if (e.getItemSelectable() == radio2) { text.setText("You clicked radio button 2."); } else if (e.getItemSelectable() == radio3) { text.setText("You clicked radio button 3."); } else if (e.getItemSelectable() == radio4) { text.setText("You clicked radio button 4."); } } }
67
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE = comboimages.class WIDTH = 400 HEIGHT = 430 > </APPLET> */ public class comboimages extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); newModel newmodel = new newModel(); newRenderer newrenderer = new newRenderer(); JComboBox jcombobox = new JComboBox(newmodel); jcombobox.setRenderer(newrenderer); contentPane.add(new JScrollPane(jcombobox)); } } class newModel extends DefaultComboBoxModel { public newModel() { for(int loop_index = 0; loop_index <= 10; loop_index++) { addElement(new Object[] {"Item " + loop_index, 68
new ImageIcon("zoll1.jpg")}); } } } class newRenderer extends JLabel implements ListCellRenderer { public newRenderer() { setOpaque(true); } public Component getListCellRendererComponent( JList jlist, Object obj, int index, boolean isSelected, boolean focus) { newModel model = (newModel)jlist.getModel(); setText((String)((Object[])obj)[0]); setIcon((Icon)((Object[])obj)[1]); if(!isSelected) { setBackground(jlist.getBackground()); setForeground(jlist.getForeground()); } else { setBackground(jlist.getSelectionBackground()); setForeground(jlist.getSelectionForeground()); } return this; } }
69
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; /* <APPLET CODE=fill_slider.class WIDTH=300 HEIGHT=200 > </APPLET> */ public class fill_slider extends JApplet implements ChangeListener { JSlider jslider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 0); public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); jslider.addChangeListener(this); jslider.putClientProperty("JSlider.isFilled", Boolean.TRUE); contentPane.add(jslider); } public void stateChanged(ChangeEvent e) { JSlider jslider1 = (JSlider) e.getSource(); showStatus("Slider minimum: " + jslider1.getMinimum() + ", maximum: " + jslider1.getMaximum() + ", value: " + jslider1.getValue()); } } 70
Source import java.awt.*; import javax.swing.*; /* <APPLET CODE=scrollpane1.class WIDTH=300 HEIGHT=200 > </APPLET> */ public class scrollpane1 extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel jpanel = new JPanel(); jpanel.setLayout(new GridLayout(11, 16)); for(int outer = 0; outer <= 10; outer++) { for(int inner = 0; inner <= 15; inner++) { jpanel.add(new JTextField("Text Field " + outer + ", " + inner)); } } 71
JScrollPane jscrollpane = new JScrollPane(jpanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); JLabel jlabel1 = new JLabel("Horizontal label"); JLabel jlabel2 = new JLabel("Vertical label"); jscrollpane.setColumnHeaderView(jlabel1); jscrollpane.setRowHeaderView(jlabel2); jscrollpane.setViewportBorder(BorderFactory.createEtchedBorder()); contentPane.add(jscrollpane); } }
72
public class JScrollbarExample2 extends JFrame implements AdjustmentListener { JScrollBar jsb1,jsb2,jsb3; JPanel p; public JScrollbarExample2() { jsb1=new JScrollBar(JScrollBar.VERTICAL,0,5,0,256); jsb2=new JScrollBar(JScrollBar.VERTICAL,0,5,0,256); jsb3=new JScrollBar(JScrollBar.VERTICAL,0,5,0,256); p=new JPanel(); jsb1.addAdjustmentListener(this); 73
jsb2.addAdjustmentListener(this); jsb3.addAdjustmentListener(this); jsb1.setBounds(10,30,25,200); jsb2.setBounds(40,30,25,200); jsb3.setBounds(70,30,25,200); p.setLayout(null); p.add(jsb1); p.add(jsb2); p.add(jsb3); add(p); setDefaultCloseOperation (EXIT_ON_CLOSE); setSize(200,300); setVisible(true); p.setBackground(Color.RED); } public void adjustmentValueChanged(AdjustmentEvent e) { Color col=new Color(jsb1.getValue(),jsb2.getValue(),jsb3.getValue()); p.setBackground(col); //repaint(); } public static void main(String args[]) { JScrollbarExample2 frm=new JScrollbarExample2(); } }
74
public class JSliderExample extends JPanel implements ChangeListener { private JSlider mySlider; private JLabel lbSlideValue;
public JSliderExample() { //construct components mySlider = new JSlider (0, 100); lbSlideValue = new JLabel("0"); lbSlideValue.setFont(new Font("Arial",Font.BOLD,28)); //set components properties mySlider.setOrientation (JSlider.HORIZONTAL); mySlider.setMinorTickSpacing (1); mySlider.setMajorTickSpacing (10); mySlider.setPaintLabels(true); mySlider.setPaintTicks(true); mySlider.setValue(0); //adjust size and set layout setPreferredSize(new Dimension (500, 380)); setLayout (null); 75
//add components add (mySlider); add (lbSlideValue); //set component bounds (only needed by Absolute Positioning) lbSlideValue.setBounds (415, 20, 100, 25); mySlider.setBounds (15, 10, 400, 65);
mySlider.addChangeListener(this); }
public void stateChanged(ChangeEvent e) { lbSlideValue.setText(String.valueOf(mySlider.getValue())); } public static void main (String[] args) { JFrame frame = new JFrame ("JSlider Example"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new JSliderExample()); //frame.pack(); frame.setSize(500,250); frame.setVisible (true); } }
76
Source
import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE = menu.class WIDTH = 350 HEIGHT = 280 > </APPLET> */ public class menu extends JApplet implements ActionListener { public void init() { JMenuBar jmenubar = new JMenuBar(); JMenu jmenu1 = new JMenu("File"); JMenuItem jmenuitem1 = new JMenuItem("New..."), jmenuitem2 = new JMenuItem("Open..."), jmenuitem3 = new JMenuItem("Exit"); jmenu1.add(jmenuitem1); jmenu1.add(jmenuitem2); 77
jmenu1.addSeparator(); jmenu1.add(jmenuitem3); jmenuitem1.setActionCommand("You selected New"); jmenuitem2.setActionCommand("You selected Open"); jmenuitem1.addActionListener(this); jmenuitem2.addActionListener(this); JMenu jmenu2 = new JMenu("Edit"); JMenuItem jmenuitem4 = new JMenuItem("Cut"), jmenuitem5 = new JMenuItem("Copy"), jmenuitem6 = new JMenuItem("Paste"); jmenu2.add(jmenuitem4); jmenu2.add(jmenuitem5); jmenu2.add(jmenuitem6); jmenuitem4.setActionCommand("You selected Cut"); jmenuitem5.setActionCommand("You selected Copy"); jmenuitem6.setActionCommand("You selected Paste"); jmenuitem4.addActionListener(this); jmenuitem5.addActionListener(this); jmenuitem6.addActionListener(this); jmenubar.add(jmenu1); jmenubar.add(jmenu2); setJMenuBar(jmenubar); } public void actionPerformed(ActionEvent e) { JMenuItem jmenuitem = (JMenuItem)e.getSource(); showStatus(jmenuitem.getActionCommand()); } }
78
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE = toolbr.class WIDTH = 500 HEIGHT = 280 > </APPLET> */ public class toolbr extends JApplet implements ActionListener { JButton jbutton1 = new JButton("Button 1", new ImageIcon("bulg2.jpg")); JButton jbutton2 = new JButton("Button 2", new ImageIcon("bulg2.jpg")); JButton setrollbutton = new JButton("Set Rollover"); JToolBar jtoolbar = new JToolBar(); JToolBar setrollover = new JToolBar(); public void init() { Container contentPane = getContentPane(); jbutton1.addActionListener(this); jbutton2.addActionListener(this); setrollbutton.addActionListener(this); 79
jtoolbar.add(jbutton1); jtoolbar.addSeparator(); jtoolbar.add(jbutton2); setrollover.add(setrollbutton); contentPane.add(jtoolbar, BorderLayout.NORTH); contentPane.add(setrollover, BorderLayout.SOUTH); jtoolbar.setFloatable(false); jtoolbar.setRollover(false); } public void actionPerformed(ActionEvent e) { if(jtoolbar.isRollover()){ if(e.getSource() == jbutton1) { showStatus("You clicked button 1"); } else if (e.getSource() == jbutton2) { showStatus("You clicked button 2"); } } else { showStatus("Rollover is not set! SET THE ROLLOVER FIRST"); } if(e.getSource() == setrollbutton) { jtoolbar.setRollover(true); showStatus("Setting Rollover Successful"); } } }
80
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE=tooltip.class WIDTH=300 HEIGHT=200 > </APPLET> */ public class tooltip extends JApplet { JButton button = new JButton("Click Me"); JTextField text = new JTextField(20); public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); button.setToolTipText("This is a button."); contentPane.add(button); contentPane.add(text); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { text.setText("Hello from Swing!"); } } ); } } 81
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE = colorchooser.class WIDTH = 200 HEIGHT = 200 > </APPLET> */ public class colorchooser extends JApplet implements ActionListener { JPanel jpanel = new JPanel(); JButton jbutton; public void init() { jbutton = new JButton("Click here to change colors."); jbutton.addActionListener(this); jpanel.add(jbutton); getContentPane().add(jpanel); } public void actionPerformed(ActionEvent e) { 82
83
Source import java.awt.*; import java.io.File; import javax.swing.*; import java.awt.event.*; import javax.swing.filechooser.*; public class filechooser extends JFrame implements ActionListener { JFileChooser chooser = new JFileChooser(); JButton jbutton = new JButton("Display file chooser"); JTextField jtextfield = new JTextField(30); public filechooser() { super(); Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(jbutton); contentPane.add(jtextfield); jbutton.addActionListener(this); 84
} public void actionPerformed(ActionEvent e) { int result = chooser.showOpenDialog(null); File fileobj = chooser.getSelectedFile(); if(result == JFileChooser.APPROVE_OPTION) { jtextfield.setText("You chose " + fileobj.getPath()); } else if(result == JFileChooser.CANCEL_OPTION) { jtextfield.setText("You clicked Cancel"); } } public static void main(String args[]) { JFrame f = new filechooser(); f.setBounds(200, 200, 400, 200); f.setVisible(true); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
85
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE = progressbarupdate.class WIDTH = 400 HEIGHT = 200 > </APPLET> */ public class progressbarupdate extends JApplet { JProgressBar jprogressbar = new JProgressBar(); JButton jbutton = new JButton("Increment the progress bar"); public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(jprogressbar); contentPane.add(jbutton); jprogressbar.setStringPainted(true); jbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jprogressbar.setValue(jprogressbar.getValue() + 10); } 86
}); } }
87
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; /* <APPLET CODE = separatorevents.class WIDTH = 300 HEIGHT = 200 > </APPLET> */ public class separatorevents extends JApplet implements ComponentListener { JSeparator jseparator = new JSeparator(JSeparator.VERTICAL); Dimension dimension = jseparator.getPreferredSize(); public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(new JTextField("Hello from Swing!")); contentPane.add(jseparator); contentPane.add(new JTextField("Hello from Swing!")); addComponentListener(this); 88
} public void componentShown(ComponentEvent e) { jseparator.setPreferredSize(new Dimension(dimension.width, getSize().height)); jseparator.revalidate(); } public void componentResized(ComponentEvent e) { jseparator.setPreferredSize(new Dimension(dimension.width, getSize().height)); jseparator.revalidate(); } public void componentMoved(ComponentEvent e) {} public void componentHidden(ComponentEvent e) {} }
89
Source import javax.swing.*; /* <applet code="Jtabbedpane" height=300 width=300> </applet> */ public class Jtabbedpane extends JApplet { public void init() { JTabbedPane jtp=new JTabbedPane(); jtp.addTab("Cities",new CitiesPanel()); jtp.addTab("Colors",new ColorsPanel()); jtp.addTab("Flavours",new FlavoursPanel()); getContentPane().add(jtp); } } class CitiesPanel extends JPanel { public CitiesPanel() 90
{ JCheckBox b1=new JCheckBox("new york"); add(b1); JCheckBox b2=new JCheckBox("japan"); add(b2); JCheckBox b3=new JCheckBox("india"); add(b3); JCheckBox b4=new JCheckBox("kandivli"); add(b4); } } class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1=new JCheckBox("red"); add(cb1); JCheckBox cb2=new JCheckBox("blue"); add(cb2); JCheckBox cb3=new JCheckBox("yellow"); add(cb3); JCheckBox cb4=new JCheckBox("green"); add(cb4); } } class FlavoursPanel extends JPanel { public FlavoursPanel() { JComboBox jcb= new JComboBox(); jcb.addItem("Pista"); jcb.addItem("Chocolet"); jcb.addItem("Milk"); jcb.addItem("Badam"); add(jcb); } }
91
Source import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.tree.*; /*<applet code="JTreeEventsDemo" width=250 height=150> </applet> */ public class JTreeEventsDemo extends JApplet { JTree tree; JTextField jtf; public void init(){ Container contentPane=getContentPane(); contentPane.setLayout(new BorderLayout()); DefaultMutableTreeNode top=new DefaultMutableTreeNode("Option"); DefaultMutableTreeNode top.add(a); DefaultMutableTreeNode a.add(a1); DefaultMutableTreeNode a.add(a2); DefaultMutableTreeNode a.add(aa1); DefaultMutableTreeNode a=new DefaultMutableTreeNode("A"); a1=new DefaultMutableTreeNode("A1"); a2=new DefaultMutableTreeNode("A2"); aa1=new DefaultMutableTreeNode("AA1"); aa2=new DefaultMutableTreeNode("AA2"); 92
a.add(aa2); DefaultMutableTreeNode b=new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1=new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2=new DefaultMutableTreeNode("B2"); b.add(b2); tree=new JTree(top); int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp=new JScrollPane(tree,v,h); contentPane.add(jsp,BorderLayout.CENTER); jtf=new JTextField(" ",20); contentPane.add(jtf,BorderLayout.SOUTH); tree.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent me) { doMouseClicked(me); } }); } void doMouseClicked(MouseEvent me) { TreePath tp=tree.getPathForLocation(me.getX(),me.getY()); if(tp!=null) jtf.setText(tp.toString()); else jtf.setText(" "); } }
93
Source import java.awt.Graphics; import java.awt.Image; import java.awt.Color; /* <APPLET CODE=cat.class WIDTH=600 HEIGHT=100 > </APPLET> */ public class cat extends java.applet.Applet implements Runnable { Image catpics[] = new Image[9]; Image currentimg; Thread runner; 94
int xpos; int ypos = 50; public void init() { String catsrc[] = { "right1.gif", "right2.gif", "stop.gif", "yawn.gif", "scratch1.gif", "scratch2.gif","sleep1.gif", "sleep2.gif", "awake.gif" }; for (int i=0; i < catpics.length; i++) { catpics[i] = getImage(getDocumentBase(),catsrc[i]); } } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { if (runner != null) { runner.stop(); runner = null; } } public void run() { setBackground(Color.white); catrun(0, size().width / 2); currentimg = catpics[2]; repaint(); pause(1000); currentimg = catpics[3]; repaint(); pause(1000); catscratch(4); catsleep(5); currentimg = catpics[8]; repaint(); pause(500); catrun(xpos, size().width + 10); } void catrun(int start, int end) { for (int i = start; i < end; i += 10) { xpos = i; if (currentimg == catpics[0]) currentimg = catpics[1]; else currentimg = catpics[0]; repaint(); 95
pause(150); } } void catscratch(int numtimes) { for (int i = numtimes; i > 0; i--) { currentimg = catpics[4]; repaint(); pause(150); currentimg = catpics[5]; repaint(); pause(150); } } void catsleep(int numtimes) { for (int i = numtimes; i > 0; i--) { currentimg = catpics[6]; repaint(); pause(250); currentimg = catpics[7]; repaint(); pause(250); } } void pause(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { } } public void paint(Graphics g) { if (currentimg != null) g.drawImage(currentimg, xpos, ypos, this); } }
96
Source import import import import import import import import import java.io.*; java.net.*; java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.event.*; javax.swing.border.*; javax.sound.sampled.*; javax.sound.midi.*;
public class SoundPlayer extends JComponent { boolean midi; Sequence sequence; Sequencer sequencer; Clip clip; boolean playing = false; int audioLength; int audioPosition = 0; JButton play; 97
JSlider progress; JLabel time; Timer timer; public static void main(String args[]) throws IOException, UnsupportedAudioFileException, LineUnavailableException, MidiUnavailableException, InvalidMidiDataException { SoundPlayer player;
File file = new File("trippygaia1.mid"); boolean ismidi; try { MidiSystem.getMidiFileFormat(file); ismidi = true; } catch(InvalidMidiDataException e) { ismidi = false; } player = new SoundPlayer(file, ismidi); JFrame f = new JFrame("SoundPlayer"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane( ).add(player, "Center"); f.pack( ); f.setVisible(true); } public SoundPlayer(File f, boolean isMidi) throws IOException, UnsupportedAudioFileException, LineUnavailableException, MidiUnavailableException, InvalidMidiDataException { if (isMidi) { midi = true; sequencer = MidiSystem.getSequencer( ); sequencer.open( ); Synthesizer synth = MidiSystem.getSynthesizer( ); synth.open( ); Transmitter transmitter = sequencer.getTransmitter( ); Receiver receiver = synth.getReceiver( ); transmitter.setReceiver(receiver); sequence = MidiSystem.getSequence(f); sequencer.setSequence(sequence); audioLength = (int)sequence.getTickLength( ); } else { midi = false; AudioInputStream ain = AudioSystem.getAudioInputStream(f); 98
try { DataLine.Info info = new DataLine.Info(Clip.class,ain.getFormat( )); clip = (Clip) AudioSystem.getLine(info); clip.open(ain); } finally { ain.close( ); } audioLength = (int)(clip.getMicrosecondLength( )/1000); } play = new JButton("Play"); progress = new JSlider(0, audioLength, 0); time = new JLabel("0"); play.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent e) { if (playing) stop( ); else play( ); } }); progress.addChangeListener(new ChangeListener( ) { public void stateChanged(ChangeEvent e) { int value = progress.getValue( ); if (midi) time.setText(value + ""); else time.setText(value/1000 + "." + (value%1000)/100); if (value != audioPosition) skip(value); } }); timer = new javax.swing.Timer(100, new ActionListener( ) { public void actionPerformed(ActionEvent e) { tick( ); } }); Box row = Box.createHorizontalBox( ); row.add(play); row.add(progress); row.add(time); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.add(row); if (midi) addMidiControls( ); else addSampledControls( ); } public void play( ) { if (midi) sequencer.start( ); else clip.start( ); timer.start( ); play.setText("Stop"); playing = true; } public void stop( ) { timer.stop( ); 99
if (midi) sequencer.stop( ); else clip.stop( ); play.setText("Play"); playing = false; } public void reset( ) { stop( ); if (midi) sequencer.setTickPosition(0); else clip.setMicrosecondPosition(0); audioPosition = 0; progress.setValue(0); } public void skip(int position) { if (position < 0 || position > audioLength) return; audioPosition = position; if (midi) sequencer.setTickPosition(position); else clip.setMicrosecondPosition(position * 1000); progress.setValue(position); } public int getLength( ) { return audioLength; } void tick( ) { if (midi && sequencer.isRunning( )) { audioPosition = (int)sequencer.getTickPosition( ); progress.setValue(audioPosition); } else if (!midi && clip.isActive( )) { audioPosition = (int)(clip.getMicrosecondPosition( )/1000); progress.setValue(audioPosition); } else reset( ); } void addSampledControls( ) { try { FloatControl gainControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN); if (gainControl != null) this.add(createSlider(gainControl)); } catch(IllegalArgumentException e) { } try { FloatControl panControl = (FloatControl)clip.getControl(FloatControl.Type.PAN); if (panControl != null) this.add(createSlider(panControl)); } catch(IllegalArgumentException e) { } JSlider createSlider(final FloatControl c) { if (c == null) return null; final JSlider s = new JSlider(0, 1000); final float min = c.getMinimum( ); final float max = c.getMaximum( ); 100 }
final float width = max-min; float fval = c.getValue( ); s.setValue((int) ((fval-min)/width * 1000)); java.util.Hashtable labels = new java.util.Hashtable(3); labels.put(new Integer(0), new JLabel(c.getMinLabel( ))); labels.put(new Integer(500), new JLabel(c.getMidLabel( ))); labels.put(new Integer(1000), new JLabel(c.getMaxLabel( ))); s.setLabelTable(labels); s.setPaintLabels(true); s.setBorder(new TitledBorder(c.getType( ).toString( ) + " " + c.getUnits( ))); s.addChangeListener(new ChangeListener( ) { public void stateChanged(ChangeEvent e) { int i = s.getValue( ); float f = min + (i*width/1000.0f); c.setValue(f); } }); return s; } void addMidiControls( ) { final JSlider tempo = new JSlider(50, 200); tempo.setValue((int)(sequencer.getTempoFactor( )*100)); tempo.setBorder(new TitledBorder("Tempo Adjustment (%)")); java.util.Hashtable labels = new java.util.Hashtable( ); labels.put(new Integer(50), new JLabel("50%")); labels.put(new Integer(100), new JLabel("100%")); labels.put(new Integer(200), new JLabel("200%")); tempo.setLabelTable(labels); tempo.setPaintLabels(true); tempo.addChangeListener(new ChangeListener( ) { public void stateChanged(ChangeEvent e) { sequencer.setTempoFactor(tempo.getValue( )/100.0f); } }); this.add(tempo); Track[ ] tracks = sequence.getTracks( ); for(int i = 0; i < tracks.length; i++) { final int tracknum = i; final JCheckBox solo = new JCheckBox("solo"); final JCheckBox mute = new JCheckBox("mute"); solo.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent e) { sequencer.setTrackSolo(tracknum,solo.isSelected( )); } }); mute.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent e) { sequencer.setTrackMute(tracknum,mute.isSelected( )); } });
101
Box box = Box.createHorizontalBox( ); box.add(new JLabel("Track " + tracknum)); box.add(Box.createHorizontalStrut(10)); box.add(solo); box.add(Box.createHorizontalStrut(10)); box.add(mute); box.add(Box.createHorizontalGlue( )); this.add(box); } } }
102
Source
import java.io.*; import java.net.*; import java.util.Date; public class URLExample { public static void main(String args[]) throws Exception { int character; //URL url = new URL("http://localhost"); URL url = new URL("file://///server/common/test.txt"); URLConnection urlconnection = url.openConnection(); System.out.println("Content type: " + urlconnection.getContentType()); System.out.println("Document date: " + new Date(urlconnection.getDate())); System.out.println("Last modified: " + Date(urlconnection.getLastModified())); new
System.out.println("Document expires: " + urlconnection.getExpiration()); int contentlength = urlconnection.getContentLength(); System.out.println("Content length: " + contentlength); //if (contentlength > 0) 103
//{ InputStream in = urlconnection.getInputStream(); while ((character = in.read()) != -1) { System.out.print((char) character); } in.close(); //} System.out.println (""); } }
104
Source Server Program import java.io.*; import java.net.*; public class Server { public static void main(String[] args ) { try { ServerSocket server = new ServerSocket(5000); System.out.println("Server waiting for connection..."); Socket client = server.accept( ); System.out.println("Client Connected..."); BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter (client.getOutputStream(),true);
do { System.out.print("Me:"); Msg=br.readLine(); out.println(Msg); System.out.println("Client:" + in.readLine()); }while(!Msg.equals("Bye")); out.print(Msg); server.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } } Client Program import java.net.*; import java.io.*; public class Client { public static void main(String args[]) { try { Socket client = new Socket("127.0.0.1", 5000); System.out.println("Connected to Server..."); BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter (client.getOutputStream(),true);
//read from key board BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String Msg; do { System.out.println("Server:" + in.readLine()); System.out.print("Me:"); Msg=br.readLine(); out.println(Msg); }while(!Msg.equals("Bye")); out.print(Msg); client.close(); 106
107
Source import import import import import import javax.swing.*; javax.swing.table.*; java.awt.*; java.sql.*; java.io.*; java.util.*;
public class JDBCExample extends JFrame { Connection con; Statement stmt; ResultSet rs; JTable tb;
public JDBCExample() { super("JDBC JTable Example"); AbstractTableModel aTable; tb=new JTable(); try { String[] tableColumnsName = {"ProductID","ProductName","UnitPrice","Category","QuantityPerUnit"}; 108
DefaultTableModel aModel = (DefaultTableModel) tb.getModel(); aModel.setColumnIdentifiers(tableColumnsName); Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","admin"," "); stmt=con.createStatement(); rs=stmt.executeQuery("select * from Product");
while(rs.next()) { Object[] objects = new Object[colNo]; for(int i=0;i<colNo;i++) { objects[i]=rs.getObject(i+1); } aModel.addRow(objects); } tb.setModel(aModel); //tb=new JTable(aTable); JScrollPane pane = new JScrollPane(tb); add(pane); setSize(400,300); setVisible(true);
109
Source
public class ProductForm extends JPanel implements ActionListener { private JLabel lbProductID; private JTextField txtProductID; private JLabel lbProduct; private JTextField txtProduct; private JLabel lbUnitPrice; private JTextField txtUnitPrice; private JLabel lbCategory; private JTextField txtCategory; private JLabel lbQty; private JTextField txtQty; 110
dbConnect db; int i=0; public ProductForm() { //construct components lbProductID = new JLabel ("Product ID"); txtProductID = new JTextField (5); lbProduct = new JLabel ("Product Name"); txtProduct = new JTextField (5); lbUnitPrice = new JLabel ("Unit Price"); txtUnitPrice = new JTextField (5); lbCategory = new JLabel ("Category"); txtCategory = new JTextField (5); lbQty = new JLabel ("Quantity Per unit"); txtQty = new JTextField (5); btnPrev = new JButton ("<<"); btnNext = new JButton (">>"); btnFirst = new JButton ("|<"); btnLast = new JButton (">|"); //adjust size and set layout setPreferredSize (new Dimension (468, 325)); setLayout (null); //add components add (lbProductID); add (txtProductID); add (lbProduct); add (txtProduct); add (lbUnitPrice); add (txtUnitPrice); add (lbCategory); add (txtCategory); add (lbQty); add (txtQty); add (btnPrev); add (btnNext); add (btnFirst); add (btnLast); //set component bounds (only needed by Absolute Positioning) lbProductID.setBounds (105, 40, 65, 25); txtProductID.setBounds (170, 40, 145, 25); lbProduct.setBounds (85, 70, 85, 25); txtProduct.setBounds (170, 70, 145, 25); lbUnitPrice.setBounds (110, 100, 60, 25); txtUnitPrice.setBounds (170, 100, 145, 25); lbCategory.setBounds (115, 130, 55, 25); txtCategory.setBounds (170, 130, 145, 25); lbQty.setBounds (70, 160, 100, 25); txtQty.setBounds (170, 160, 145, 25); 111
btnPrev.setBounds (175, 285, 50, 25); btnNext.setBounds (230, 285, 50, 25); btnFirst.setBounds (125, 285, 45, 25); btnLast.setBounds (285, 285, 50, 25); btnFirst.addActionListener(this); btnPrev.addActionListener(this); btnNext.addActionListener(this); btnLast.addActionListener(this); db=new dbConnect(); displayData(); } public void displayData() { Product prod=db.getProduct(i); txtProductID.setText(String.valueOf(prod.ProductID)); txtProduct.setText(prod.product); txtUnitPrice.setText(String.valueOf(prod.UnitPrice)); txtQty.setText(String.valueOf(prod.QtyPerUnit)); txtCategory.setText(prod.Category); } public void actionPerformed(ActionEvent e) { if(e.getSource()==btnFirst) { i=0; displayData(); } if(e.getSource()==btnPrev) { if(i>0) { i--; displayData(); } } if(e.getSource()==btnNext) { if(i<db.getRowCount()-1) { i++; displayData(); } } if(e.getSource()==btnLast) { i=db.getRowCount()-1; displayData(); }
112
} public static void main (String[] args) { JFrame frame = new JFrame ("ProductForm"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new ProductForm()); frame.pack(); frame.setVisible (true); } }
int ProductID; String product; String Category; int UnitPrice; int QtyPerUnit;
class dbConnect { Connection con; Statement stmt; ResultSet rs; ArrayList<Product> products=new ArrayList<Product>(); public int getRowCount() { return products.size(); } public Product getProduct(int pos) { Product prod=(Product)products.get(pos); return prod; }
public dbConnect() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); stmt=con.createStatement(); rs=stmt.executeQuery("select * from product"); while(rs.next()) { Product prod=new Product(); prod.ProductID=rs.getInt("ProductID"); prod.product =rs.getString("ProductName"); prod.UnitPrice=rs.getInt("UnitPrice"); prod.QtyPerUnit=rs.getInt("QuantityPerunit"); 113
prod.Category =rs.getString("Category"); products.add(prod); } } catch(Exception ex) { } } public Boolean AddProduct(Product prod) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); PreparedStatement pstmt=con.prepareStatement("insert into product(ProductName,UnitPrice,Category,QuantityPerunit) values('" + prod.product + "',"+ prod.UnitPrice +",'"+ prod.Category +"',"+ prod.QtyPerUnit +")"); pstmt.executeUpdate(); return true; } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.toString()); return false; } } public Boolean UpdateProduct(Product prod) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); PreparedStatement pstmt=con.prepareStatement("update product Set ProductName='" + prod.product + "',UnitPrice="+ prod.UnitPrice +",Category='"+ prod.Category +"',QuantityPerunit="+ prod.QtyPerUnit +" where ProductID=" + prod.ProductID); pstmt.executeUpdate(); return true; } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.toString()); return false; } } public Boolean DeleteProduct(Product prod) { try { 114
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); PreparedStatement pstmt=con.prepareStatement("delete from product where ProductID=" + prod.ProductID); pstmt.executeUpdate(); return true; } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.toString()); return false; } } }
115
Source import import import import import import java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.event.*; java.sql.*; java.util.*;
public class ProductForm extends JPanel implements ActionListener { private JLabel lbProductID; private JTextField txtProductID; private JLabel lbProduct; private JTextField txtProduct; private JLabel lbUnitPrice; 116
private private private private private private private private private private private private private
JTextField txtUnitPrice; JLabel lbCategory; JTextField txtCategory; JLabel lbQty; JTextField txtQty; JButton btnNew; JButton btnAdd; JButton btnUpdate; JButton btnDelete; JButton btnPrev; JButton btnNext; JButton btnFirst; JButton btnLast;
dbConnect db; int i=0; public ProductForm() { //construct components lbProductID = new JLabel ("Product ID"); txtProductID = new JTextField (5); lbProduct = new JLabel ("Product Name"); txtProduct = new JTextField (5); lbUnitPrice = new JLabel ("Unit Price"); txtUnitPrice = new JTextField (5); lbCategory = new JLabel ("Category"); txtCategory = new JTextField (5); lbQty = new JLabel ("Quantity Per unit"); txtQty = new JTextField (5); btnNew = new JButton ("New"); btnAdd = new JButton ("Add"); btnUpdate = new JButton ("Update"); btnDelete = new JButton ("Delete"); btnPrev = new JButton ("<<"); btnNext = new JButton (">>"); btnFirst = new JButton ("|<"); btnLast = new JButton (">|"); //adjust size and set layout setPreferredSize (new Dimension (468, 325)); setLayout (null); //add components add (lbProductID); add (txtProductID); add (lbProduct); add (txtProduct); add (lbUnitPrice); add (txtUnitPrice); add (lbCategory); add (txtCategory); add (lbQty); add (txtQty); add (btnNew); add (btnAdd); add (btnUpdate); add (btnDelete); add (btnPrev); 117
add (btnNext); add (btnFirst); add (btnLast); //set component bounds (only needed by Absolute Positioning) lbProductID.setBounds (105, 40, 65, 25); txtProductID.setBounds (170, 40, 145, 25); lbProduct.setBounds (85, 70, 85, 25); txtProduct.setBounds (170, 70, 145, 25); lbUnitPrice.setBounds (110, 100, 60, 25); txtUnitPrice.setBounds (170, 100, 145, 25); lbCategory.setBounds (115, 130, 55, 25); txtCategory.setBounds (170, 130, 145, 25); lbQty.setBounds (70, 160, 100, 25); txtQty.setBounds (170, 160, 145, 25); btnNew.setBounds (85, 225, 65, 25); btnAdd.setBounds (155, 225, 75, 25); btnUpdate.setBounds (235, 225, 80, 25); btnDelete.setBounds (320, 225, 70, 25); btnPrev.setBounds (175, 285, 50, 25); btnNext.setBounds (230, 285, 50, 25); btnFirst.setBounds (125, 285, 45, 25); btnLast.setBounds (285, 285, 50, 25); btnFirst.addActionListener(this); btnPrev.addActionListener(this); btnNext.addActionListener(this); btnLast.addActionListener(this); btnNew.addActionListener(this); btnAdd.addActionListener(this); btnUpdate.addActionListener(this); btnDelete.addActionListener(this); db=new dbConnect(); displayData(); } public void displayData() { Product prod=db.getProduct(i); txtProductID.setText(String.valueOf(prod.ProductID)); txtProduct.setText(prod.product); txtUnitPrice.setText(String.valueOf(prod.UnitPrice)); txtQty.setText(String.valueOf(prod.QtyPerUnit)); txtCategory.setText(prod.Category); } public void actionPerformed(ActionEvent e) { if(e.getSource()==btnFirst) { i=0; displayData(); } if(e.getSource()==btnPrev) { if(i>0) 118
{ i--; displayData(); } } if(e.getSource()==btnNext) { if(i<db.getRowCount()-1) { i++; displayData(); } } if(e.getSource()==btnLast) { i=db.getRowCount()-1; displayData(); } if(e.getSource()==btnNew) { txtProductID.setText(""); txtProduct.setText(""); txtUnitPrice.setText(""); txtQty.setText(""); txtCategory.setText(""); } if(e.getSource()==btnAdd) { Product prod=new Product(); prod.product=txtProduct.getText(); prod.UnitPrice=Integer.parseInt(txtUnitPrice.getText()); prod.QtyPerUnit=Integer.parseInt(txtQty.getText()); prod.Category=txtCategory.getText(); if(db.AddProduct(prod)) { JOptionPane.showMessageDialog(this,"Record Added successfully"); db=new dbConnect(); i=db.getRowCount()-1; displayData(); } else { JOptionPane.showMessageDialog(this,"Record Adding failed"); } } if(e.getSource()==btnUpdate) { Product prod=new Product(); prod.ProductID=Integer.parseInt(txtProductID.getText()); 119
prod.product=txtProduct.getText(); prod.UnitPrice=Integer.parseInt(txtUnitPrice.getText()); prod.QtyPerUnit=Integer.parseInt(txtQty.getText()); prod.Category=txtCategory.getText(); if(db.UpdateProduct(prod)) { JOptionPane.showMessageDialog(this,"Record Updated Successfully"); db=new dbConnect(); i=db.getRowCount()-1; displayData(); } else { JOptionPane.showMessageDialog(this,"Record Updating Failed"); } } if(e.getSource()==btnDelete) { Product prod=new Product(); prod.ProductID=Integer.parseInt(txtProductID.getText());
if(db.DeleteProduct(prod)) { JOptionPane.showMessageDialog(this,"Record Deleted Successfully"); db=new dbConnect(); i=0; displayData(); } else { JOptionPane.showMessageDialog(this,"Record Deleting Failed"); } } } public static void main (String[] args) { JFrame frame = new JFrame ("ProductForm"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new ProductForm()); frame.pack(); frame.setVisible (true); } }
public int QtyPerUnit; } class dbConnect { Connection con; Statement stmt; ResultSet rs; ArrayList<Product> products=new ArrayList<Product>(); public int getRowCount() { return products.size(); } public Product getProduct(int pos) { Product prod=(Product)products.get(pos); return prod; }
public dbConnect() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); stmt=con.createStatement(); rs=stmt.executeQuery("select * from product"); while(rs.next()) { Product prod=new Product(); prod.ProductID=rs.getInt("ProductID"); prod.product =rs.getString("ProductName"); prod.UnitPrice=rs.getInt("UnitPrice"); prod.QtyPerUnit=rs.getInt("QuantityPerunit"); prod.Category =rs.getString("Category"); products.add(prod); } } catch(Exception ex) { } } public Boolean AddProduct(Product prod) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
121
con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); PreparedStatement pstmt=con.prepareStatement("insert into product(ProductName,UnitPrice,Category,QuantityPerunit) values('" + prod.product + "',"+ prod.UnitPrice +",'"+ prod.Category +"',"+ prod.QtyPerUnit +")"); pstmt.executeUpdate(); return true; } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.toString()); return false; } } public Boolean UpdateProduct(Product prod) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); PreparedStatement pstmt=con.prepareStatement("update product Set ProductName='" + prod.product + "',UnitPrice="+ prod.UnitPrice +",Category='"+ prod.Category +"',QuantityPerunit="+ prod.QtyPerUnit +" where ProductID=" + prod.ProductID); pstmt.executeUpdate(); return true; } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.toString()); return false; } } public Boolean DeleteProduct(Product prod) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:JavaLecture","",""); PreparedStatement pstmt=con.prepareStatement("delete from product where ProductID=" + prod.ProductID); pstmt.executeUpdate(); return true; } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.toString()); return false; } } }
122
Source import javax.xml.parsers.*; import org.w3c.dom.*; import java.io.*; public class XMLReader { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("books.xml"));
Node root=document.getDocumentElement();
123
//For getting the node names System.out.println("Root Element:" + root.getNodeName()); Node childNodes=root.getChildNodes().item(1); System.out.println("Child Element:" + childNodes.getNodeName()); Node grandChild1=childNodes.getChildNodes().item(1); System.out.println("Grand Child 1:" + grandChild1.getNodeName()); Node grandChild2=childNodes.getChildNodes().item(3); System.out.println("Grand Child 2:" + grandChild2.getNodeName()); Node grandChild3=childNodes.getChildNodes().item(5); System.out.println("Grand Child 3:" + grandChild3.getNodeName());
System.out.println("\n\n================Book Data================\n");
for(int i=1;i<root.getChildNodes().getLength();i+=2) { Node childNode=root.getChildNodes().item(i); Node titleNode=childNode.getChildNodes().item(1); Node authorNode=childNode.getChildNodes().item(3); Node priceNode=childNode.getChildNodes().item(5); System.out.println("Title:" + titleNode.getTextContent()); System.out.println("======================"); System.out.println("Author:" + authorNode.getTextContent()); System.out.println("Price:" + priceNode.getTextContent()); System.out.println(""); }
} }
124
Source import import import import import import import javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.*; javax.xml.transform.stream.*; org.w3c.dom.*; org.xml.sax.*; java.io.*;
public class WriteXMLFile { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("books.xml")); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(true) { Node BooksNode=document.getDocumentElement();
125
Node BookNode=document.createElement("book"); Node TitleNode=document.createElement("title"); Node AuthorNode=document.createElement("author"); Node PriceNode=document.createElement("price"); System.out.println("enter title"); TitleNode.setTextContent(br.readLine()); System.out.println("enter author"); AuthorNode.setTextContent(br.readLine()); System.out.println("enter price"); PriceNode.setTextContent(br.readLine());
BooksNode.appendChild(BookNode); BookNode.appendChild(TitleNode); BookNode.appendChild(AuthorNode); BookNode.appendChild(PriceNode); System.out.println("Continue?y/n"); if(br.readLine().equals("n")) { break; } } // Prepare the DOM document for writing Source source = new DOMSource(document); // Prepare the output file File file = new File("books.xml"); Result result = new StreamResult(file); // Write the DOM document to the file TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans=transFact.newTransformer(); trans.transform(source, result);
} }
126