Monday, 19 August 2013

Event Handling in java

Event: The act of changing the state of one object to another is called event.The java.awt.event package provides some action  or key events like clicking the button,press the key etc.Events are supported by a number of Java packages, like java.util, java.awt and java.awt.event.Some event classes that provide some action or key press events that are:

  • Action Event:-Action listener generated when any button is pressed.It performs a particular action.The syntax for action listener is:
private void jButtonActionPerformed(java.awt.event.ActionEvent evt)
 {  
//Code on which action is to be performed
 }
  • Mouse Event:-Mouse listener generated when mouse is dragged,moved or released.The syntax for using a mouse listener is:
private void jTextFieldMouseClicked(java.awt.event.MouseEvent evt) {
        //code on which mouse event is to be performed
    }

  • Key Event:-Key listener generated when key is pressed from keyboard.The syntax for using key listener event is:
private void jTextFieldKeyTyped(java.awt.event.KeyEvent evt)
 {                                     
  //Code on which key event is to be performed
  }


  • Focus Event:-Focus listener generated when the cursor gains or looses the focus.The syntax for using focus event listener is
private void jTextFieldFocusLost(java.awt.event.FocusEvent evt) 
{
//Code on which focus event listener is to be performed.
 }
  • Mouse Motion Event:-Mouse wheel listener is generated when mouse  is moved.The syntax for this event is:
private void jTextFieldMouseMoved(java.awt.event.MouseEvent evt)
 {
  // code on which action is to be performed
    }

To apply any of the above event on your code,you just need to right click on the control where you want to perform the action then go to event and select which event listener you want to select,these events can be performed on Text fields,Radio buttons,Password fields,lists,combo box etc.

{ Read More }


Sunday, 18 August 2013

How Can we Use JFrames In Netbeans

IDE,till now we have worked on the simple Text Editor,but now we need to use a Development Environment to add more functionality to our code.Here are the steps need to follow while installing and running a Netbeans IDE.

1.First of all we need to install an IDE(Integrated Development Environment),right now we are using Netbeans IDE version 7.2.1.
2.After IDE is installed,click on File>New Project.

New project

3.Now the New Project window will open,in Projects click on Java Application,then click Next.

java application

4.Now New Java Application window will open,give a name to your Project as required,click Next.
5.You are ready to use IDE for writing Java Codes.
6.Now as we want to build frames using IDE,so right click on the Package you created,and now Open New>JFrame Form.

Jframe

7.Give the name you want to give to your Frame form,click Next.
8.Now,your form design window is ready to use,now you can drag and drop your Controls on your Window.
9.You can change the variable name,the control name you selected ,double click on the Control you had selected,and write the code.It is the example of how you can drag and drop controls in design window.

10.If you want to apply action listener on their control then you need to double click on the control.Then it move on source window and write the following code if you apply action listener on buttons and perform calculations.





WAP to add action listeners in calculator

 private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {   
                               
if(evt .getSource()==btn1)
{int num1,num2,res;
num1=Integer.parseInt(txt1.getText());
   num2=Integer.parseInt(txt2.getText()) ;
   res=num1+num2;
   txt3.setText(Integer.toString(res));

  
}
    }                                   

    private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {
                                   
if(evt.getSource()==btn2)
{
    txt1.setText("");
    txt2.setText("");
    txt3.setText("");
    txt1.requestFocus();
}
    }                                   

    private void btn3ActionPerformed(java.awt.event.ActionEvent evt) { 
                                 
        if(evt .getSource()==btn3)
{int num1,num2,res;
num1=Integer.parseInt(txt1.getText());
   num2=Integer.parseInt(txt2.getText()) ;
   res=num1*num2;
   txt3.setText(Integer.toString(res));
    }                                   
}
    private void btn4ActionPerformed(java.awt.event.ActionEvent evt) {   
                               
if(evt .getSource()==btn4)
{int num1,num2,res;
num1=Integer.parseInt(txt1.getText());
   num2=Integer.parseInt(txt2.getText()) ;
   res=num1/num2;
   txt3.setText(Integer.toString(res));       
    }                                   
    }
    private void btn5ActionPerformed(java.awt.event.ActionEvent evt) { 
                                 
if(evt .getSource()==btn5)
{int num1,num2,res;
num1=Integer.parseInt(txt1.getText());
   num2=Integer.parseInt(txt2.getText()) ;
   res=num1-num2;
   txt3.setText(Integer.toString(res));       
    }                                   
    }

