Sunday, December 22, 2013

Applet application

Besides, desktop applications that run on operating systems, Java allows you to create applications that can be run on web browsers that enable Java or applet viewers. These types of applications are called applet applications. The java.applet package has Applet class that provides necessary support for applet applications.

Unlike desktop or stand-alone application, applet does not require the main method. The execution of the applet does not begin at the main method. Rather, Applet class provides different methods serving as the basic mechanism of executing an applet application on a web browser or applet viewer. These methods are init(), start(), paint(), stop(), and destroy(). When an applet begins, the init() methods is called. You can use this method to initialize variables. The init() method is called once. The start() method is called after the init() method. This method is called every time the applet's HTML page displays on the web browser. When the user leaves the HTML page that contains applet, the applet stops by calling the stop() method. When he/she comes back to that page, the start() method will be called again to resume the applet. The destroy() method will be called after the stop method to free up resources used by applet from memory. The paint method is called each time the applet needs to redraw its output. For example, the applet draw its output when it starts and it is minimized and restored.

Create an applet

To create an applet application, you will extend the Applet class in java.applet package. The following example code is a simple applet application to display an image and a button that can be clicked to change the background color of the applet's window. You need an image file called gmaptr.png.

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
/* 
<applet code="AppletApp" width=600 height=300> 
</applet> 
*/

