Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, November 26, 2013

Sending Email using JavaMail API

In this post i am going to provide source code for sending email from our java application. There can be many cases when you may need to send email from your application. JavaMail API is used for sending email from java application.

Below code demonstrate how to send email from your Gmail account using JavaMail API. You can edit the source code for sending email from your desired email provider, for doing this you will need to provide smtp host and smtp port for your email provider. Replace the smtphost and smtpPort in the program.

Note: replace username , pass and to with your account’s username, password and to with the email address you want to send email.

You can Download JavaMail API from this link

/**
* SendMail class Demonstrate using JavaMail API to send email
* The code uses gmail account as sender account, you can use any email provider.
* set smtphost and smtpPort for the desired email provider.
*
* Replace username and pass with your account's username and password.
* Replace toAddress with the email address to whom you want to send email.
*/

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

class SendMail
{
String smtphost = "smtp.gmail.com";
String smtpPort ="587";

Session session;
MimeMessage message1;

String username = "your_email_id@host.com";
String pass = "your_pwd";
String to ="toAddress";

public static void main(String args[])
{
SendMail sm = new SendMail();
sm.createMessage();
sm.sendMail(to,"thisissubject","thisismessage");
}

public void createMessage()
{
try
{

//smtp properties
Properties prop = new Properties();
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", smtphost);
prop.put("mail.smtp.user", username);
prop.put("mail.smtp.password", pass);
prop.put("mail.smtp.port", smtpPort);
prop.put("mail.smtp.auth", "true");

session = Session.getDefaultInstance(prop);

message1 = new MimeMessage(session);


}
catch(Exception e)
{
System.out.println("Connetction "+e);
}


}

//send mail method
public void sendMail(String receiptentAddress,String Subject,String messageText)
{
//counstructor will be called
String sendto = receiptentAddress;
String msg = messageText;
String sub = Subject;
String frm = username;
String pas = pass;

try
{
message1.setFrom(new InternetAddress(frm));

message1.addRecipient(Message.RecipientType.TO, new InternetAddress (sendto));

message1.setSubject(sub);

message1.setText(msg);

Transport transport = session.getTransport("smtp");

transport.connect(smtphost, frm, pas);
System.out.println("Sending mail..");
transport.sendMessage(message1, message1.getAllRecipients());

transport.close();

System.out.println("Sent!");

}catch(Exception e)
{
System.out.println(e);
}
}
}


Monday, November 25, 2013

How to add controls on AWT Frame

Controls are the basic element of GUI or user interface which allow users to interact with the application. In previous post How to create Frame in AWT we learnt How to create Frame in AWT. In this post we are going to learn how to add common controls on frame.
Some most common controls:
  1. Label
  2. TextField
  3. Button
  4. TextArea
  5. CheckBox
  6. RadioButton
  7. List
  8. Choice

Label:

Label is the simplest control and It is generally used to display unselectable text.
lbe
Declaration Syntax:
Label _label1 = new Label(“Label Text”);


in above syntax we have declared and initialized a label with the text “Label Text”.

Code for adding a label on the frame:

import java.awt.*;
class LabelExample
{
    //declaring frame object
    Frame _frame;
    //declaring label object
    Label label1;
   
    LabelExample()
    {
        _frame = new Frame("Window Title"); // initializing frame
        _frame.setSize(200,200); // The setSize method will set the heigth and width of the frame.
        _frame.setLayout(null); // setting frame's layout to null so that we can add control(s) on the frame at specific location
        
        label1 = new Label("Label 1"); // Intialising Label with the text "Label 1"
        
        // setBounds method is used to set the label position, height and width of the label
        // syntax for setBounds(xPos,yPos,width,height)
        label1.setBounds(50,40,50,20);

        _frame.add(label1); //  add method will add the label on the frame

        _frame.show(); // show() method will display the frame at runtime.
    }

    public static void main(String args[])
    {
        new LabelExample();
    }
}