Output of this program:

Calculator

{ Read More }


Saturday, 17 August 2013

Simple Applet In Java

An applet is a Java program that runs in a Web browser.An applet is a java class that extends with java.applet.Applet class.A main() method is not invoked on an applet.In Applets the place of the main method init method is used because the main method is used as an entry point for applications, the init method is used as an entry point for applets.Two packages are importing to implement the applet these are:


  • import java.awt.*  :- AWT stands for abstract window toolkit.It is used for creating user interfaces and for painting graphics and images. 
  • import java.applet.*:-   It Provides the necessary classes to create an applet.


WAP to implement simple applet

import java.awt.*;                      //creating user interfaces and for painting graphics and images.
import java.applet.*;                  //Provides the necessary classes to create an applet.
public class app extends Applet{   //Extending Applet class from applet package.
String msg;
public void init()                         //To initialize the applet
{
msg="This is my first applet";
}

//When the paint method is call AWT package uses a "callback" mechanism for painting.

public void paint(Graphics g)     
{
g.drawString(msg,10,20);          //It Returns the specified text at specified location.
}
}

Now save this program with name app.java and then compile it.Make sure that your program is error free.



Now open new notepad file and write the following code:

<html>
<body>
<applet code="app.class",width="200",height="200">
</applet>
</body>
</html>

Then save this file with name app.html in same folder where you have saved app.java file.

Output of this program:

Applets

{ Read More }


How Can We Take User Input In Applet

An applet is a Java program that runs in a Web browser.It takes user input at the run time in applet window.Due to this it used some built in functions that is stored in import java.awt.* and import java.applet.*.The functions used are:
1.Integer.parseInt() :-Change the user input to integer because the value we have entered is in integer but it will be interpreted as a String.

2.Repaint():-   when you want to re-draw your GUI because you have changed something inside.

3. Draw String():-It Returns the specified text at specified location.

WAP to implement add of two numbers from user input in applet

import java.awt.*;          //creating user interfaces and for painting graphics and images.
import java.applet.*;       //Provides the necessary classes to create an applet.

public class userInput extends Applet
{
      TextField text1, text2;        //TextField is keyword that creates the test fields
    
      public void init()                //To initialize the applet
      {
           text1 = new TextField(8);   //It specifies the length of text field   
           text2 = new TextField(8);
           add(text1);
           add(text2);
          
      }

      public void paint(Graphics g)
      {
          int x=0,y=0,z=0;
          String s1,s2,s;

// It Returns the specified text at specified location.
 g.drawString("Input a numbers which you want to add ",10,50);   
                                                              
        
try
{         

                 s1 = text1.getText();
                 x = Integer.parseInt(s1);    // Change the user input to integer
                 s2 = text2.getText();
                 y = Integer.parseInt(s2);}

          catch(Exception e){}
            z = x + y;
           s =  String.valueOf(z);      //Returns the string representation of integer value
           g.drawString("The Sum is : ",10,75);
           g.drawString(s,100,75);
    }

    public boolean action(Event event, Object obj)
    {
          repaint();   //when you want to re-draw your GUI
          return true;
    }
}

Now save this program with name userInput.java and then compile it.
Applets






Now open new notepad file and write the following code:

<html>
<body>
<applet code="userInput.class",width="200",height="200">
</applet>
</body>
</html>

Then save this file with name app.html in same folder where you have saved app.java file.

Output of this program:
Applets



{ Read More }


Friday, 16 August 2013

How We Can Read File Using Exceptions Through Scanner Class

Exception handling is powerful feature that is supported by java.A method catches an exception using a combination of the try and catch keywords.In the given program we used utility package for using scanner class and IO package using various exceptions.A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:


WAP to display the content of file using exceptions through scanner class