public class AppletApp extends Applet implements ActionListener{

public void init(){
setSize(600,300);
setBackground(Color.LIGHT_GRAY);
Button bt=new Button("Change Color");
bt.setBackground(Color.PINK);
bt.addActionListener(this);
add(bt);

}

public void paint(Graphics g){
try {
MediaTracker mt=new MediaTracker(this);
URL imgurl=new URL(getCodeBase().toString()+"gmaptr.png");
Image img=getImage(imgurl);
mt.addImage(img,0);
mt.waitForID(0);
g.drawImage(img,10, 10,this);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showStatus("There are one button and one image on the applet window.");
}

public void actionPerformed(ActionEvent e){
Color c=getBackground();
if(c==Color.BLACK)
setBackground(Color.BLUE);
else

setBackground(Color.BLACK);
}
}


You need to create AppletApp.class file from the source code above. This can be done by compiling the source code with the javac command from command prompt.

Embed the applet in HTML file

In order to execute the applet on a web browser, you need to create an HTML file that includes the applet. You can include the applet within the HTML document by using the <applet> tag. Below is an example HTML file.

<!DOCTYPE html>
<html>
<head> <title>Applet Test</title>
</head>
<body>
<applet code="AppletApp" width=600 height=300>
</applet>
</body>

</html>

After you create the HTML file that contains applet, you can execute the applet by using the appletviewer tool that comes with JDK. The command line below will execute the AppletApp application in the appletviewer from command prompt.

D:\sitedemo\AppletApp\AppletTest\bin>appletviewer AppletApp.html


run applet from command prompt


If you are Eclipse user, you can execute the applet in the appletviewer from Eclipse by clicking the Run menu item.
Besides running the applet from command prompt and Eclipse, you can run the applet in a web browser that supports Java. You need to copy the AppleAppt.class, AppletApp.html, and other related files to a directory of your web server. Then run the HTML file as you do with other HTML, php, or jsp pages. In my machine i have Chrome browser and WampServer installed.


run applet from web browser


Thursday, December 5, 2013

XML processing in Java

XML and HTML are Markup Languages. However, they are different. XML is generally used to store and transport structured data while HTML is used to format and present the data. Today XML is the most common tool for data transmissions on the web. In XML file, you can define your own tags or elements starting from a root tag and then its children tags. Here is an example of an XML file:

xml file example


The root element is Books. Under the root element, there are two sub-elements or children elements Book.

This tutorial is designed for people who come to work with XML file in Java. After completing the tutorial, you will be able to create an XML document and save it to a file, read data from an XML file, and modify elements in the XML file by using JDOM library. With the JDOM libary, XML file can be easily created, read, and modified.

Create XML document and Save it to a file

To create an XML document, first you will use the Element class to create a root element object. Then create a document object by using the Document class to wrap the root object. A child element object can also be constructed by using the Element class and added to root element by using the addContent method. You can add many children to the root element. To save the XML document to a file, you will use the XMLOutputter class. The XMLOutputter class has a method called output that can be used to write the document to the file.  See the example code below:

public static void createXML(){
//create a root element
Element root=new Element("Books");
//construct the document object with the root
Document doc=new Document(new Element("Books"));
//create first child element
Element b1=new Element("Book");
b1.setAttribute("Title","C++ for beginners");
b1.addContent(new Element("Author").setText("Dara"));
b1.addContent(new Element("Year").setText("2011"));
//add the first child to the root
root.addContent(b1);

//create second child element
Element b2=new Element("Book");
b2.setAttribute("Title","Java for programmers");
b2.addContent(new Element("Author").setText("Dara"));
b2.addContent(new Element("Year").setText("2012"));
//add the second child to the root
root.addContent(b2);
//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
outputter.output(doc, new FileWriter("d:/books.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Read data from the XML file

Reading data from an XML file is a common task. This task can be accomplished easily by using JDOM. To read the data from the XML file, you will use SAXBuilder class to construct a document object from the XML file. After you have the document object, you can easily navigate through the document to access all its elements. Read the example code below:


public static void readXML(){
SAXBuilder builder=new SAXBuilder();
try {
//construct document object from the file books.xml
Document doc = (Document)builder.build(new File("d:/books.xml"));
//get the root element
Element root=doc.getRootElement();
//get all children of the root
List<Element> chs=root.getChildren();
for(Element e: chs){
System.out.println("Book:");
System.out.println("\t"+e.getChild("Author").getText());
System.out.println("\t"+e.getChild("Year").getText());
}

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Modify the data in the XML file

Before you can modify the data in the XML file, first you need to read the XML file in to a document object as you did in the previous section. Then you can add new children elements to the root, update data of an element, or delete an element from the document. After you complete the tasks, call the output method of the XMLOutputter class to save change to the file. Here is the example code.

public static void ModifyXML(){
SAXBuilder builder=new SAXBuilder();
try {
Document doc = (Document)builder.build(new File("d:/books.xml"));
Element root=doc.getRootElement();
//create third child element
Element b3=new Element("Book");
b3.setAttribute("Title","C# for beginners");
b3.addContent(new Element("Author").setText("Dara"));
b3.addContent(new Element("Year").setText("2013"));

//add the third child to the root
root.addContent(b3);

//Update the year of a book
List<Element> chs=root.getChildren();
for(Element e: chs){
Element ce=e.getChild("Year");
if(ce.getText().equals("2013")){
ce.setText("2010");
break;
}
}
//Remove a book that has the title "C# for beginners"
for(Element e: chs){
if(e.getAttribute("Title").getValue().endsWith("C# for beginners")){
root.removeContent(e);
break;
}

}

//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, new FileWriter("d:/books.xml"));

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

compass app flashLight app

Monday, November 18, 2013

Splash Screen

Splash screen is a special window that displays in a short time period before the main window of a program or website shows. Generally, on the splash screen, you will see an image that represents an introduction to the program or website. Sometimes, a splash screen displays a progress bar to inform the user about a process that is loading and might take a long time to complete. When the process completes, the splash screen disappears.

In Java, you can use the SplashScreen class (in awt package) to create a splash screen for your program. Alternatively, you can write your own code to create a splash screen. In this tutorial, i prefer to do the latter. First of all, you will have a class that extends the JFrame class. This class will represent the splash screen. In this tutorial, i name it as SimpleSplashScreen. The splash screen has no border and title. So will use the setUndecorated method to hide border and title. On the splash screen, there is an image that provides introductory information of the program. The JLabel component is used to wrap the image. Then it will be added on the splash screen to show the image. In the SimpleSplashScreen class, you need to add two methods. The first method (wait) allows the user to set the time delay of the splash screen. Another method (showScreen) will be invoked in the program to display the splash screen. Simply, when the time is out, the splash screen disappears and the Welcome window is shown.

splash screen

welcome


This is the complete code of the SplashScreen program.

import java.awt.Container;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

class SimpleSplashScreen extends JFrame{
int delay=2000; //default delay time 2 seconds
SimpleSplashScreen(String imgfile){
ImageIcon iicon=new ImageIcon(imgfile);
int iwidth=iicon.getIconWidth();
int iheight=iicon.getIconHeight();
setSize(iwidth,iheight);
setLocationRelativeTo(null);
setUndecorated(true);
Container cont=getContentPane();
JLabel lbl=new JLabel();
lbl.setIcon(iicon);
cont.add(lbl);
}
//set time delay
public void wait(int mills){
delay=mills;
}

public void showScreen(){
setVisible(true); //show the screen
try {
Thread.sleep(delay); //delay the screen
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//close the SplashScreen when time out
dispose();
new MaiInterface();
}
}

class MaiInterface extends JFrame{
MaiInterface(){
setSize(400,300);
setTitle("Your main interface here");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont=getContentPane();
JLabel lbl=new JLabel("Welcome");
lbl.setHorizontalAlignment(JLabel.CENTER);
lbl.setFont(new Font("Arial", Font.BOLD,30));
cont.add(lbl);
setVisible(true);
}
}
public class SplashSr {
public static void main(String[] args){
SimpleSplashScreen sss=new SimpleSplashScreen("d:/splashscreen.png");
sss.wait(5000);
sss.showScreen();
}
}

compass app flashLight app

Saturday, November 16, 2013

Open browser with Desktop class

Desktop is a useful class in Java. It can be used to open the default browser for a specified url, open a default mail client with optional e-mail address, open a file for editing or viewing, and send a file to the default printer.
To do such operatons mentioned above, first you need to create an object of the Desktop class by using the getDesktop method.

Desktop dt=Desktop.getDesktop();

To launch the default browser on your computer with a specified url, you will use the browse method. The browse method has one argument that is a uri object referencing to the url. To obtain the uri object, you have to create a url object that accepts the address of a web page. Then use the toURI method to convert the url object to uri object. The example code below will open the default browser and shows the http://javatheprogram.blogspot.com address on its address box.


open browser


import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

public class DesktopDemo {

public static void main(String args[]){
//openMail();
try {

URL url=new URL("http://javatheprogram.blogspot.com");
openBrowser(url.toURI());

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//openFile("d:/chart.pdf");

}


public static void openBrowser(URI uri){
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
try {

dt.browse(uri);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

You can launch an e-mail client program with your specified e-mail address by using the mail method. The mail method accepts one value that is the uri object. When you construct an url object to refer to an e-mail address, the string that will be passed to the URL constructor takes this form: "mailto:e-mail_addresss". The example below will open the e-mail client program with the e-mail address yuk.dara@gmail.com on you machine.

public static void openMail(){
try {
URL url=new URL("mailto:yuk.dara@gmail.com");
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
dt.mail(url.toURI());
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

To open a file on your local computer, you will use the open method. This method will take the file object that references to a file on your computer. The code below opens the test.txt file (in drive D) of the computer.

dt.open(new File("d://test.txt"));

If you wan to print the file to the default printer that connects to your computer, you can use the print method. This method also accepts the file object that you want to print. The following code will print the file chart.pdf to the default printer.

dt.print(new File("d:/chart.pdf"));

Tuesday, November 12, 2013

Robot in Java

Robot is an automation class in AWT package of Java. The Robot class is useful when your Java programs requires test automation, mouse, and keyboard controls. The frequently used methods of the Robot class are shown in the table below.

Method Description
createScreenCapture(Rectangle r) This method returns the image (BufferedImage object) of the captured screen. The dimension of the image is specified by the rectangle r argument.
delay(int mills) The delay method will delay the robot before an event occurs.
getPixelColor(int x,int y) The getPixelColor returns the color at the specified coordinate (x,y) on the screen.
keyPress(int key) This method tells the robot to press a key specified by the key argument. The KeyEvent class defines key constants that can be used in this method.
mouseMove(int x,int y) The mouseMove method will move the mouse pointer to the coordinate (x,y) on the screen.
mousePress(int buttons) This method tells the robot to press the mouse button. The value of buttons argument can be found in the InputEvent class.

In the example code below, the robot is commanded to move to the start button on the Task Bar of Window 7 and the mouse is clicked there. Then the word notepad are typed in the search box and the Enter key is pressed to open the NotePad application.

public class RobotDemo {
public static void main(String[] args){
try {
Robot r=new Robot();
//move to the start button on the Task Bar
r.mouseMove(20, (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
r.mousePress(InputEvent.BUTTON1_MASK); //press the left button
//type notepad in the search box
r.keyPress(KeyEvent.VK_N);
r.keyPress(KeyEvent.VK_O);
r.keyPress(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_E);
r.keyPress(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_D);
//delay the key pressed
r.delay(1000);
//press enter key
r.keyPress(KeyEvent.VK_ENTER);

} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



}


Another example is an easy screen capture program. To capture any part of the screen, you will drag the transparent capturing rectangle to a location on the screen where you want to capture. Then press the Enter key to capture the screen. In default, the captured area is 400 pixels wide (width) and 300 pixels long (height). If you wan to increase the dimension of the area to be captured, you will press the ] symbol key. Similarly, to decrease the dimension, simply press the [ symbol key. To minimize the transparent capturing rectangle, press the minus (-) key. When your work completes, you can press the ESC key to exit the program.
The images of the captured screen are saved in the current working directory of the program.

Robot screen capture



import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;

class InUI extends JFrame{
int wWin;
int hWin;
int xWin;
int yWin;
InUI(){

wWin=400;
hWin=300;
setSize(wWin,hWin);
Point loc=MouseInfo.getPointerInfo().getLocation();
xWin=loc.x;
yWin=loc.y;
setLocation(xWin,yWin);
addKeyListener(new KeyDetector());
addMouseMotionListener(new MouseMove());
setUndecorated(true);
setOpacity(0.7f);
Container cont=getContentPane();
cont.setLayout(new BorderLayout());
JLabel lbl=new JLabel("<html>Click and drag this capture area.<br>Press Enter to capture the screen.</html>");
lbl.setHorizontalAlignment(JLabel.CENTER);
cont.add(lbl, BorderLayout.CENTER);
setVisible(true);

}

class KeyDetector extends KeyAdapter{
public void keyPressed(KeyEvent e){
System.out.println(e.getKeyCode());
int code=e.getKeyCode();
if(code==27) //exit the program when the Esc key is pressed. 
System.exit(0);
else if(code==45) //minimize the capture
minimize();
else if(code==91) //decrease capture area
decreaseSize();
else if(code==93) //increase capture area
increaseSize();
else if(code==10){ //capture the screen when Enter key is pressed
minimize();
capture();
}
//else if((code==KeyEvent.VK_X) && (e.getModifiers() & KeyEvent.ALT_MASK)!=0 )
//System.exit(0);

}
}
class MouseMove extends MouseMotionAdapter{
public void mouseDragged(MouseEvent e){
//change location of the capture area when mouse is dragged
setWinLocation(e.getXOnScreen(),e.getYOnScreen());
}
}
public void increaseSize(){
Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();
if(wWin<ds.getWidth()){
wWin+=5;
this.setSize(wWin,hWin);
}
if(hWin<ds.getHeight()){
hWin+=5;
this.setSize(wWin,hWin);
}

}
public void decreaseSize(){
if(wWin>5){
wWin-=5;
this.setSize(wWin,hWin);
}
if(hWin>5){
hWin-=5;
this.setSize(wWin,hWin);
}
}
public void setWinLocation(int x,int y){
xWin=x-wWin/2;
yWin=y-wWin/2;
this.setLocation(new Point(xWin,yWin));
}
public void minimize(){
this.setExtendedState(JFrame.ICONIFIED);
}
public void capture(){
try {
Robot rb=new Robot();
//capture the target part of the screen
BufferedImage bi=rb.createScreenCapture(new Rectangle(xWin,yWin,wWin,hWin));
//save the image
ImageIO.write(bi, "png", new File(System.getProperty("user.dir")+File.separator+"image"+System.currentTimeMillis()+".png"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

public class RobotDemo {
public static void main(String[] args){
new InUI();
   }
}
compass app flashLight app

Monday, November 11, 2013

final class, variable, and method

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.

final keyword

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();

}


}

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.

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.

GridBagLayout


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);

}


}