CSE II yr JNTU

Embed Size (px)

Citation preview

  • 8/6/2019 CSE II yr JNTU

    1/42

    //Quadratic.java/*Write a java program that prints all real solutions to the Quadraticequation Read in a,b,c and use the Quadratic formula. If the discrminantis b2 - 4ac is negative then display a message stating that there areno real solutions*/

    import java.lang.*;import java.io.*;

    publicclass Quadratic {

    publicstaticvoid main(String args[]) throws IOException { int a, b, c, disc, r1, r2;

    InputStreamReader obj = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(obj);

    System.out.println("Enter a");a = Integer.parseInt(br.readLine());

    System.out.println("Enter b");b = Integer.parseInt(br.readLine());

    System.out.println("Enter c");c = Integer.parseInt(br.readLine());

    disc = (b * b) - (4 * a * c);

    if (disc > 0) {System.out.println("Roots are real and unequal");

    r1 = ((-b) + (b * b - 4 * a * c)) / (2 * a);r2 = ((-b) - (b * b - 4 * a * c)) / (2 * a);

    System.out.println("Roots are as Follows");System.out.println(" r1 = " + r1);System.out.println(" r2 = " + r2);

    }

    elseif (disc == 0) {System.out.println("Roots are Real and Equal");r1 = r2 = (-b) / (2 * a);System.out.println(" r1 = " + r1);System.out.println(" r2 = " + r2);

    }

    else {

    System.out.println("Roots are imaginary");}

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    2/42

    OUTPUTEnter a2Enter b4Enter c2Roots are Real and Equalr1 = -1r2 = -1

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    3/42

    //Fibonacci.java/*Write a java program that uses non recursive function to printthe nth value in the Fibonnacci Sequence*/

    publicclass Fibonacci{ int a = 0, b = 1, c = 1, i = 0;

    publicvoid fibonacci(int n){

    System.out.println("Fibonacci serries as follows");System.out.println("" + a);System.out.println("" + b);

    while (i

  • 8/6/2019 CSE II yr JNTU

    4/42

    //FibonacciRec.java/*Write a java program that uses recursive function to printthe nth value in the Fibonnacci Sequence*/

    import java.io.*;publicclass FibonacciRec {

    publicint fibonacci( int n ){

    if( n == 1 || n == 2 ) return n;

    elsereturn fibonacci( n - 1 ) + fibonacci( n - 2 );

    }

    }

    //FibonacciRecTest.java

    import java.io.*;

    publicclass FibonacciRecTest{ publicstaticvoid main(String args[]) throws IOException

    {InputStreamReader obj = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(obj);

    System.out.println("Enter last integer"); int n = Integer.parseInt(br.readLine());

    FibonacciRec fibrec = new FibonacciRec();System.out.println("Fibonacci series using recursion");

    for (int i = 1; i

  • 8/6/2019 CSE II yr JNTU

    5/42

    //Prime.java/*Write a program that prompts the user for an integer and then printsout all the prime numbers up to that integer*/

    import java.io.*;publicclass Prime{ boolean isPrime = false;

    publicvoid prime(int n){

    System.out.println("prime Numbers are as follows"); for (int i = 2; i

  • 8/6/2019 CSE II yr JNTU

    6/42

    //MatrixMul.java/*Write a Java Program to multiply two given matrices*/

    import java.io.*;import java.util.Scanner;

    publicclass MatrixMul{ publicstaticvoid main(String args[])

    {Scanner s = new Scanner(System.in);

    System.out.println("Enter rows and columns of first matrix");

    int m = s.nextInt(); int n = s.nextInt();

    System.out.println("Enter the col and rows of second matrix"); int p = s.nextInt(); int q = s.nextInt();

    int a[][] = newint[m][n]; int b[][] = newint[p][q]; int c[][] = newint[m][q];

    if (n == p){

    System.out.println("Matrix Multiplication is possible");

    System.out.println("Enter the values of matrix1"); for (int i = 0; i < m; i++)

    for (int j = 0; j < n; j++) {a[i][j] = s.nextInt();

    }

    System.out.println("Enter the values of second matrix"); for (int i = 0; i < p; i++)

    for (int j = 0; j < q; j++){

    b[i][j] = s.nextInt();}

    for (int i = 0; i < p; i++){

    for (int j = 0; j < q; j++){

    int sum = 0;

    for (int k = 0; k < n; k++){

    sum += a[i][k] * b[k][j];}c[i][j] = sum;

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    7/42

    System.out.println("Product is"); for (int i = 0; i < m; i++)

    {System.out.println("");

    for (int j = 0; j < q; j++){

    System.out.print("" + c[i][j]);}

    }}

    elseSystem.out.println("Matrix Multiplication is not possible");

    }}

    OUTPUTEnter rows and columns of first matrix

    2 2Enter the col and rows of second matrix2 2Matrix Multiplication is possibleEnter the values of matrix11 0 0 1Enter the values of second matrix1 2 3 4Product is1 23 4

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    8/42

    //SumOfInt.java//Program for sum of all integers using string tokenizer

    import java.io.*;import java.util.*;publicclass SumOfInt { publicstaticvoid main(String args[]) throws IOException

    {InputStreamReader obj = new InputStreamReader(System.in);BufferedReader br = new BufferedReader( obj );System.out.println("Enter integers");String input = br.readLine();StringTokenizer tokens = new StringTokenizer(input);

    int sum = 0;

    while(tokens.hasMoreTokens()){

    String value = tokens.nextToken(); int value1 = Integer.parseInt(value);

    sum += value1;

    }System.out.println("Sum of integers is: "+ sum);

    }

    }

    OUTPUTEnter integers1 2 3 4 5 6Sum of integers is: 21

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    9/42

    //Palimdrome.java/*Write a java Program that checks whether the string is palindrome ornot*/

    import java.util.*;publicclass Palindrome{ publicstaticvoid main(String args[])

    {String s1 = new String();String s2 = new String();System.out.println("Enter a string");

    Scanner sc = new Scanner( System.in);s1 = sc.nextLine();StringBuffer sb = new StringBuffer( s1 );

    //String reverse function for reversing the string

    s2 = sb.reverse().toString(); if( s1.equals( s2 ))

    System.out.println("" + s1 + " is a palindrome"); else

    System.out.println("" + s2 + " is not a palindrome");}

    }

    OUTPUTEnter a string madammadam is a palindrome

    Enter a string javaavaj is not a palindrome

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    10/42

    //Sort.java/*Write a java Program for sorting a given list of names in ascendingorder*/

    import java.util.*;

    publicclass Sort{ publicstaticvoid main(String args[])

    {Scanner sc = new Scanner(System.in);

    int i, j;

    System.out.println("Enter the number of strings to be sorted"); int n = sc.nextInt();

    String a[] = new String[n + 1];

    System.out.println("enter the names"); for (i = 0; i

  • 8/6/2019 CSE II yr JNTU

    11/42

    //ReadTxt.java/*Write a Program to make a frequency count of words in a given text*/

    import java.util.*;publicclass ReadTxt { publicstaticvoid main(String args[])

    {String s1 = new String();System.out.println("Enter a line of text:-");Scanner sc = new Scanner(System.in);s1 = sc.nextLine();

    int sum = 0;StringTokenizer st = new StringTokenizer( s1 );

    while(st.hasMoreTokens()){

    String value = st.nextToken();System.out.println(value);

    sum++;}System.out.println("Frequency counts of words is" + sum);

    }

    }

    OUTPUTEnter a line of text:- This is a line with 7 tokensThisisalinewith7tokensFrequency counts of words is7

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    12/42

    //FileInfo.java/* Write a java program that reads a file name from the user, thendisplays information about whether the files exists, is readable, isWritable, the type of file and the length of the file in bytes*/

    import java.io.*;import javax.swing.*;

    publicclass FileInfo{ publicstaticvoid main(String args[])throws IOException

    {InputStreamReader obj = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(obj);

    System.out.println("Enter File Name:");String fileName = br.readLine();File f = new File( fileName );

    if (f.isFile())

    {System.out.println(f + (f.isFile() ? " is " : "isNot")

    + "aFile");

    System.out.println(f + (f.exists() ? " does " : "doesNot")+ "exists");

    System.out.println(f + (f.canRead() ? " can " : "cannot")+ "read");

    System.out.println(f + (f.canWrite() ? " can ": "canno")+ "write");

    }else

    System.out.println(f + "is not a File");

    }}

    OUTPUTEnter File Name: C:\\cse\\FibDemo.java

    C:\cse\FibDemo.java is aFileC:\cse\FibDemo.java does existsC:\cse\FibDemo.java can readC:\cse\FibDemo.java can write

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    13/42

  • 8/6/2019 CSE II yr JNTU

    14/42

    //DisplayFile.java/*Write a java program that displays the number of characters, lines andwords in a text file*/

    import java.io.*;import java.util.*;

    publicclass DisplayFile {

    publicstaticvoid main(String args[]) throws IOException {String s1 = "";String s2 = "";

    int c = 0, i = 0, j = 0, sum = 0; try {

    String fileName = "C:\\cse\\FibonacciRec.java";FileReader f1 = new FileReader(fileName);FileReader f2 = new FileReader(fileName);BufferedReader br1 = new BufferedReader(f1);BufferedReader br2 = new BufferedReader(f2);

    while ((s1 = br1.readLine()) != null) {i++;

    }

    while (s2 != null) {

    s2 = br2.readLine();j = s2.length();sum += j;

    StringTokenizer st = new StringTokenizer(s2);

    while (st.hasMoreTokens()) {

    st.nextToken();c++;

    }

    }} catch (Exception e){ }

    System.out.println("total number of lines " + i);System.out.println("Total number of words " + c);System.out.println("Total number of characters " + sum);

    }}

    OUTPUTtotal number of lines 17Total number of words 57Total number of characters 331

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    15/42

    // WelcomeApplet.java// Develop an applet that displays a simple message.

    import java.awt.*;import javax.swing.*;publicclass WelcomeApplet extends JApplet { publicvoid paint(Graphics g)

    {g.drawString("Welcome..This string is displayed at the position

    x= 25,y =25",25,25);}

    }

    OUTPUT

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    16/42

    //Factorial.java//Develop an applet that receives an integer in one text field,//and computes its factorial Value and returns it in another text//field, when the button named Compute is clicked.

    import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;publicclass Factorial extends JApplet implements ActionListener {

    JLabel numLabel;JTextField numField;

    JLabel factLabel;JTextField factField;

    JButton compute;

    int fact ;

    publicvoid init(){

    fact = 1;Container c = getContentPane();c.setLayout(new GridLayout(3,2,3,3));

    numLabel = new JLabel("num");numField = new JTextField( 10 );c.add(numLabel);c.add(numField);

    factLabel = new JLabel("FactorialVal");factField = new JTextField( 10 );c.add(factLabel);c.add(factField);

    compute = new JButton("Compute");c.add(compute);compute.addActionListener(this);

    setSize(100,100);

    //setVisible(true);}

    publicvoid actionPerformed(ActionEvent e){

    String a = numField.getText();

    int a1 = Integer.parseInt(a);System.out.println(a1);

    int facto = factorial( a1);

    String fact = String.valueOf(facto);factField.setText(fact);

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    17/42

    publicint factorial( int n){

    if( n

  • 8/6/2019 CSE II yr JNTU

    18/42

    //MouseTracker.java//Write a Java program for handling mouse events.

    import java.awt.*;import java.awt.event.*;import javax.swing.*;

    publicclass MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel outputLabel;

    public MouseTracker(){

    super( "Demonstrating Mouse Events" );

    outputLabel = new JLabel();Container c = getContentPane();c.add(outputLabel);

    // application listens to its own mouse events

    addMouseListener( this );addMouseMotionListener( this );

    setSize( 275, 100 );setVisible(true);

    }

    // MouseListener event handler publicvoid mouseClicked( MouseEvent e )

    {int x = e.getX();

    int y = e.getY();outputLabel.setText( "Mouse Clicked at x =" + x + " y = " + y );

    }

    // MouseListener event handler publicvoid mousePressed( MouseEvent e )

    { int x = e.getX(); int y = e.getY();

    outputLabel.setText( "Mouse Pressed at x =" + x + " y = " + y );}

    // MouseListener event handler publicvoid mouseReleased( MouseEvent e )

    {

    int x = e.getX(); int y = e.getY();

    outputLabel.setText( "Mouse Released at x =" + x + " y = " + y );}

    // MouseListener event handler publicvoid mouseEntered( MouseEvent e )

    {outputLabel.setText( "Mouse in window" );

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    19/42

    // MouseListener event handler publicvoid mouseExited( MouseEvent e )

    {outputLabel.setText( "Mouse outside window" );

    }

    // MouseMotionListener event handler publicvoid mouseDragged( MouseEvent e )

    { int x = e.getX(); int y = e.getY();

    outputLabel.setText( "Mouse Dragged at x =" + x + " y = " + y );}

    // MouseMotionListener event handler publicvoid mouseMoved( MouseEvent e )

    { int x = e.getX(); int y = e.getY();

    outputLabel.setText( "Mouse Moved at x =" + x + " y = " + y );

    }

    publicstaticvoid main( String args[] ){

    MouseTracker app = new MouseTracker();app.addWindowListener(

    new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {System.exit( 0 );

    }}

    );

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    20/42

    //Multi.java//Write a Java program that creates three threads.//First thread displays Good Morning every one second,//the second thread displays Hello every two seconds and//the third thread displays Welcome every three seconds.

    publicclass Multi extends Thread {

    staticint thread1, thread2, thread3;

    publicvoid run(){

    while (true){

    String name = Thread.currentThread().getName(); //Thread-1 prints GoodMorning every 1000ms

    if (name.equals("Thread-1")){

    thread1++;System.out.println(name + "-->Good Morning");

    try{

    Thread.sleep(1000);} catch (Exception e){

    System.out.println("Interrupted");}

    }

    //Thread-2 prints "Hello" every 2000msif (name.equals("Thread-2")){

    thread2++;System.out.println(name + "-->Hello");

    try{

    Thread.sleep(2000);}catch (Exception e){

    System.out.println("Interrupted");}

    }

    //Thread-3 displays "Welcome" every 3000msif (name.equals("Thread-3")){

    thread3++;System.out.println(name + "-->Welcome");

    try{

    Thread.sleep(3000);}catch (Exception e){System.out.println("Interrupted");

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    21/42

    }}

    }}

    publicclass MultiTest{

    publicstaticvoid main(String args[]) {Multi t0 = new Multi();Multi t1 = new Multi();Multi t2 = new Multi();

    t0.setName("Thread-1");t1.setName("Thread-2");t2.setName("Thread-3");

    t0.start();t1.start();t2.start();

    // main thread will sleep for 5000ms try

    {Thread.currentThread().sleep(5000);

    System.out.println("Number of times Thread-1, Thread-2,Thread-3 has been executed in 5000 milliseconds i.e 5sec");

    System.out.println(" Thread-1 = " + thread1 +

    " Thread-2 = " + thread2 +" Thread-3 = " + thread3);

    System.exit(0);

    }catch (InterruptedException e){

    System.out.println("Interrupted");}

    }}

    OUTPUTThread-1-->Good MorningThread-3-->WelcomeThread-2-->HelloThread-1-->Good MorningThread-2-->HelloThread-1-->Good Morning

    Thread-3-->WelcomeThread-1-->Good MorningThread-2-->HelloThread-1-->Good MorningNumber of times Thread-0, Thread-1, Thread-2 has been executed in 5000msi.e 5secThread-1 = 5 Thread-2 = 3 Thread-3 = 2

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    22/42

    // Producer.java// Definition of threaded class Producer

    publicclass Producer extends Thread {

    public SharedAccess pHold;

    public Producer(SharedAccess h) { super("ProduceInteger");

    pHold = h;}

    publicvoid run() { for (int count = 1; count

  • 8/6/2019 CSE II yr JNTU

    23/42

    // SharedAccess.java// Definition of class SharedAccess that// uses thread synchronization to ensure that both// threads access sharedInt at the proper times.

    publicclass SharedAccess {

    privateint sharedInt = -1; privateboolean producerTurn = true; // condition variable

    publicsynchronizedvoid setSharedInt(int val){

    while (!producerTurn) { // not the producer's turn

    try{

    System.out.println("Producer is waiting");

    System.out.println("Consumer is consuming thevalue produced by

    producer");wait();

    }catch (InterruptedException e){

    System.out.println(Interrupted);}

    }

    sharedInt = val;producerTurn = false;notify(); // tell a waiting thread(consumer) to become ready

    }

    publicsynchronizedint getSharedInt(){

    while (producerTurn) { // not the consumer's turn

    try { System.out.println("Consumer is waiting forproducer

    to produce the value");System.out.println("Producer is Producing");

    wait();

    }catch (InterruptedException e) {

    System.out.println(Interrupted);}

    }

    producerTurn = true;notify(); // tell a waiting thread(producer) to become ready

    return sharedInt;}

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    24/42

    // ProducerConsumerTest.java// Show multiple threads modifying shared object.

    publicclass ProducerConsumerTest { publicstaticvoid main( String args[] )

    {SharedAccess h =new SharedAccess();Producer p = new Producer( h );Consumer c = new Consumer( h );

    p.start();c.start();

    }}

    OUTPUT

    Producer:1

    Producer is waitingConsumer is consuming the value produced by producerConsumer:1

    Consumer is waiting for producer to produce the valueProducer is ProducingProducer:2Producer is waitingConsumer is consuming the value produced by producerConsumer:2

    Consumer is waiting for producer to produce the valueProducer is ProducingProducer3Producer is waitingConsumer is consuming the value produced by producerConsumer:3

    Consumer is waiting for producer to produce the valueProducer is ProducingProducer4Producer is waitingConsumer is consuming the value produced by producerConsumer:4

    Consumer is waiting for producer to produce the valueProducer is Producing

    Producer:5Producer is waitingConsumer is consuming the value produced by producerConsumer:5

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    25/42

    //Addition.java//Write a program that creates a user interface to perform addition.//The user enters two numbers in the textfields, Num1 and Num2.//The addition of Num1 and Num2 is displayed in the Result field//when the Additon button is clicked.

    import javax.swing.*;import java.awt.*;import java.awt.event.*;

    publicclass Addition extends JFrame implements ActionListener { private JLabel numLabel; private JLabel num2Label; private JLabel resultLabel; private JButton addBtn;

    private JTextField num1Field; private JTextField num2Field;

    private JTextField resultField;

    public Addition(){ super("Addition");

    Container c = getContentPane();c.setLayout( new FlowLayout());

    numLabel = new JLabel("Num1");c.add(numLabel);num1Field = new JTextField(10);c.add(num1Field);

    num2Label = new JLabel("Num2");c.add(num2Label);num2Field = new JTextField(10);c.add(num2Field);

    resultLabel = new JLabel("Result");c.add(resultLabel);resultField = new JTextField(10);c.add(resultField);

    addBtn = new JButton("Addition");

    addBtn.addActionListener(this);c.add(addBtn);

    setSize(100,100);setVisible(true);

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    26/42

    publicvoid actionPerformed(ActionEvent e){

    String a = num1Field.getText(); int a1 = Integer.parseInt(a);

    String b = num2Field.getText(); int b1 = Integer.parseInt(b);

    int result = a1 + b1;String result1 = String.valueOf(result);resultField.setText(result1);

    }

    publicstaticvoid main(String args[]){

    Addition add = new Addition(); add.addWindowListener( new WindowAdapter() {

    publicvoid windowClosing( WindowEvent e ){

    System.exit( 0 );}

    });

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    27/42

    //SignalLight.java//Write a java program that simulates a traffic light.//The program lets the user select one of three lights: red,yellow,or //green.When a radio button is selected, the light is turned

    on, and //only one light can be on at a time No light is on when theprogram //starts.

    import javax.swing.*;import java.awt.*;import java.awt.event.*;

    publicclass SignalLight extends JFrame implements ItemListener {

    private JRadioButton redLightBtn; private JRadioButton greenLightBtn; private JRadioButton yellowLightBtn;

    JTextArea out;ButtonGroup signal;

    public SignalLight() {

    Container c = getContentPane();c.setLayout(new FlowLayout());

    redLightBtn = new JRadioButton("redLight");redLightBtn.addItemListener(this);c.add(redLightBtn);

    greenLightBtn = new JRadioButton("greenLight");greenLightBtn.addItemListener(this);c.add(greenLightBtn);

    yellowLightBtn = new JRadioButton("YellowLight");yellowLightBtn.addItemListener(this);c.add(yellowLightBtn);

    signal = new ButtonGroup();signal.add(redLightBtn);signal.add(greenLightBtn);signal.add(yellowLightBtn);

    setSize(250, 250);setVisible(true);

    }

    publicvoid itemStateChanged(ItemEvent e) {Graphics g = getGraphics();

    if (e.getSource() == redLightBtn) {g.setColor(Color.RED);g.fillOval(100, 100, 40, 40);

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    28/42

    if (e.getSource() == greenLightBtn) {g.setColor(Color.GREEN);g.fillOval(100, 100, 40, 40);

    }

    if (e.getSource() == yellowLightBtn) {g.setColor(Color.YELLOW);g.fillOval(100, 100, 40, 40);

    }

    }

    publicstaticvoid main(String args[]) {SignalLight app = new SignalLight();

    app.addWindowListener( new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {System.exit( 0 );

    }

    });

    }}

    OUTPUT

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    29/42

    //LineOvalRect.java// Write a Java program that allows the user to draw lines,// rectangles and ovals.

    import java.awt.*;import javax.swing.*;

    publicclass LineOvalRect extends JApplet{

    publicvoid paint(Graphics g){

    g.setColor(Color.BLUE);g.drawLine(50,10,150,10);g.drawRect(50, 50, 100, 50);g.drawOval(50, 150, 100, 50);

    }}

    OUTPUT

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    30/42

    //Shape.java//Write a java program to create an abstract class named Shape//that contains an empty method named numberOfSides ( ).//Provide three classes named Triangle,Pentagon and Hexagon

    //such that each one of the classes extends the class Shape.//Each one of the classes contains only the method numberOfSides( )//that shows the number of sides in the given geometrical figures.

    publicabstractclass Shape { publicabstractvoid noOfSides();

    }

    //Triangle.java

    publicclass Triangle extends Shape{ publicvoid noOfSides()

    {System.out.println("Triangle has 3 sides");

    }}

    //Pentagon.java

    publicclass Pentagon extends Shape{publicvoid noOfSides(){

    System.out.println("Pentagon has 5 sides");}}

    //Hexagon.java

    publicclass Hexagon extends Shape { publicvoid noOfSides()

    {System.out.println("Hexagon has 6 sides");

    }}

    //ShapeTest.java

    publicclass ShapeTest {

    publicstaticvoid main(String args[]) {Shape s;

    Triangle t = new Triangle();t.noOfSides();s = t;s.noOfSides();

    Pentagon p = new Pentagon();p.noOfSides();

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    31/42

    s = p;s.noOfSides();

    Hexagon h = new Hexagon();h.noOfSides();s = h;s.noOfSides();

    }}

    OUTPUT

    Triangle has 3 sidesTriangle has 3 sidesPentagon has 5 sidesPentagon has 5 sidesHexagon has 6 sidesHexagon has 6 sides

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    32/42

    //LoginTable.java

    //Write a program to create login table using JTable

    import javax.swing.*;import java.awt.*;publicclass LoginTable extends JApplet {

    publicvoid init() {

    // Get content paneContainer c = getContentPane();

    // Set layout managerc.setLayout(new BorderLayout());

    // Initialize column headingsfinal String[] colHeads = { "UserName", "Passsword" };

    // Initialize login with username and passwordfinal String Login[][] = { { "Sana" , "1234" },

    { "Adam" , "qwer"},{ "Sachin", "asdf" }

    };

    // Create the tableJTable table = new JTable(Login, colHeads);

    JScrollPane scroller = new JScrollPane(table);

    // Add scroll pane to the content panec.add(scroller);

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    33/42

    //ComboBoxTest.java//create a comboBox and listen to its event

    import java.awt.*;import java.awt.event.*;import javax.swing.*;publicclass ComboBoxTest extends JFrame implements ItemListener { public String courses[] = {"CSE","ECE","EEE"}; public JComboBox courseComBox;

    public ComboBoxTest(){//get ContentPane and set its layout

    Container c =getContentPane();c.setLayout(new FlowLayout());

    // set up JComboBox and register its event handlercourseComBox = new JComboBox(courses);

    courseComBox.addItemListener(this);

    //add the comboBox to containerc.add(courseComBox);setSize(100,100);setVisible(true);

    }

    //handle JComboBox eventpublicvoid itemStateChanged(ItemEvent e){

    int index = courseComBox.getSelectedIndex();String selected = courses[index];JOptionPane.showMessageDialog(this,"u have selected "+selected);

    } publicstaticvoid main(String args[])

    {ComboBoxTest app = new ComboBoxTest();

    app.addWindowListener( new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {System.exit( 0 );

    }}

    );

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    34/42

    //CheckBoxTest.java//Create a CheckBox and listen to its event.

    import javax.swing.*;import java.awt.*;import java.awt.event.*;

    publicclass CheckBoxTest extends JFrame implements ItemListener {

    public JCheckBox accept; public JTextArea output;

    public CheckBoxTest() {

    super("CheckBoxTest");

    //get the container and set its layoutContainer c = getContentPane();c.setLayout(new FlowLayout());

    //Initialise the checkbox and register it with the ItemListeneraccept = new JCheckBox("I accept the terms and agreement");accept.addItemListener(this);c.add(accept);

    output = new JTextArea();output.setEditable(false);c.add(output);

    setSize(300, 200);

    setVisible(true);}

    //handle JCheckBox events publicvoid itemStateChanged(ItemEvent e) { if (e.getSource() == accept)

    { if (e.getStateChange() == ItemEvent.SELECTED)

    output.setText("\nYou have SELECTED I accept the terms and agreement");

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    35/42

    elseif (e.getStateChange() == ItemEvent.DESELECTED)

    output.setText("\nYou have DESELECTED I accept the terms andagreement");

    }

    }

    publicstaticvoid main(String args[]) {CheckBoxTest app = new CheckBoxTest();

    app.addWindowListener( new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {System.exit( 0 );

    }}

    );}

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    36/42

    //ListTest.java//Create a JList and Listen to its event

    import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;

    publicclass ListTest extends JFrame implements ListSelectionListener { private JList cityList;JTextArea output;

    private String metroCities[] =

    { "Hyderabad","Bangalore","Chennai","Mumrbai","Pune","Delhi" };

    public ListTest(){

    super( "List Test" );

    Container c = getContentPane();c.setLayout( new FlowLayout() );

    // create a list with the items in the metroCities array

    cityList = new JList( metroCities );cityList.setVisibleRowCount( 3 );

    // do not allow multiple selectionscityList.setSelectionMode(

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    37/42

    ListSelectionModel.SINGLE_SELECTION );

    // add a JScrollPane containing the JList // to the content pane

    c.add( new JScrollPane( cityList ) );

    output = new JTextArea();c.add(output);

    // set up event handler

    cityList.addListSelectionListener(this);setSize( 350, 150 );setVisible(true);

    }

    //handling JList events publicvoid valueChanged( ListSelectionEvent e )

    {

    int index = cityList.getSelectedIndex();String city = metroCities[index];output.setText("You have selected " + city);

    }

    publicstaticvoid main( String args[] ){

    ListTest app = new ListTest();app.addWindowListener(

    new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {System.exit( 0 );

    }}

    );

    }}

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    38/42

    // KeyDemo.java// Demonstrating keystroke events.

    import javax.swing.*;import java.awt.*;import java.awt.event.*;

    publicclass KeyDemo extends JFrame implements KeyListener {

    private JTextArea output;

    public KeyDemo(){

    super( "Demonstrating Keystroke Events" );

    Container c = getContentPane();c.setLayout(new FlowLayout());

    output = new JTextArea( 10, 15 );output.setText( "Press any key on the keyboard..." );output.setEnabled( false );c.add(output);

    // allow frame to process Key eventsaddKeyListener( this );

    setSize( 350, 100 );setVisible(true);

    }

    publicvoid keyPressed( KeyEvent e ){

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    39/42

    String key = e.getKeyText( e.getKeyCode() );

    output.append("\nKey Pressed = " + key );

    boolean actionKey = e.isActionKey(); if(actionKey == true)

    output.append("\n"+ key + " is an action key");}

    publicvoid keyReleased( KeyEvent e ){

    String key = e.getKeyText( e.getKeyCode() );

    output.append("\nKey Released = " + key );

    }

    publicvoid keyTyped( KeyEvent e ){

    char key = e.getKeyChar();

    output.append("\nCharacter Key typed is = " + key );

    }

    publicstaticvoid main( String args[] ){

    KeyDemo app = new KeyDemo();

    app.addWindowListener( new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {

    System.exit( 0 );}}

    );}

    }

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    40/42

    Adapter classes: Window adapter, mouse adapter, mouse motion adapter, key

    adapter classes, anonymous inner class//listening to key strokesimport javax.swing.*;import java.awt.event.*;import java.awt.*;

    publicclass KeyAdapterDemo extends JFrame {

    JTextArea output;JLabel statusBar;

    public KeyAdapterDemo() { super("A simple paint program");

    Container c = getContentPane();c.setLayout(new FlowLayout());

    output = new JTextArea(150, 10);output.setText("press any key on the kryboard") ;

    output.setEnabled(false);c.add(output);

    addKeyListener( new KeyAdapter() {

    publicvoid keyTyped(KeyEvent e) { char key = e.getKeyChar();

    output.append("\nCharacter key typed is = " + key);

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    41/42

    }});

    setSize(300, 150);setVisible(true);

    }

    publicstaticvoid main(String args[]) {KeyAdapterDemo app = new KeyAdapterDemo();

    app.addWindowListener( new WindowAdapter() { publicvoid windowClosing(WindowEvent e) {

    System.exit(0);}

    });}

    }

    //MouseAdapterDemo.javaimport javax.swing.*;import java.awt.event.*;import java.awt.*;

    publicclass MouseAdaptersDemo extends JFrame { public JLabel outputLabel;

    public MouseAdaptersDemo(){

    super( "Mouse Events" );

    Container c = getContentPane();c.setLayout(new FlowLayout());

    outputLabel = new JLabel();c.add(outputLabel);

    addMouseListener(

    new MouseAdapter() { publicvoid mouseClicked( MouseEvent e )

    { int x = e.getX(); int y = e.getY();

    outputLabel.setText("Mouse Clicked at x = " + x + " y = "+ y );

    }}

    );

    Dr.VRK Womens College Of Engg & Technology, Aziz Nagar, RR Dist.

  • 8/6/2019 CSE II yr JNTU

    42/42

    addMouseMotionListener( new MouseMotionAdapter() { publicvoid mouseDragged( MouseEvent e )

    { int x = e.getX(); int y = e.getY();

    outputLabel.setText("Mouse Dragged at x = " + x + " y = "+ y );

    }}

    );

    setSize( 300, 150 );setVisible(true);

    }

    publicstaticvoid main( String args[] ){

    MouseAdaptersDemo app= new MouseAdaptersDemo();

    app.addWindowListener( new WindowAdapter() { publicvoid windowClosing( WindowEvent e )

    {System.exit( 0 );

    }}

    );}

    }