import java.util.*;                                 //Using scanner class
import java.io.*;                                  //Using Exceptions
public class msexcep{
public static void main(String args[])
{
File file=new File("D:/data.txt");         //Specify path that you have create text file
try{
Scanner scanner = new Scanner(file);

while(scanner.hasNextLine()){          //hasNext line function used to read text in file
String line=scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
catch(FileNotFoundException n){     //If file not found then this exception executed
n.printStackTrace();

}
catch (NumberFormatException n)     //It shows the content of the file
System.out.println("The file contains non numeric data."); 

}
}
}

Output of this program:


Exception handling

{ Read More }


multiThrading in Java

Java defines two ways To implement threads:


  • You can implement the Runnable interface.
  • You can extend the Thread class.
As we know if we use thread class then we can't extends any other class so inheritance is not allowed but on the flip side if we use Runnable interface then we extends any other class and use the feature of inheritance.So according to me Runnable interface is more used than Thread class.

1.Using Runnable interface

Here is the program:


class first implements Runnable{
public void run(){
for(int i=1;i<=10;i++)
{
System.out.println("value of i is"+i);
}
}
}
class second implements Runnable
{
public void run()
{
for(int j=1;j<=10;j++)
{

System.out.println("value of j is"+j);
}
}
}
class runables
{
public static void main(String args[])
{
first ms=new first();
Thread thread1=new Thread(ms);
thread1.start();

second obj2=new second();
Thread thread2=new Thread(obj2);
thread2.start();
    
}
}

Output of this program:

Multithreading

{ Read More }


Wednesday, 14 August 2013

Basic String Handling Function

String is a collection of stream of characters.Following are some most basic string functions:

1. CharAt(): To extract a single character from a string.This method checks the value of the given position.

2. indexOf(): It checks the position of the given value.

3. lastIndexOf: It checks the last position of the given value.

4. endsWith:This function gives result in Boolean expression. If the given value  matches at the end of the stored string then the result is true otherwise false.

5. startWith:This function gives result in Boolean expression. If the given value is matches at the start  of the stored string then the result is true otherwise false.

6. equals: This function gives result in Boolean expression.If the two string are equals on the basis of characters then the result is true otherwise false.It also considered the upper and lower case of the characters.

7. equalsIgnoreCase: This function gives result in Boolean expression.If the two string are equals on the basis of characters and it also ignore upper and lower case of the characters then the result is true otherwise false.







WAP to implement simple string methods.

class methods{
public static void main(String args[])
{
String s="maninder ";
String s1="Maninder ";

System.out.println(s.charAt(4)+"\n");

System.out.println(s.indexOf("i")+"\n");

System.out.println(s.lastIndexOf("n")+"\n");

System.out.println(s.endsWith("d")+"\n");

System.out.println(s.startsWith("m")+"\n");

System.out.println(s.equals(s1)+"\n");

System.out.println(s.equalsIgnoreCase(s1)+"\n");


}
}

Output of the program:



String handling
{ Read More }


Exception Handling In Java

An exception is an unwanted condition that arises during the execution of a program.An exception can occur for many different reasons.Some reasons are:

  • When the user has entered invalid data.
  • When a file that needs to be opened cannot be found.
Exception handling



All exception classes are sub types of the java.lang.Exception class. The exception class is a subclass of the Throwable class. During the program execution if any error occurs and you want to print your own message then you write the part of the program which generate the error in thetry{} block and catch the errors using catch() block.The syntax is:

try
{

}
catch(ExceptionName obj)
{
   
}

There are three types of exceptions in Java. These are -:

1. Compile time Exceptions.
2. Logical Exceptions.
3. Runtime exception.

Two types of exception functions used in java:

Java Built in exceptions: Java built functions are those function that are in java.lang class.For ex:

ArithmeticException: Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException: Array index is out-of-bounds.

User defined exceptions:It can be achieved by inheriting the root exception class.
{ Read More }


Tuesday, 13 August 2013

How to change String Upper And Lower case

Converting your Java strings of text to upper or lower case. Just use the inbuilt methods toUpperCase and toLowerCase.

WAP to change string upper and lower case.

class cases{
public static void main(String args[])
{
String s=" maninder";
System.out.println(s.toUpperCase());
String s1=" MANINDER";
System.out.println(s1.toLowerCase());

}
}

Output of the program:


String functions


{ Read More }


IconIconIconFollow Me on Pinterest

Blogger news

Blogroll

What's Hot