TextField:


TextField is a very common and basic control which allows users to enter small amount of text in a single line.

txtfld

Syntax:

TextField text_field = new TextField(20);


We can specify the maximum number of the columns (characters) allowed for the text field by passing the value in the constructor. It the above syntax i have used 20 as the maximum number, you can use any number according to your requirement.

code for adding text field on the frame:

import java.awt.*;
class TextFieldExample
{
    Frame fob;
    
    TextField text_field;
        
    TextFieldExample()
    {
        fob= new Frame("Window Title");       
        fob.setSize(200,200); // setSize will set the heigth and width of the frame
        fob.setLayout(null); 
    
        text_field = new TextField(20); // initializing textfield with maximum 20characters length
        text_field.setBounds(40,70,100,20); // setting textfield on the frame

        
        fob.add(text_field); // adding textfield on the frame
        fob.show(); // display the frame on the runtime
    }

    public static void main(String args[])
    {
        new TextFieldExample();
    }
}




Button:


We all are familiar with button, they allow user to perform some operation like: save / close / open or to perform any other action related with the task.

btn

Syntax:

Button button1 = new Button("Button1");


We have passed a string “Button1” in constructor of the Button class, it will set the button text to “Button1”.

import java.awt.*;
class ButtonExample
{
    Frame _frame;
    Button button1;
    
    ButtonExample()
    {
        _frame= new Frame("Window Title");
        _frame.setSize(200,200); 
        _frame.setLayout(null);
    
        button1= new Button("Button1"); // Initializing button with text Button1.
        button1.setBounds(70,100,50,20);// setting button on the frame.
            
        _frame.add(button1); // adding button on the frame.
        _frame.show(); // show() method will display the frame on runtime
    }

    public static void main(String args[])
    {
        new ButtonExample();
    }
}




TextArea:


TextArea is used to display very long text (ex. action logs)  to users and it also allows user to enter or edit values in text area.
txtara Syntax:

TextArea text_area = new TextArea();



We can also specify the size of textarea in  rows and the columns (maximum characters allowed) by :

TextArea ( int rows, int cols );

import java.awt.*;
class TextAreaExample
{
    Frame _frame;
    TextArea text_area; // declaring text area object

    TextAreaExample()
    {
        _frame= new Frame("Window Title");
        _frame.setSize(200,200); 
        _frame.setLayout(null);
        
        text_area = new TextArea(); // initializing text area object
        text_area.setBounds(20,70,150,80); // setting position and height width of textarea
    
        _frame.add(text_area); // adding textarea on frame
        _frame.show(); 
    }

    public static void main(String args[])
    {
        new TextAreaExample();
    }
}



CheckBox


We all are familiar with checkbox. They allows user to select  one or multiple option.

chbx

Syntax:

Checkbox checkbox1= new Checkbox("chekbox1");


import java.awt.*;
class CheckboxExample
{
    Frame _frame;
    Checkbox checkbox1;
    
    CheckboxExample()
    {
        _frame= new Frame("Window Title");
        _frame.setSize(200,200); 
        _frame.setLayout(null);
    
        checkbox1= new Checkbox("chekbox1"); // initializing checkbox
        checkbox1.setBounds(70,100,80,20); 
    
        _frame.add(checkbox1 ); // adding checkbox on frame
        _frame.show(); 
    }

    public static void main(String args[])
    {
        new CheckboxExample();
    }
}




RadioButton:


Radio Button is a group of buttons from which only one button can be selected a time. For creating radio button, we need to add check boxes to checkbox group.

rdbut

Syntax for Creating CheckboxGroup:

CheckboxGroup checkboxGroup_name = new CheckboxGroup();


import java.awt.*;
class RadioButtonExample
{
    Frame _frame;
    CheckboxGroup chkgp;
    Checkbox r1,r2;

    RadioButtonExample()
    {
        _frame= new Frame("Window Title");
        _frame.setSize(200,200); // The setSize method will set the heigth and width to 400px.
        _frame.setLayout(null);
    
        chkgp = new CheckboxGroup(); // initializing checkbox group
    
        // initializing checkbox by passing caption, checkbox group and default value
        r1 =new Checkbox("FristRadioButton",chkgp, true); 
        r2 =new Checkbox("SecondRadioButton",chkgp, false);
    
        r1.setBounds(20,80,130,20);
        r2.setBounds(100,110,130,20);
    
        _frame.add(r1);
        _frame.add(r2);

        _frame.show(); //the Show Method is used to show the Frame on screen
    }

    public static void main(String args[])
    {
        new RadioButtonExample();
    }
}




List


The List presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items.

lst Syntax:

List list_1 = new List();


adding items in list:

//additem() method is used to add item in list.
list_1.addItem("java"); 
list_1.addItem("JSp");
list_1.addItem("J2ME");


Code for creating list and adding items:

import java.awt.*;
class ListExample
{
    Frame _frame;
    List list_1;

    ListExample()
    {
        _frame = new Frame("Window Title");
        _frame.setSize(200,200); // The setSize method will set the heigth and width to 400px
        _frame.setLayout(null);

        list_1 = new List(); // intializing list object
    
        //adding item in list
        list_1.addItem("java"); 
        list_1.addItem("JSp");
        list_1.addItem("J2ME");
    
        list_1.setBounds(40,70,100,50);
        _frame.add(list_1);        

        _frame.show(); 
    }

    public static void main(String args[])
    {
        new ListExample();
    }
}




Choice (Dropdown or Combo box):


The Choice lets the user choose one of several choices. The current selected choice is displayed as the title of the menu.

chce Syntax:

Choice choice_name = new Choice();


adding item in choice:

choice.addItem("J2SE");
choice.addItem("J2ME");
choice.addItem("J2EE");


import java.awt.*;
class ChoiceExample
{
    Frame _frame;
    Choice choice;

    ChoiceExample()
    {
        _frame= new Frame("Window Title");
        _frame.setSize(200,200); 
        _frame.setLayout(null);

        choice=new Choice(); // initializing chocie
    
        //adding item in choice 
        choice.addItem("J2SE");
        choice.addItem("J2ME");
        choice.addItem("J2EE");
    
        choice.setBounds(40,70,100,50);

        _frame.add(choice); // adding choice on frame
        _frame.show(); 
    }

    public static void main(String args[])
    {
        new ChoiceExample();
    }
}





Sunday, November 24, 2013

How to create Frame in AWT

Frame: Frame encapsulates what is commonly thought of as a "window". Window is basic element of user interface. AWT provides Frame class to create and maintain windows.
Creating a frame or window is very simple, you just need to initialize an object of Frame class, set some properties and your window is ready to display. Frame class provides two constructors:
1. Frame()
2. Frame(String Title)
First constructor is used to initialize frame object and the second constructor is used to initialize the frame object with title (Title of the window).
Syntax:
Frame _frame = new Frame(); //for creating a window without title



Frame _frame = new Frame("Window Title"); // for creating window with title


after initializing frame object we can set height and width of the frame or window by setSize() method.

Syntax:
//setSize(int newWidth, int newHeigth);

_frame.setSize(200,300);


after setting the height and width of the frame we can display the form by calling show() method of class Frame.
_frame.show(); // it will display the frame on runtime


Here is the complete code for creating and displaying AWT Frame/ Window:
import java.awt.*; // importing awt package
class MyWindow
{
    Frame _frame;
    MyWindow()
    {
        _frame = new Frame("Window Title");

        _frame.setSize(200,300); // The setSize method will set the heigth and width

        _frame.show(); //the Show Method is used to show the Frame on screen
    }

    public static void main(String args[])
    {
        new MyWindow();
    }
}


Output of the above program will look like:
frm