Java Language provides two Graphical User Interface (GUI) packages.

  • java.awt
  • javax.swing

The java.awt package was the primary repository for classes that are used to create a GUI in java but many of the classes it defines have been superseded in Java 2 by javax.swing. However the Swing classes are generally derived from, and depend on, fundamental classes within java.awt, so these cant be ignored. Following picture describes class diagram of java.wt package.

Similarly, following picture depicts the class diagram of javax.swing package.

Components in swing package

A component represents a graphical entity of one kind or another that can be displayed on screen. All container and visual components inherit from java.awt.Component. There are some key Classes that are used frequently for example Window, JFrame, JDialog, JApplet etc.

Following are few examples that will describe how to create a GUI object in java.

Example:

// Create a button with text OK
Jbutton   jbtOK = new JButton("OK");

// Create a label with text "Enter your name: "
Jlabel    jlblName = new JLabel("Enter your name: ");

// Create a text field with text "Type Name Here"
JTextField   jtfName = new JTextField("Type Name Here");

// Create a check box with text bold
JCheckBox   jchkBold = new JCheckBox("Bold");

// Create a radio button with text red
JRadioButton   jrbRed = new JRadioButton("Red");

// Create a combo box with choices red, green, and blue
JComboBox jcboColor = new JComboBox(new String[]{"Red",  "Green", "Blue"});

Frames

Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications. The JFrame class can be used to create windows. For Swing GUI programs, use JFrame class to create widows.
Example:

import javax.swing.JFrame;
public class TryWindow {
  // The window object
  static JFrame aWindow = new JFrame("This is the Window Title");
  public static void main(String[] args) {
    int windowWidth = 400;             // Window width in pixels
    int windowHeight = 150;            // Window height in pixels
    // set position and size
   aWindow.setBounds(50, 100,windowWidth, windowHeight);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    aWindow.setVisible(true);          // Display the window
 }}


Another Example:

import javax.swing.*;
public class MyFrame {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Test Frame");
    frame.setSize(400, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(
      JFrame.EXIT_ON_CLOSE);
  }
   }

Adding Components into a Frame

// Add a button into the frame
frame.getContentPane().add(new JButton("OK"));

Methods for Components

There are several methods that are available for components

  •  setForeground( ) and setBackground( )
  • setFont( )
  • setEnabled( )
  • setSize( ) and setBounds( )
  • setVisible( )

Containers

The Container class is abstract and most commonly used concrete subclasses are JApplet, JFrame, JDialog and Panel. All the classes derived from the Container can contain other objects of the classes derived from Component. Swing provides containers such as

  • top level: frames, dialogs
  • intermediate level: panel, scroll pane, tabbed pane, …
  • other Swing components: buttons, labels, …

It uses a layout manager to position and size the components contained in them. Components are added to a container using one of the various forms of its add method depending on which layout manager is used by the container. For example, panel.add(component)

Top Level Containers

Every program that presents a Swing GUI contains at least one top-level container. A Top level container provides the support that Swing components need to perform their painting and event-handling. Swing provides three top-level containers:

  • JFrame (Main window)
  • JDialog (Secondary window)
  • JApplet (An applet display area within a browser window)

Layout Managers

Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. The UI components are placed in containers.  Each container has a layout manager to arrange the UI components within the container. Layout managers are set in containers using the setLayout(LayoutManager) method in a container. Java GUI reside in applets or in frames. There are several layout manager classes in the AWT and swing. java.awt.LayoutManager is an interface not a class. The Java platform supplies five commonly used layout managers:

Flow Layout Manager

It is the default layout manager for panels and applets. It always arranges the components in horizontal rows while honoring each components preferred size. The components always appear left to right in the order in which they were added to their container. Within every row the components are evenly spaced and the cluster of components is centered. To change this default behavior , you can use setLayout( )

  • setLayout needs a parameter of type object of Layout Manager
  • setLayout(new FlowLayout(FlowLayout.RIGHT))

By default it leaves a gap of 5 pixels between components in both horizontal and vertical directions.

Example

import javax.swing.Jframe;
import javax.swing.Jbutton;	import java.awt.Toolkit;
import java.awt.Dimension;	import java.awt.Container;
import java.awt.FlowLayout;
public class TryFlowLayout {
  // The window object
  static JFrame aWindow = new JFrame("This is a Flow Layout");
  public static void main(String[] args) {

    int windowWidth = 400;                              // Window width in pixels
    int windowHeight = 150;                             // Window height in pixels

   aWindow.setBounds(100, 100,                          // Set position
                      windowWidth, windowHeight);       // and size

    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FlowLayout flow = new FlowLayout();            // Create a layout manager
 Container  content = aWindow.getContentPane();  // Get the content pane
 content.setLayout(flow);                       // Set the container layout mgr
    // Now add six button components
    for(int i = 1; i <= 6; i++)
      content.add(new JButton("Press " + i));      // Add a Button to content pane
    aWindow.setVisible(true);                      // Display the window
  }
}

Border Layout Manager

It is the default layout manager for frames. It divides its territory in five regions, North, South, East, West and Center. Each region can contain at the most one component, It may be empty though. Its constructors are 

  • p.setLayout(new BorderLayout()); // Default is no gaps
  • p.setLayout(new BorderLayout(hgap, vgap);

A component at east or west extends vertically up to the bottom of the North component( if there is one) or to the top of the container( if there is no North component), similarly for south component. The border layout is not affected by the order in which you add the components. You can pass either a string like “North”, “Center” or you can use defined constants like BorderLayout.NORTH, BorderLayout.CENTER etc

Example:

public class MyBorder {
    static JFrame aWindow = new JFrame("This is the Window Title");

public static void main(String[] args) {
    int windowWidth = 400;                              // Window width in pixels
    int windowHeight = 150;                             // Window height in pixels
    aWindow.setBounds(50, 100, windowWidth, windowHeight);
  BorderLayout br = new BorderLayout(3,4);
  aWindow.setLayout(br);
  Container content = aWindow.getContentPane();
  content.add(new JButton("EAST"), BorderLayout.EAST);
  content.add(new JButton("WEST"), BorderLayout.WEST);
  content.add(new JButton("NORTH"), BorderLayout.NORTH);
  content.add(new JButton("SOUTH"), BorderLayout.SOUTH);
  content.add(new JButton("CENTER"), BorderLayout.CENTER);
  aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  aWindow.setVisible(true);
}
}

Grid Layout Manager

It always ignores a component’s preferred size. It divides the whole region into a matrix of rows and columns. The number of rows and columns are specified as parameters to the constructor. Every component in the applet in this case is exactly the same size and they appear in the order in which they are added from left to right row by row. They behave strangely if you put lesser components than number of rows times number of columns or more components. How?

Example:

GridLayout grid = new GridLayout(3,4,30,20); //Create layout manager
Container content = aWindow.getContentPane();//Get content pane
    content.setLayout(grid);        // Set the container layout mgr
JButton button;                     // Stores a button
    for(int i = 1; i <= 10; i++) {
      content.add(button = new JButton(" Press " + i));// Add a Button
      button.setBorder(edge);                          // Set the border
    }


HomeWork: using border layout

Related Posts

Tagged with: ClassesJAVAJAVA GUIObject Oriented
 

3 Responses to JAVA Graphical User Interface (GUI)

  1. shashank says:

    nice tutorials..best on the web…gr8 website…loved it

  2. [...] JAVA Graphical User Interface (GUI) | Java Programming … click here … [...]

  3. plzz help me i want to design a GUI based application with best UI,
    so what i need to do.???? help me plzzz

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds