Java does allow you to extend a class, change the value of a variable, and override a method of a class. Sometimes, however, you can modify this behavior to disable extendibility, prevent value of the variable from being changed, and prevent the method from being overridden by using the final keyword.
When the final keyword is written before the name of a class, the class will become a final class. You cannot create a sub-class to extend the final class. You will get a compile error if you try to extend the final class. By placing the final keyword before the name of a variable, the variable will be a constant variable. You can assign a value to the constant variable only one time when it is defined. Further change to the value of the variable will also generate compile error. When the final keyword stays before the name of a method, the method will become a final method. The final method does not allow any code to override it.
In the example code below, the Reader class is a final class. The value of the path variable cannot be further changed by any code in the class. The readText method can be called from other classes. However, it cannot be overridden by any code outside the class.
import java.io.BufferedReader;
import java.io.FileReader;
final class Reader{ //final class
private final String path="d:/test.txt"; //constant variable
public final void readText(){ //final method
try {
FileReader fr=new FileReader(path);
BufferedReader br=new BufferedReader(fr);
String content="";
while((content=br.readLine())!=null){
System.out.println(content);
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you try to extend the Reader by creating another class and use the extends keyword, the compile error will display as shown in the picture below.
This site provides you the opportunity to learn Java programming language by programs.
Monday, November 11, 2013
Thursday, November 7, 2013
Generics
Generics is a powerful feature in Java programming language. It is implemented in Collections Framework of Java. The Generics allows you to create generic class, interface, method, and variable. A generic class, interface, method, or variable can work with different types of data because you can specify the type of data as a parameter. Since the generic class, interface, method, or variable does not restrict the type of data when it is defined, it can be reused. For example, you can create only a LinkedList class to store text, integer values, or floating-point values.
You can create a generic class or interface by placing the generic type parameter between the smaller and the greater signs (< and >) after name of the class. The example code below creates a generic class called ListNode. T is the generic type parameter. When you define a generic method or variable, you can place the generic type parameter as you do with a normal data type. This generic type parameter must be the same as the generic type parameter defined with the class.
Example:
class ListNode<T>
{
public T val;
public ListNode<T> next;
public ListNode(T val) { this.val = val; next = null; }
}
When you use a generic class to store value by creating an object and pass the value to it, you should specify the specific data type of the value.
Example:
ListNote<Integer> node=new ListNode<Integer>(123);
You can use many generic type parameters in a class, interface, or methods. You will need to separate the type parameters by comma. See the example below.
Example:
class MyMap<T1,T2>{
private T1 key;
private T2 value;
MyMap(T1 key, T2 value){
this.key=key;
this.value=value;
}
}
Here is the complete LinkedList program that uses the Generics feature.
class ListNode<T>
{
public T val;
public ListNode<T> next;
public ListNode(T val) { this.val =val; next = null; }
}
interface ListOperations<T>
{
void insertNode(T val, int post);
void deleteNode(int post);
void printList();
}
class LinkedList<T> implements ListOperations<T>
{
protected ListNode<T> pfirst; //pfirst points to the first element of the linked list
protected ListNode<T> plast;//plast points to the last element of the linked list
protected int NumItems;
public LinkedList() { pfirst = plast = null; NumItems = 0; }
public void insertNode(T val,int post)
{
ListNode<T> newNode = new ListNode<T>(val);
if (pfirst == null)
{
pfirst = newNode;
plast = newNode;
NumItems++;
}
else
{
if (post == 1)
{
newNode.next = pfirst;
pfirst =newNode;
NumItems++;
}
else if(post>1 && post<=NumItems){
ListNode<T> ta = pfirst;
for (int i = 1; i < post - 1; i++) ta = ta.next;
newNode.next = ta.next;
ta.next = newNode;
NumItems++;
}
else if (post == (NumItems + 1))
{
plast.next = newNode;
plast = newNode;
NumItems++;
}
else
{
System.out.println("Invalid position");
}
}
}
public void deleteNode(int post)
{
if (pfirst == null)
{
System.out.println("Empty list");
return;
}
if (post == 1)
{
if (NumItems == 1)
{
pfirst = null;
plast = null;
}
else
{
ListNode<T> temp = pfirst;
pfirst = pfirst.next;
temp = null;
}
}
else if(post>=1 && post<=NumItems){
ListNode<T> temp, ta;
ta = pfirst;
for(int i=0;i<post-1;i++) ta=ta.next;
temp = ta.next;
ta.next = temp.next;
if (temp.next == null) plast = ta;
temp = null;
}
}
public void printList()
{
ListNode<T> ta = pfirst;
while (ta != null)
{
System.out.println(ta.val);
ta = ta.next;
}
}
public Object[] toArray(){
Object[] arr=new Object[NumItems];
ListNode<T> ta = pfirst;
int i=0;
while (ta != null)
{
arr[i]=ta.val;
ta = ta.next;
i++;
}
return arr;
}
}
public class GenericsJava {
public static void main(String[] args){
//Creating linked list to store text
LinkedList<String> lstString = new LinkedList<String>();
lstString.insertNode("Item1", 1);
lstString.insertNode("Item2", 2);
lstString.insertNode("Item3", 3);
lstString.printList();
//creating linked list to store numbers
LinkedList<Integer> lstNumber = new LinkedList<Integer>();
lstNumber.insertNode(10, 1);
lstNumber.insertNode(13, 2);
lstNumber.insertNode(13, 3);
lstNumber.printList();
}
}
You can create a generic class or interface by placing the generic type parameter between the smaller and the greater signs (< and >) after name of the class. The example code below creates a generic class called ListNode. T is the generic type parameter. When you define a generic method or variable, you can place the generic type parameter as you do with a normal data type. This generic type parameter must be the same as the generic type parameter defined with the class.
Example:
class ListNode<T>
{
public T val;
public ListNode<T> next;
public ListNode(T val) { this.val = val; next = null; }
}
When you use a generic class to store value by creating an object and pass the value to it, you should specify the specific data type of the value.
Example:
ListNote<Integer> node=new ListNode<Integer>(123);
You can use many generic type parameters in a class, interface, or methods. You will need to separate the type parameters by comma. See the example below.
Example:
class MyMap<T1,T2>{
private T1 key;
private T2 value;
MyMap(T1 key, T2 value){
this.key=key;
this.value=value;
}
}
Here is the complete LinkedList program that uses the Generics feature.
class ListNode<T>
{
public T val;
public ListNode<T> next;
public ListNode(T val) { this.val =val; next = null; }
}
interface ListOperations<T>
{
void insertNode(T val, int post);
void deleteNode(int post);
void printList();
}
class LinkedList<T> implements ListOperations<T>
{
protected ListNode<T> pfirst; //pfirst points to the first element of the linked list
protected ListNode<T> plast;//plast points to the last element of the linked list
protected int NumItems;
public LinkedList() { pfirst = plast = null; NumItems = 0; }
public void insertNode(T val,int post)
{
ListNode<T> newNode = new ListNode<T>(val);
if (pfirst == null)
{
pfirst = newNode;
plast = newNode;
NumItems++;
}
else
{
if (post == 1)
{
newNode.next = pfirst;
pfirst =newNode;
NumItems++;
}
else if(post>1 && post<=NumItems){
ListNode<T> ta = pfirst;
for (int i = 1; i < post - 1; i++) ta = ta.next;
newNode.next = ta.next;
ta.next = newNode;
NumItems++;
}
else if (post == (NumItems + 1))
{
plast.next = newNode;
plast = newNode;
NumItems++;
}
else
{
System.out.println("Invalid position");
}
}
}
public void deleteNode(int post)
{
if (pfirst == null)
{
System.out.println("Empty list");
return;
}
if (post == 1)
{
if (NumItems == 1)
{
pfirst = null;
plast = null;
}
else
{
ListNode<T> temp = pfirst;
pfirst = pfirst.next;
temp = null;
}
}
else if(post>=1 && post<=NumItems){
ListNode<T> temp, ta;
ta = pfirst;
for(int i=0;i<post-1;i++) ta=ta.next;
temp = ta.next;
ta.next = temp.next;
if (temp.next == null) plast = ta;
temp = null;
}
}
public void printList()
{
ListNode<T> ta = pfirst;
while (ta != null)
{
System.out.println(ta.val);
ta = ta.next;
}
}
public Object[] toArray(){
Object[] arr=new Object[NumItems];
ListNode<T> ta = pfirst;
int i=0;
while (ta != null)
{
arr[i]=ta.val;
ta = ta.next;
i++;
}
return arr;
}
}
public class GenericsJava {
public static void main(String[] args){
//Creating linked list to store text
LinkedList<String> lstString = new LinkedList<String>();
lstString.insertNode("Item1", 1);
lstString.insertNode("Item2", 2);
lstString.insertNode("Item3", 3);
lstString.printList();
//creating linked list to store numbers
LinkedList<Integer> lstNumber = new LinkedList<Integer>();
lstNumber.insertNode(10, 1);
lstNumber.insertNode(13, 2);
lstNumber.insertNode(13, 3);
lstNumber.printList();
}
}
Tuesday, November 5, 2013
GridBagLayout
GridBagLayout is a layout manager in AWT package. It is more complex than GridLayout. But it is more powerful or flexible than GridLayout. By using the GridBagLayout, you can have different components of different sizes in a single row or column. When you arrange components on a container, you do not need to specify the number of rows or columns. Instead, you will need to specify the constraints or rules by using the GridBagContraints class. These constraints help GridBagLayout to place the components in the proper places on the container. Below are common constraints used in setting up the grid.
Example: The following code below arranges the components on the JFrame window as shown in the picture.
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class GridBagLayoutManager {
public static void main(String[] args){
JFrame jf=new JFrame("GridBagLayout");
jf.setSize(500,300);
Container container=jf.getContentPane();
GridBagLayout gb=new GridBagLayout();
container.setLayout(gb);
GridBagConstraints gc = new GridBagConstraints();
JButton bt1=new JButton("Button 1");
JButton bt2=new JButton("Button 2");
//fill components in cells
gc.fill = GridBagConstraints.BOTH;
gb.setConstraints(bt1, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gb.setConstraints(bt2, gc);
container.add(bt1);
container.add(bt2);
//add JTextArea, Button 3, and Button 4 to the second row
JTextArea ja=new JTextArea(10,10);
ja.setLineWrap(true);
ja.setText("GridBagLayout is a layout manager that is more powerful than the GridLayout manager.");
JButton bt3=new JButton("Button 3");
JButton bt4=new JButton("Button 4");
//expand row and column
gc.gridwidth =2; //2 columns
gc.gridheight =3;//3 rows
gb.setConstraints(ja, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
//reset row and column
gc.gridwidth =1;
gc.gridheight = 1;
gb.setConstraints(bt3, gc);
gc.gridy=2; //Add the Button 4 below the Button 3
gb.setConstraints(bt4, gc);
container.add(ja);
container.add(bt3);
container.add(bt4);
jf.setVisible(true);
}
}
| fill | allows the components to resize automatically when the row or column expanded or thrinked. |
|---|---|
| gridwidth | specifies the number of columns in the area to display the component. |
| gridheight | specifies the number of rows in the area to display the component. |
| gridx | specifies the column in the grid to display the component. Its value starts from 0 (first column). |
| gridy | specifies the row in the grid to display the component. Its value starts from 0 (first row). |
Example: The following code below arranges the components on the JFrame window as shown in the picture.
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class GridBagLayoutManager {
public static void main(String[] args){
JFrame jf=new JFrame("GridBagLayout");
jf.setSize(500,300);
Container container=jf.getContentPane();
GridBagLayout gb=new GridBagLayout();
container.setLayout(gb);
GridBagConstraints gc = new GridBagConstraints();
JButton bt1=new JButton("Button 1");
JButton bt2=new JButton("Button 2");
//fill components in cells
gc.fill = GridBagConstraints.BOTH;
gb.setConstraints(bt1, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gb.setConstraints(bt2, gc);
container.add(bt1);
container.add(bt2);
//add JTextArea, Button 3, and Button 4 to the second row
JTextArea ja=new JTextArea(10,10);
ja.setLineWrap(true);
ja.setText("GridBagLayout is a layout manager that is more powerful than the GridLayout manager.");
JButton bt3=new JButton("Button 3");
JButton bt4=new JButton("Button 4");
//expand row and column
gc.gridwidth =2; //2 columns
gc.gridheight =3;//3 rows
gb.setConstraints(ja, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
//reset row and column
gc.gridwidth =1;
gc.gridheight = 1;
gb.setConstraints(bt3, gc);
gc.gridy=2; //Add the Button 4 below the Button 3
gb.setConstraints(bt4, gc);
container.add(ja);
container.add(bt3);
container.add(bt4);
jf.setVisible(true);
}
}
Sunday, November 3, 2013
ArrayDeque
ArrayDeque is a data structure that implements the Deque interface. Deque is the short form of "double ended queue" and generally pronounced as "deck". The ArrayDeque does not limit the number of its elements. It can grow when needed. It is likely to be faster than stack or queue data structure when it used as stack or queue data structure. Most its methods (e.g. add, addFirst, addLast, clear, clone, getFirst, getLast, isEmpty, peekFirst, peakLas, pollFirst, pollLast, size, and toArray) of the ArrayDeque run in constant time (c) and few methods (e.g. remove, removeFirstOccurence, removeLastOccurrence, and contains) run in linear time
(O(n)). You can create an ArrayDeque object by using one of the ArrayDeque constructors.
-ArrayDeque() creates an empty deque enough for storing 16 elements.
-ArrayDeque(Collection<? extends E> c) creates a deque from a specified collection object (e.g. ArrayDeque, LinkedList, Stack, ...).
-ArrayDeque(int capacity) creates an empty deque with initial capacity (number of elements).
To add a new element to the ArrayDeque object, you can use the add(E e), addFirst(E e), and addLast(E e) methods. The add and addLast method will add the element at the end of the deque. The addFirst method will add the element to the front of the deque.
Example:
ArrayDeque<Integer> ad=new ArrayDeque<Integer>();
Random random=new Random();
for(int i=0;i<10;i++){
ad.add(1+Math.abs(random.nextInt())%6);
}
To remove elements from the ArrayDeque object, you will use the clear, poll, pollFirst, pollLast, remove, remove(Object o), removeFirst(), removeFirstOccurence(Object o), removeLast, and removeLastOccurrence (Object o). The clear method will remove all elements of the deque. The poll, pollFirst, remove, removeFirst methods will retrieve and remove the first element of the deque. The pollLast and removeLast method will retrieve and remove the last elelement of the deque. If you want to remove any element in the deque, you can use the remove(Object o) method. The removeFirstOccurrence will remove the the first matched element and the removeLastOccurrence will remove the last matched elements.
Example:
int fele=ad.remove();
System.out.println("Removed "+fele);
int lele=ad.removeLast();
System.out.println("Removed "+lele);
If you want to get the elements without removing them from the deque, you will use the getFirst, getLast, peekFirst, and peekLast methods. The getFirst and peekFirst methods return the first element of the deque. In contrast, the getLast and peekLast methods return the last element of the deque.
Example:
int fele=ad.getFirst();
System.out.println("The first element is "+fele+".");
int lele=ad.getLast();
System.out.println("The last element is "+lele+".");
Another useful method of the ArrayDeque is iterator(). The iterator method can be used traverse through the deque. See the example code below.
Iterator<Integer> i=ad.iterator();
while(i.hasNext()){
System.out.print(i.next()+"\t");
}
-ArrayDeque() creates an empty deque enough for storing 16 elements.
-ArrayDeque(Collection<? extends E> c) creates a deque from a specified collection object (e.g. ArrayDeque, LinkedList, Stack, ...).
-ArrayDeque(int capacity) creates an empty deque with initial capacity (number of elements).
To add a new element to the ArrayDeque object, you can use the add(E e), addFirst(E e), and addLast(E e) methods. The add and addLast method will add the element at the end of the deque. The addFirst method will add the element to the front of the deque.
Example:
ArrayDeque<Integer> ad=new ArrayDeque<Integer>();
Random random=new Random();
for(int i=0;i<10;i++){
ad.add(1+Math.abs(random.nextInt())%6);
}
To remove elements from the ArrayDeque object, you will use the clear, poll, pollFirst, pollLast, remove, remove(Object o), removeFirst(), removeFirstOccurence(Object o), removeLast, and removeLastOccurrence (Object o). The clear method will remove all elements of the deque. The poll, pollFirst, remove, removeFirst methods will retrieve and remove the first element of the deque. The pollLast and removeLast method will retrieve and remove the last elelement of the deque. If you want to remove any element in the deque, you can use the remove(Object o) method. The removeFirstOccurrence will remove the the first matched element and the removeLastOccurrence will remove the last matched elements.
Example:
int fele=ad.remove();
System.out.println("Removed "+fele);
int lele=ad.removeLast();
System.out.println("Removed "+lele);
If you want to get the elements without removing them from the deque, you will use the getFirst, getLast, peekFirst, and peekLast methods. The getFirst and peekFirst methods return the first element of the deque. In contrast, the getLast and peekLast methods return the last element of the deque.
Example:
int fele=ad.getFirst();
System.out.println("The first element is "+fele+".");
int lele=ad.getLast();
System.out.println("The last element is "+lele+".");
Another useful method of the ArrayDeque is iterator(). The iterator method can be used traverse through the deque. See the example code below.
Iterator<Integer> i=ad.iterator();
while(i.hasNext()){
System.out.print(i.next()+"\t");
}
Saturday, November 2, 2013
Get IP Address
In Java, it is not hard to get the IP address or host name of the local or remote machine. If your program has to retrieve the IP address or host name of a machine, you will use the InetAddress class. The instance of the InetAddress stores IP address and host name of the machine. The getLoopbackAddress method of the InetAddress will return the loop back address and the localhost name of the local machine. These information are embedded in an InetAddress object. Besides getLoopbackAddress method, you can use the getLocalHost method to get the IP address and the host name that you use to connect to your network. See the example code below.
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
public class GetIP{
public static void main(String[] args) {
try
{
InetAddress addr1 = InetAddress.getLoopbackAddress();
InetAddress addr2 = InetAddress.getLocalHost();
System.out.println("Host name:"+addr1.getHostName());
System.out.println("IP:"+addr1.getHostAddress());
System.out.println("Host name:"+addr2.getHostName());
System.out.println("IP:"+addr2.getHostAddress());
}catch(UnknownHostException e) {e.printStackTrace(); }
}
}
The two methods above are able to get the IP addresses and host names of the local machine only. If you want to get the IP addresses of a remote machine (e.g. IP addresses of a web server), you will use the getByName method. This method accepts the host name of the remote machine. You will use the URL class to point to the remote host.
public static void getIPfromURL(String strurl){
try {
URL url=new URL(strurl);
InetAddress address = InetAddress.getByName(url.getHost());
System.out.println(address.getHostAddress());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
public class GetIP{
public static void main(String[] args) {
try
{
InetAddress addr1 = InetAddress.getLoopbackAddress();
InetAddress addr2 = InetAddress.getLocalHost();
System.out.println("Host name:"+addr1.getHostName());
System.out.println("IP:"+addr1.getHostAddress());
System.out.println("Host name:"+addr2.getHostName());
System.out.println("IP:"+addr2.getHostAddress());
}catch(UnknownHostException e) {e.printStackTrace(); }
}
}
The two methods above are able to get the IP addresses and host names of the local machine only. If you want to get the IP addresses of a remote machine (e.g. IP addresses of a web server), you will use the getByName method. This method accepts the host name of the remote machine. You will use the URL class to point to the remote host.
public static void getIPfromURL(String strurl){
try {
URL url=new URL(strurl);
InetAddress address = InetAddress.getByName(url.getHost());
System.out.println(address.getHostAddress());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thursday, October 31, 2013
Documentation in Java
In this tutorial, you will learn to do documentation of your Java programs. Java comes with a powerful tool called javadoc. This tool allows Java developer easily to create documentation of their programs. The javadoc tool extracts your comments embedded in the source code, constant fields, class name, methods and outputs these information in html files.
The comments that can be recognized by the javadoc tool must be placed between /** and */. Besides normal text, in the block of /** and */, there are some special tags that can be recognized by the javadoc tool. The table below summarizes these tags.
For example, you have the JCalc class that is a simple calculator class. It contains twelve methods that can be used to add, subtract, multiply, and divide integer and floating-pointer numbers.
/**
* This is the JCalc class. It has twelve methods that can be called to add, subtract, multiply,
* and divide floating-point numbers. See the {@link <a href="index.html">JCalc</a>}.
* @author Dara Yuk
* @version 1.0
*
*/
public class JCalc{
/**
* The value of the constant is {@value}.
*/
public static final double PI=Math.PI;
public static void main(String[] args){
}
/**
* This method adds two integer values a and b.
* @param a
* @param b
* @return a+b
* @see <a href="JavaTutorial.html">Java Tutorial</a>
*/
public int sum(int a,int b){
return(a+b);
}
/**
* This method adds two float values a and b.
* @param a
* @param b
* @return a+b
*/
public float sum(float a,float b){
return(a+b);
}
/**
* This method adds double values a and b.
* @param a
* @param b
* @return a+b
*/
public double sum(double a,double b){
return(a+b);
}
/**
* This method subtracts b from a. The parameters a and b are integer.
* @param a
* @param b
* @return a-b
*/
public int subtract(int a,int b){
return(a-b);
}
/**
* This method subtracts b from a. The parameters a and b are float.
* @param a
* @param b
* @return a-b
*/
public float subtract(float a,float b){
return(a-b);
}
/**
* This method subtracts b from a. The parameters a and b are double.
* @param a
* @param b
* @return a-b
*/
public double subtract(double a,double b){
return(a-b);
}
/**
* This method multiplies a and b. The parameters a and b are integer.
* @param a
* @param b
* @return a*b
*/
public int multiply(int a,int b){
return(a*b);
}
/**
* This method multiplies a and b. The parameters a and b are float.
* @param a
* @param b
* @return a*b
*/
public float multiply(float a,float b){
return(a*b);
}
/**
* This method multiplies a and b. The parameters a and b are double.
* @param a
* @param b
* @return a*b
*/
public double multiply(double a,double b){
return(a*b);
}
/**
* This method divides a by b. The parameters a and b are integer.
* @param a
* @param b
* @return a/b
*/
public double divide(int a,int b){
return(a/b);
}
/**
* This method divides a by b. The parameters a and b are float.
* @param a
* @param b
* @return a/b
*/
public float divide(float a,float b){
return(a/b);
}
/**
* This method divides a by b. The parameters a and b are double.
* @param a
* @param b
* @return a/b
*/
public double divide(double a,double b){
return(a/b);
}
}
To create the document of the JCalc class, from the command prompt, enter the directory that contains the JCalc.java file and type the following command:
D:\eclipse\charts\Calculator\src>javadoc -d docs JCalc.java
While javadoc is processing the file, the messages below are displayed on the screen.
Loading source file JCalc.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_21
Building tree for all the packages and classes...
Generating docs\JCalc.html...
Generating docs\package-frame.html...
Generating docs\package-summary.html...
Generating docs\package-tree.html...
Generating docs\constant-values.html...
Generating docs\serialized-form.html...
Building index for all the packages and classes...
Generating docs\overview-tree.html...
Generating docs\index-all.html...
Generating docs\deprecated-list.html...
Building index for all classes...
Generating docs\allclasses-frame.html...
Generating docs\allclasses-noframe.html...
Generating docs\index.html...
Generating docs\help-doc.html...
The document pages will be generated in the src/docs folder.
The comments that can be recognized by the javadoc tool must be placed between /** and */. Besides normal text, in the block of /** and */, there are some special tags that can be recognized by the javadoc tool. The table below summarizes these tags.
| Tag | Description | Example |
|---|---|---|
| @author | The author tag allows you to specify the information about the author. | @author Dara Yuk |
| @deprecated | This tag specifies that a class or method is deprecated in the current version. | @deprecated Deprecated |
| @exception | This tag is used to specify the type of exception to be thrown. | @exception IOException |
| {@link} | This tag is used to specify the in-line link to other page. | See the {@link <a href="JCalc.htm">JCalc</a>} |
| @param | This tag specifies the parameter of a method. | @param a |
| @return | This tag allows you to specify the return value of a method. | @return sum |
| @see | You can use this tag to provide a link to other topic or page. This link will shown at the "See Also" section of the page. | @see <a href="Jtutorial.html">Java Tutorial</a> |
| @serial | This tag specifies the default serial field. You can describe the field and its possible values. The information about this tag will be shown in the Serial Form page. | @serial The PI field |
| @since | You will use this tag to spcify the version of your software when a specific change was introduced. | @since 1.6 |
| {@value} | You will use this tag to display the value of a constant field. | The value of this field is {@value}. |
| @version | This tag will be used to specify the current version of your software. | @version 1.0 |
For example, you have the JCalc class that is a simple calculator class. It contains twelve methods that can be used to add, subtract, multiply, and divide integer and floating-pointer numbers.
/**
* This is the JCalc class. It has twelve methods that can be called to add, subtract, multiply,
* and divide floating-point numbers. See the {@link <a href="index.html">JCalc</a>}.
* @author Dara Yuk
* @version 1.0
*
*/
public class JCalc{
/**
* The value of the constant is {@value}.
*/
public static final double PI=Math.PI;
public static void main(String[] args){
}
/**
* This method adds two integer values a and b.
* @param a
* @param b
* @return a+b
* @see <a href="JavaTutorial.html">Java Tutorial</a>
*/
public int sum(int a,int b){
return(a+b);
}
/**
* This method adds two float values a and b.
* @param a
* @param b
* @return a+b
*/
public float sum(float a,float b){
return(a+b);
}
/**
* This method adds double values a and b.
* @param a
* @param b
* @return a+b
*/
public double sum(double a,double b){
return(a+b);
}
/**
* This method subtracts b from a. The parameters a and b are integer.
* @param a
* @param b
* @return a-b
*/
public int subtract(int a,int b){
return(a-b);
}
/**
* This method subtracts b from a. The parameters a and b are float.
* @param a
* @param b
* @return a-b
*/
public float subtract(float a,float b){
return(a-b);
}
/**
* This method subtracts b from a. The parameters a and b are double.
* @param a
* @param b
* @return a-b
*/
public double subtract(double a,double b){
return(a-b);
}
/**
* This method multiplies a and b. The parameters a and b are integer.
* @param a
* @param b
* @return a*b
*/
public int multiply(int a,int b){
return(a*b);
}
/**
* This method multiplies a and b. The parameters a and b are float.
* @param a
* @param b
* @return a*b
*/
public float multiply(float a,float b){
return(a*b);
}
/**
* This method multiplies a and b. The parameters a and b are double.
* @param a
* @param b
* @return a*b
*/
public double multiply(double a,double b){
return(a*b);
}
/**
* This method divides a by b. The parameters a and b are integer.
* @param a
* @param b
* @return a/b
*/
public double divide(int a,int b){
return(a/b);
}
/**
* This method divides a by b. The parameters a and b are float.
* @param a
* @param b
* @return a/b
*/
public float divide(float a,float b){
return(a/b);
}
/**
* This method divides a by b. The parameters a and b are double.
* @param a
* @param b
* @return a/b
*/
public double divide(double a,double b){
return(a/b);
}
}
To create the document of the JCalc class, from the command prompt, enter the directory that contains the JCalc.java file and type the following command:
D:\eclipse\charts\Calculator\src>javadoc -d docs JCalc.java
While javadoc is processing the file, the messages below are displayed on the screen.
Loading source file JCalc.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_21
Building tree for all the packages and classes...
Generating docs\JCalc.html...
Generating docs\package-frame.html...
Generating docs\package-summary.html...
Generating docs\package-tree.html...
Generating docs\constant-values.html...
Generating docs\serialized-form.html...
Building index for all the packages and classes...
Generating docs\overview-tree.html...
Generating docs\index-all.html...
Generating docs\deprecated-list.html...
Building index for all classes...
Generating docs\allclasses-frame.html...
Generating docs\allclasses-noframe.html...
Generating docs\index.html...
Generating docs\help-doc.html...
The document pages will be generated in the src/docs folder.
Tuesday, October 29, 2013
E-mail in Java
This is a simple E-mail in Java program. You can use it to send message with multiple attachments to multiple recipients at the same time. Before you use the program to send e-mail message, you will need to configure the mail. The configuration form allows you to enter the outgoing server name, port, user name and password to log in the server. For security reason, your password is encrypted. The configuration file (mailconfigs.con) is stored in your current working folder. You can configure the email by going to File menu->Setup Configuration...One you configured the mail correctly, you do not need to configure it again later.
After you configured the mail, you will need to input the From address (your e-mail address), the recipients' e-mail addresses, subject, and message of the mail. Bcc, Cc e-mail addresses, and file attachments are optional.
In Java, it is easy to send e-mail by using the Apache Commons Mail api. You will download the Apache Commons Mail api from its website. This api depends on the Java Mail api. You can download Java Mail api from here. After downloading the two api, extract the zip files and add the jar files (commons-email-1.3.2.jar and javax.mail.jar) to the Java Build Path in the Eclipse.
In the Commons Mail api, there two classes that can be used to send e-mail message. One class is SimpleEmail. The SimpleEmail class is used to send e-mail message without attachment. Another class is called MultiPartEmail. This class is able to send e-mail message with attachments. Like the SimpleEmail class, the MultiPartEmail class has methods that allow you to configure e-mail in your Java code.
MultiPartEmail email=new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,password);
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
There are other methods that you will use to set the From e-mail address, To e-mail addresses, Bcc e-mail adddress, Cc e-mail addresses, subject, message, and attachment of the mail.
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipient's (to) e-mail address
email.addTo(Toadd);
//add recipient's (Bcc) e-mail address
email.addBcc(Bccadd);
//add recipient's (Cc) e-mail address
email.addCc(Ccadd);
//add file attachment
email.attach(new File(path));
//send the email
email.send();
Here is the complete code of the E-mail in Java program.
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
class UI extends JFrame implements ActionListener{
JTextField textfrom;
JTextField textto;
JTextField textbcc;
JTextField textcc;
JTextField textsubject;
JTextArea textmessage;
JLabel lblstatus;
JTextField txtserver;
JTextField txtport;
JTextField txtuser;
JPasswordField txtpwd;
DefaultListModel<String> listmodel;
MultiPartEmail email;
ArrayList<String> configs;
JFrame frame;
UI(String title){
Container cont=getContentPane();
setTitle(title);
setResizable(false);
setSize(new Dimension(650,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic('F');
JMenuItem itemserver=new JMenuItem("Mail configure...");
itemserver.addActionListener(this);
JMenuItem itemexit=new JMenuItem("Exit");
itemexit.addActionListener(this);
mfile.add(itemserver);
mfile.add(itemexit);
mbar.add(mfile);
setJMenuBar(mbar);
JPanel panelmain=new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel lblfrom=new JLabel("From:");
textfrom=new JTextField(30);
JButton btadd=new JButton("Send");
btadd.addActionListener(this);
JPanel panelnorth=new JPanel();
panelnorth.add(lblfrom);
panelnorth.add(textfrom);
panelnorth.add(btadd);
GridBagLayout gbl=new GridBagLayout();
JPanel panelcenter=new JPanel(gbl);
GridBagConstraints gc = new GridBagConstraints();
JLabel lblto=new JLabel("To:");
textto=new JTextField(30);
JLabel lblbcc=new JLabel("Bcc:");
textbcc=new JTextField(30);
JLabel lblcc=new JLabel("Cc:");
textcc=new JTextField(30);
JLabel lblsubject=new JLabel("Subject:");
textsubject=new JTextField();
JButton btatt=new JButton("Attach");
btatt.addActionListener(this);
listmodel=new DefaultListModel<String>();
JList<String> attlist=new JList<String>(listmodel);
attlist.setVisibleRowCount(5);
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 1.0;
gbl.setConstraints(lblto, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textto, gc);
panelcenter.add(lblto);
panelcenter.add(textto);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblbcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textbcc, gc);
panelcenter.add(lblbcc);
panelcenter.add(textbcc);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textcc, gc);
panelcenter.add(lblcc);
panelcenter.add(textcc);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblsubject, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textsubject, gc);
panelcenter.add(lblsubject);
panelcenter.add(textsubject);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(btatt, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gc.gridheight = 2;
gbl.setConstraints(attlist, gc);
panelcenter.add(btatt);
panelcenter.add(attlist);
gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weighty = 1.0;
lblstatus=new JLabel("");
lblstatus.setForeground(Color.RED);
gbl.setConstraints(lblstatus, gc);
panelcenter.add(lblstatus);
JPanel panelsouth=new JPanel(new FlowLayout(FlowLayout.LEFT));
panelsouth.add(new JLabel("Message:"));
textmessage=new JTextArea(15,50);
textmessage.setWrapStyleWord(true);
JScrollPane scroll=new JScrollPane(textmessage);
panelsouth.add(scroll);
panelmain.add(panelnorth);
panelmain.add(panelcenter);
panelmain.add(panelsouth);
cont.add(panelmain);
setVisible(true);
configureMail();
}
public void configureMail(){
readConfigs();
if(configs.size()>2){
setEmailConfigs(configs.get(0),Integer.parseInt(configs.get(1)),configs.get(2),configs.get(3));
}
}
public void actionPerformed(ActionEvent e){
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
if(e.getActionCommand().equals("Send")){
String from=textfrom.getText();
if(textto.getText().length()>0)
Tos=textto.getText().split(", ");
if(textbcc.getText().length()>0)
Bccs=textbcc.getText().split(", ");
if(textcc.getText().length()>0)
Ccs=textcc.getText().split(", ");
String subject=textsubject.getText();
String message=textmessage.getText();
if(from.length()>0 && Tos.length>0 && subject.length()>0 && message.length()>0) {
Th th=new Th(from,Tos,Bccs,Ccs,subject,message);
th.start();
}
else{
JOptionPane.showMessageDialog(this,"From, To, Subject, and Message cannot be blank.");
textfrom.requestFocus();
}
}
else if(e.getActionCommand().equals("Attach")){
selectFile();
}
else if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
else if(e.getActionCommand().equals("Mail configure...")){
JPanel p=new JPanel(new GridLayout(5,1));
txtserver=new JTextField("Enter outgoing server");
txtport=new JTextField("Enter server port");
txtuser=new JTextField("Enter user name");
txtpwd=new JPasswordField("Enter password");
JButton bt=new JButton("Save and Close");
bt.addActionListener(this);
p.add(txtserver);
p.add(txtport);
p.add(txtuser);
p.add(txtpwd);
p.add(bt);
frame=new JFrame("Configure mail");
frame.getContentPane().add(p);
frame.setSize(300, 200);
frame.setVisible(true);
}
else if(e.getActionCommand().equals("Save and Close")){
saveConfigs();
frame.dispose();
}
}
class Th extends Thread{
String from;
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
String subject;
String message;
Th(String fromaddr,String[] toaddr,String[] bccaddr,String[] ccaddr,String subj,String mess){
from=fromaddr;
Tos=toaddr;
Bccs=bccaddr;
Ccs=ccaddr;
subject=subj;
message=mess;
lblstatus.setText("Sending the message");
}
public void run(){
sendEmail(from,Tos, Bccs,Ccs,subject, message);
email=null; //create object
lblstatus.setText("");
}
}
public void readConfigs(){
configs=new ArrayList<String>();
BufferedReader br=null;
try {
File f=new File("mailconfigs.con");
if(f.exists()){
FileReader fr=new FileReader(f);
br=new BufferedReader(fr);
String line="";
while((line=br.readLine())!=null){
configs.add(line);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null)
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void saveConfigs(){
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw = new FileWriter("mailconfigs.con");
bw=new BufferedWriter(fw);
bw.write(txtserver.getText());
bw.newLine();
bw.write(txtport.getText());
bw.newLine();
bw.write(txtuser.getText());
bw.newLine();
bw.write(encrypt(new String(txtpwd.getPassword())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null)
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String encrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]+101);
return(new String(sb));
}
public String decrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]-101);
return(new String(sb));
}
public void selectFile(){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
listmodel.addElement(file.getPath());
}
}
public void setEmailConfigs(String smtp,int port, String user, String password){
email = new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,decrypt(password));
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
}
public void sendEmail(String from, String[] Tos, String[] Bccs, String[] Ccs, String subject, String message){
configureMail();
if(email.getHostName().length()>0){
try {
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipients' (to) e-mail addresses
if(Tos!=null)
for(String Toadd:Tos)
email.addTo(Toadd);
//add recipients' (Bcc) e-mail addresses
if(Bccs!=null)
for(String Bccadd:Bccs)
email.addBcc(Bccadd);
//add recipients' (Cc) e-mail addresses
if(Ccs!=null)
for(String Ccadd:Ccs)
email.addCc(Ccadd);
//add file attachments
for(int i=0;i<listmodel.getSize();i++)
email.attach(new File(listmodel.get(i)));
//send the email
email.send();
}catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(this,"The email is not configured.");
}
}
}
public class EmailSender {
public static void main(String[] args){
new UI("E-Mail Sender");
}
}
After you configured the mail, you will need to input the From address (your e-mail address), the recipients' e-mail addresses, subject, and message of the mail. Bcc, Cc e-mail addresses, and file attachments are optional.
In Java, it is easy to send e-mail by using the Apache Commons Mail api. You will download the Apache Commons Mail api from its website. This api depends on the Java Mail api. You can download Java Mail api from here. After downloading the two api, extract the zip files and add the jar files (commons-email-1.3.2.jar and javax.mail.jar) to the Java Build Path in the Eclipse.
In the Commons Mail api, there two classes that can be used to send e-mail message. One class is SimpleEmail. The SimpleEmail class is used to send e-mail message without attachment. Another class is called MultiPartEmail. This class is able to send e-mail message with attachments. Like the SimpleEmail class, the MultiPartEmail class has methods that allow you to configure e-mail in your Java code.
MultiPartEmail email=new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,password);
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
There are other methods that you will use to set the From e-mail address, To e-mail addresses, Bcc e-mail adddress, Cc e-mail addresses, subject, message, and attachment of the mail.
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipient's (to) e-mail address
email.addTo(Toadd);
//add recipient's (Bcc) e-mail address
email.addBcc(Bccadd);
//add recipient's (Cc) e-mail address
email.addCc(Ccadd);
//add file attachment
email.attach(new File(path));
//send the email
email.send();
Here is the complete code of the E-mail in Java program.
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
class UI extends JFrame implements ActionListener{
JTextField textfrom;
JTextField textto;
JTextField textbcc;
JTextField textcc;
JTextField textsubject;
JTextArea textmessage;
JLabel lblstatus;
JTextField txtserver;
JTextField txtport;
JTextField txtuser;
JPasswordField txtpwd;
DefaultListModel<String> listmodel;
MultiPartEmail email;
ArrayList<String> configs;
JFrame frame;
UI(String title){
Container cont=getContentPane();
setTitle(title);
setResizable(false);
setSize(new Dimension(650,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic('F');
JMenuItem itemserver=new JMenuItem("Mail configure...");
itemserver.addActionListener(this);
JMenuItem itemexit=new JMenuItem("Exit");
itemexit.addActionListener(this);
mfile.add(itemserver);
mfile.add(itemexit);
mbar.add(mfile);
setJMenuBar(mbar);
JPanel panelmain=new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel lblfrom=new JLabel("From:");
textfrom=new JTextField(30);
JButton btadd=new JButton("Send");
btadd.addActionListener(this);
JPanel panelnorth=new JPanel();
panelnorth.add(lblfrom);
panelnorth.add(textfrom);
panelnorth.add(btadd);
GridBagLayout gbl=new GridBagLayout();
JPanel panelcenter=new JPanel(gbl);
GridBagConstraints gc = new GridBagConstraints();
JLabel lblto=new JLabel("To:");
textto=new JTextField(30);
JLabel lblbcc=new JLabel("Bcc:");
textbcc=new JTextField(30);
JLabel lblcc=new JLabel("Cc:");
textcc=new JTextField(30);
JLabel lblsubject=new JLabel("Subject:");
textsubject=new JTextField();
JButton btatt=new JButton("Attach");
btatt.addActionListener(this);
listmodel=new DefaultListModel<String>();
JList<String> attlist=new JList<String>(listmodel);
attlist.setVisibleRowCount(5);
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 1.0;
gbl.setConstraints(lblto, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textto, gc);
panelcenter.add(lblto);
panelcenter.add(textto);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblbcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textbcc, gc);
panelcenter.add(lblbcc);
panelcenter.add(textbcc);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textcc, gc);
panelcenter.add(lblcc);
panelcenter.add(textcc);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblsubject, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textsubject, gc);
panelcenter.add(lblsubject);
panelcenter.add(textsubject);
gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(btatt, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gc.gridheight = 2;
gbl.setConstraints(attlist, gc);
panelcenter.add(btatt);
panelcenter.add(attlist);
gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weighty = 1.0;
lblstatus=new JLabel("");
lblstatus.setForeground(Color.RED);
gbl.setConstraints(lblstatus, gc);
panelcenter.add(lblstatus);
JPanel panelsouth=new JPanel(new FlowLayout(FlowLayout.LEFT));
panelsouth.add(new JLabel("Message:"));
textmessage=new JTextArea(15,50);
textmessage.setWrapStyleWord(true);
JScrollPane scroll=new JScrollPane(textmessage);
panelsouth.add(scroll);
panelmain.add(panelnorth);
panelmain.add(panelcenter);
panelmain.add(panelsouth);
cont.add(panelmain);
setVisible(true);
configureMail();
}
public void configureMail(){
readConfigs();
if(configs.size()>2){
setEmailConfigs(configs.get(0),Integer.parseInt(configs.get(1)),configs.get(2),configs.get(3));
}
}
public void actionPerformed(ActionEvent e){
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
if(e.getActionCommand().equals("Send")){
String from=textfrom.getText();
if(textto.getText().length()>0)
Tos=textto.getText().split(", ");
if(textbcc.getText().length()>0)
Bccs=textbcc.getText().split(", ");
if(textcc.getText().length()>0)
Ccs=textcc.getText().split(", ");
String subject=textsubject.getText();
String message=textmessage.getText();
if(from.length()>0 && Tos.length>0 && subject.length()>0 && message.length()>0) {
Th th=new Th(from,Tos,Bccs,Ccs,subject,message);
th.start();
}
else{
JOptionPane.showMessageDialog(this,"From, To, Subject, and Message cannot be blank.");
textfrom.requestFocus();
}
}
else if(e.getActionCommand().equals("Attach")){
selectFile();
}
else if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
else if(e.getActionCommand().equals("Mail configure...")){
JPanel p=new JPanel(new GridLayout(5,1));
txtserver=new JTextField("Enter outgoing server");
txtport=new JTextField("Enter server port");
txtuser=new JTextField("Enter user name");
txtpwd=new JPasswordField("Enter password");
JButton bt=new JButton("Save and Close");
bt.addActionListener(this);
p.add(txtserver);
p.add(txtport);
p.add(txtuser);
p.add(txtpwd);
p.add(bt);
frame=new JFrame("Configure mail");
frame.getContentPane().add(p);
frame.setSize(300, 200);
frame.setVisible(true);
}
else if(e.getActionCommand().equals("Save and Close")){
saveConfigs();
frame.dispose();
}
}
class Th extends Thread{
String from;
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
String subject;
String message;
Th(String fromaddr,String[] toaddr,String[] bccaddr,String[] ccaddr,String subj,String mess){
from=fromaddr;
Tos=toaddr;
Bccs=bccaddr;
Ccs=ccaddr;
subject=subj;
message=mess;
lblstatus.setText("Sending the message");
}
public void run(){
sendEmail(from,Tos, Bccs,Ccs,subject, message);
email=null; //create object
lblstatus.setText("");
}
}
public void readConfigs(){
configs=new ArrayList<String>();
BufferedReader br=null;
try {
File f=new File("mailconfigs.con");
if(f.exists()){
FileReader fr=new FileReader(f);
br=new BufferedReader(fr);
String line="";
while((line=br.readLine())!=null){
configs.add(line);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null)
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void saveConfigs(){
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw = new FileWriter("mailconfigs.con");
bw=new BufferedWriter(fw);
bw.write(txtserver.getText());
bw.newLine();
bw.write(txtport.getText());
bw.newLine();
bw.write(txtuser.getText());
bw.newLine();
bw.write(encrypt(new String(txtpwd.getPassword())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null)
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String encrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]+101);
return(new String(sb));
}
public String decrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]-101);
return(new String(sb));
}
public void selectFile(){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
listmodel.addElement(file.getPath());
}
}
public void setEmailConfigs(String smtp,int port, String user, String password){
email = new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,decrypt(password));
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
}
public void sendEmail(String from, String[] Tos, String[] Bccs, String[] Ccs, String subject, String message){
configureMail();
if(email.getHostName().length()>0){
try {
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipients' (to) e-mail addresses
if(Tos!=null)
for(String Toadd:Tos)
email.addTo(Toadd);
//add recipients' (Bcc) e-mail addresses
if(Bccs!=null)
for(String Bccadd:Bccs)
email.addBcc(Bccadd);
//add recipients' (Cc) e-mail addresses
if(Ccs!=null)
for(String Ccadd:Ccs)
email.addCc(Ccadd);
//add file attachments
for(int i=0;i<listmodel.getSize();i++)
email.attach(new File(listmodel.get(i)));
//send the email
email.send();
}catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(this,"The email is not configured.");
}
}
}
public class EmailSender {
public static void main(String[] args){
new UI("E-Mail Sender");
}
}
|
|
|
Subscribe to:
Posts (Atom)





