Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

Graphical User Interface (GUI)

Graphical User Interface (GUI)

Unit Structure

11.1 GUI Components
11.2 Interface and Classes of AWT Package
11.2.1 Labels
11.2.2 Buttons
11.2.3 Check Boxes
11.2.4 Radio Button
11.2.5 Text Area
11.2.6 Text Field
11.2.7 Scrollbar
11.2.8 Panels
11.3 Layout managers 11.4 Methods of AWT

Introduction

A type of user interface item that allows people to interact with programs in more ways than typing such as computers and many hand-held devices such as mobile phones is called a graphical user interface (GUI) . A GUI offers graphical icons, and visual indicators, as opposed to text-based interfaces. This helps to develop more efficient programs that are easy to work with. The user can interact with the application without any problem.
The GUI application is created in three steps. These are:
 Add components to Container objects to make your GUI.
 Then you need to setup event handlers for the user interaction with GUI.
 Explicitly display the GUI for application.


11.1GUI Components

It is visual object and the user interacts with this object via a mouse or a keyboard. Components included, can be actually seen on the screen, such as, buttons, labels etc. Any operation that is common to all GUI components are found in class Component. Different components are available in the Java AWT (Abstract Window Toolkit )package for developing user interface for your program.

A class library is provided by the Java programming language which is known as Abstract Window Toolkit (AWT). The Abstract Window Toolkit (AWT) contains several graphical widgets which can be added and positioned to the display area with a layout manager.


AWT is a powerful concept in JAVA. AWT is basically used to develop for GUI application building. AWT is platform dependant. That means your .class file after the program compilation is platform independent but the look of your GUI application is platform dependant. AWT copies GUI component from local macines operating system. That means your applications look will differ in MAC operating system, as you have seen in WINDOWS operating system.



11.2 Interface and Classes of AWT Package:

Some of the Classes Interfaces of AWT package are explained below







Some of the AWT components are explained below.

11.2.1 Labels:

This is the simplest component of Java Abstract Window Toolkit. This component is generally used to show the text or string in your application and label never perform any type of action. Syntax for defining the label only and with justification:
Label label_name = new Label ("This is the label text.");
above code simply represents the text for the label.
Label label_name = new Label ("This is the label text. ‖ , Label.CENTER);
Justification of label can be left, right or centered. Above declaration used the center justification of the label using the Label.CENTER.
Example for Label.
import java.awt.*;
import java.applet.Applet;
/*<applet code="LabelTest" width=200 height=100>
</applet>
*/
public class LabelTest extends Applet
{
public void init()
{
add(new Label("A label"));
// right justify next label
add(new Label("Another label", Label.RIGHT));
}
}


  • Save the file as LabelTest. Java 
  • Compile the file using javac LabelTest.java 
  • On successful compilation, execute the file using appletviewer LabelTest.java

The output appers as shown in following figure :



11.2.2 Buttons:

This is the component of Java Abstract Window Toolkit and is used to trigger actions and other events required for your application. The syntax of defining the button is as follows:
Button button_name = new Button ("This is the label of the button.");
You can change the Button's label or get the label's text by using the Button.setLabel (String) and Button.getLabel () method. Buttons are added to its container using the, add (button_name) method.
Example for Buttons:-
import java.awt.*;
import java.applet.Applet;
/*<applet code="ButtonTest" width=200 height=100>
</applet>
* /
public class ButtonTest extends Applet
{
public void init()
{
Button button = new Button ("OK");
add (button);
}
}


  • Save the file as ButtonTest. Java 
  • Compile the file using javac ButtonTest.java 
  • On successful compilation, execute the file using appletviewer ButtonTest.java

The output appers as shown in following figure :


Note that in the above example there is no event handling added; pressing the button will not do anything.

11.2.3 Check Boxes:

This component of Java AWT allows you to create check boxes in your applications. The syntax of the definition of Checkbox is as follows:
Checkbox checkbox_name = new Checkbox ("Optional check box 1", false);
Above code constructs the unchecked Checkbox by passing the boolean valued argument false with the Checkbox label through the Checkbox() constructor. Defined Checkbox is added to its container using add (checkbox_name) method. You can change and get the checkbox's label using the setLabel (String) and getLabel () method. You can also set and get the state of the checkbox using the setState (boolean) and getState () method provided by the Checkbox class.
Example for Check Boxes:-
import java.awt.*;
import java.applet.Applet;
/*<applet code="CheckboxTest" width=200 height=100>
</applet>
*
public class CheckboxTest extends Applet
{
public void init()
{
Checkbox m = new Checkbox ("Allow Mixed Case");
add (m);
}
}


  • Save the file as CheckboxTest. Java 
  • Compile the file using javac CheckboxTest.java 
  • On successful compilation, execute the file using appletviewer CheckboxTest.java

The output appers as shown in following figure :



11.2.4 Radio Button:

Radio buttons are a bunch of option boxes in a group. Only one of then can be checked at a time. This is useful if you need to give the user a few options where only one will apply. This is the special case of the Checkbox component of Java AWT package. This is used as a group of checkboxes whos group name is same. Only one Checkbox from a Checkbox Group can be selected at a time.
Syntax for creating radio buttons is as follows:
CheckboxGroup chkboxgp = new CheckboxGroup ();
add (new Checkbox ("chkboxname", chkboxgp, value);
―Value‖ in the second statement can only be true or false.If you mention more than one true valued for checkboxes then your program takes the last true and shows the last check box as checked.
Example for Radio Buttons.
import java.awt.*;
import java.applet.Applet;
/*<applet code="Rbutton" width=200 height=100>
</applet>
*/
public class Rbutton extends Applet
{
public void init()
{
CheckboxGroup chkgp = new CheckboxGroup ();
add (new Checkbox ("One", chkgp, false));
add (new Checkbox ("Two", chkgp, false));
add (new Checkbox ("Three",chkgp, false));
}
}
In the above code we are making three check boxes with the label "One", "Two" and "Three".


  • Save the file as Rbutton. Java 
  • Compile the file using javac Rbutton.java 
  • On successful compilation, execute the file using appletviewer Rbutton.java

The output appers as shown in following figure :



11.2.5 Text Area:

This is the text container component of Java AWT package. The Text Area contains plain text. TextArea can be declared as follows:
TextArea txtArea_name = new TextArea ();
You can make the Text Area editable or not using the setEditable (boolean) method. If you pass the boolean valued argument false then the text area will be non-editable otherwise it will be editable. The text area is by default in editable mode. Texts are set in the text area using the setText (string) method of the TextArea class.
Example for Text Area:-
import java.awt.*;
import java.applet.Applet;
/*<applet code="TAreaTest" width=200 height=100>
</applet>
*/
public class TAreaTest extends Applet
{
TextArea disp;
public void init()
{
disp = new TextArea("Code goes here", 10, 30);
add (disp);
}
}


  • Save the file as TAreaTest. Java 
  • Compile the file using javac TAreaTest.java 
  • On successful compilation, execute the file using appletviewer TAreaTest.java

The output appers as shown in following figure :





11.2.6 Text Field:

This is also the text container component of Java AWT package. This component contains single line and limited text information. This is declared as follows:
TextField txtfield = new TextField (20);
You can fix the number of columns in the text field by specifying the number in the constructor. In the above code we have fixed the number of columns to 20.
A displayed label object is known as the Label. Most of the times label is used to demonstrate the significance of the other parts of the GUI. It helps to display the functioning of the next text field. A label is also restricted to a single line of text as a button.
Example for Text Field:-
import java.awt.*;
import java.applet.Applet;
/*<applet code="TFieldTest" width=200 height=100>
</applet>
*/
public class TFieldTest extends Applet
{
public void init()
{
TextField f1 =
new TextField("type something");
add(f1);
}
}


  • Save the file as TFieldTest. Java 
  • Compile the file using javac TFieldTest.java 
  • On successful compilation, execute the file using appletviewer TFieldTest.java

The output appers as shown in following figure :



11.2.7 Scrollbar:-

Scrollbar is represented by a "slider" widget. The characteristics of it are specified by integer values which are being set at the time of scrollbar construction. Both the types of Sliders are available i.e. horizontal and vertical. The example below shows the code for the scrollbar construction. The subtraction of scrollbar width from the maximum setting gives the maximum value of the Scrollbar. In the program code, '0' is the <<<<<<< scrollbar.shtml initial value of the scrollbar, '8' is the width of the scrollbar.
Example for Scrollbar
import java.awt.*;
import java.applet.Applet;
/*<applet code="ScrollbarDemo" width=200 height=100> </applet> */
public class ScrollbarDemo extends Applet {
public void init() {
Scrollbar sb = new Scrollbar (Scrollbar.VERTICAL, 0, 8, -100, 100);
add(sb);
}
}


  • Save the file as ScrollbarDemo. Java 
  • Compile the file using javac ScrollbarDemo.java 
  • On successful compilation, execute the file using appletviewer ScrollbarDemo.java

The output appers as shown in following figure :




11.2.8 Panels

A panel is an object which holds other objects. It‘s just a container to organize and arrange your GUI better. Once, you learn about Layout Managers you‘ll see why panels are a useful tool. For now, just know that they‘re useful. Here‘s an example of a set of buttons added into a panel:
Panel myPanel = new Panel();
myPanel.add(helloButton);
myPanel.add(goodbyeButton);
add(myPanel);
It looks no different than if you just added the buttons regularly, but you‘ll see why you might want to use panels later on... This is what it looks like:



11.3 Layout managers

The layout manager are a set of classes that implement the java.AWT.LayoutManager interface and help to position the components in a container. The interface takes a task of laying out the child components in the container. The task is achieved by resizing and moving the child components. The advantages of this type of mechanism is that when the container is resized the layout manager automatically updates the interface
The basic layout managers includes:
1) FlowLayout : It is a simple layout manager that works like a word processor. It is also the default Layout manager for the panel. The flow layout lays out components linewise from left to right.
FlowLaout can be created using following constructors
a. FlowLaout() : Constructs a new layout with centered alignment, leaving a vertical and horizontal gap.
b. FlowLayout(int aling, int vgap, int hgap) : Constructs a new flowlayout with the alignment specified, leaving a vertical and horizontal gap as specified.
Various methods can be used alog with the flow layout. For eg.
getAlignment(), getHgap(), getAlignment(int align) etc.
Example for Flow Layout
import java.awt.*;
import java.awt.event.*;
class FlowDemo extends Frame
{
Button b1 = new Button("one");
Button b2 = new Button("two");
public FlowDemo(String s)
{
super(s);
setSize(400,400);
setLayout(new FlowLayout(FlowLayout.LEFT));
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
add(b1);
add(b2);
}
public static void main(String arg[])
{
Frame f=new Frame();
f.show();
}
}



  • Save the file as FlowDemo. Java 
  • Compile the file using javac FlowDemo.java 
  • On successful compilation, execute the file using java FlowDemo.java

2) Grid Layout : It lays out components in a way very similar to spredsheet(rows and columns). Specifying the number of rows and columns in grid creates the Grid layout.

Grid Layout can be created using following constructors
a. GridLayout() : Creates a grid layout with a default of one column per component in a single row.
b. GridLayout(int rows, int cols, int hgap, int vgap) : Creates a grid layout with the specified rows and columns and specified horizontal and vertical gaps.
Various methods can be used alog with the Grid layout. For eg.
getColumns(), getRows(), geHgap(), getVgap() etc.
Example for Grid Layout
import java.applet.Applet;
import java.awt.*;
public class Grid1 extends Applet {
LayoutManager Layout;
Button [] Buttons;
public Grid1 () {
int i;
Layout = new GridLayout (3, 2);
setLayout (Layout);
Buttons = new Button [5];
for (i = 0; i < 5; ++i) {
Buttons[i] = new Button ();
Buttons[i].setLabel ("Button " + (i + 1));
add (Buttons[i]);
}
}
}


  • Save the file as Grid1. Java 
  • Compile the file using javac Grid1.java 
  • On successful compilation, execute the file using appletviewer Grid1.java

The output appers as shown in following figure :


3) BorderLayout : It is the class that enables specification, i.e. where on the border of container each component should be placed. All areas need not be filled. The size of the areas will depend on the components they contain.

Border Layout can be created using following constructors
a. BorderLayout() : It creates a new border layout with no gap between the components.
b. BorderLayout(int hgap, int vgap) : It creates a border layout with the specified horizontal and vertical gap between components.
Various methods can be used alog with the Border layout. For eg.
getHgap(), getVgap(), setHgap(int hgap), setVgap(int vgap)
Example for Border Layout
import java.awt.*;
import java.applet.*;
import java.util.*;
/*<applet code="BorderDemo" width=300 height=100>
</applet>
*/
public class BorderDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add(new Button("This across the top"),BorderLayout.NORTH);
add(new Button("The Footer message might go here"),BorderLayout.SOUTH);
add(new Button("Right"),BorderLayout.EAST);
add(new Button("Left"),BorderLayout.WEST);
String msg=" This is border layout";
add(new TextArea(msg),BorderLayout.CENTER);
add(new Button("new"),BorderLayout.CENTER);
}
}


  • Save the file as BorderDemo. Java 
  • Compile the file using javac BorderDemo.java 
  • On successful compilation, execute the file using appletviewer BorderDemo.java

The output appers as shown in following figure :



11.4 Methods of AWT:-

The common methods of AWT components are as follow:
getLocation () - This method is used to get position of the component, as a Point. The usage of the method is shown below.
Point p = someComponent.getLocation ();
int x = p.x;
int y = p.y;
the x and y parts of the location can be easily accessed by using getX () and getY (). It is always efficient to use getX () and getY () methods. For example,
int x = someComponent.getX();
int y = someComponent.getY();

getLocationOnScreen () - This method is used to get the position of the upper-left corner of the screen of the component, as a Point. The usage of the method is shown below. Point p = someComponent.getLocationOnScreen ();

int x = p.x;
int y = p.y;
It is always advisable to use getLocation () method (if working on Java 2 platform).

getBounds () - This method is used to get the current bounding Rectangle of component. The usage of the method is shown below.

Rectangle r = someComponent.getBounds ();
int height = r.height;
 int width = r.width;
int x = r.x;
int y = r.y;
if you need a Rectangle object then the efficient way is to use getX (), getY(), getWidth(), and getHeight() methods.

getSize () - This method is used to get the current size of component, as a Dimension. The usage of the method is shown below.

Dimension d = someComponent.getSize ();
int height = d.height;
int width = d.width;
use getWidth () and getHeight () methods to directly access the width and height. You can also use getSize () if you require a Dimension object.
For Example,int height = someComponent.getHeight();
int width = someComponent.getWidth();

setBackground(Color)/setForeground(Color) - This method is used to change the background/foreground colors of the component


setFont (Font) - This method is used to change the font of text within a component.


setVisible (boolean) - This method is used for the visibility state of the component. The component appears on the screen if setVisible () is set to true and if it‘s set to false then the component will not appear on the screen. Furthermore, if we mark the component as not visible then the component will disappear while reserving its space in the GUI.


setEnabled (boolean) - This method is used to toggle the state of the component. The component will appear if set to true and it will also react to the user. ON the contrary, if set to false then the component will not appear hence no user interaction will be there. As discussed earlier a container is a component that can be nested. The most widely used Panel is the Class Panel which can be extended further to partition GUIs. There is a Panel which is used for running the programs. This Panel is known as Class Applet which is used for running the programs within the Browser.


Common Container Methods:- All the subclasses of the Container class inherit the behavior of more than 50 common methods of Container. These subclasses of the container mostly override the method of component. Some of the methods of container which are most widely used are as follow:

getComponents ();
add();
getComponentCount();
getComponent(int);

ScrollPane:-

The ScrollPane container provides an automatic scrolling of any larger component introduced with the 1.1 release of the Java Runtime Environment (JRE). Any image which is bigger in size for the display area or a bunch of spreadsheet cells is considered as a large object. Moreover there is no LayoutManager for a ScrollPane because only a single object exists within it. However, the mechanism of Event Handling is being managed for scrolling.

The example below shows the Scrollpane. This scrollpane demonstrates the scrolling of the large image. In the program code below, first of all we have created a scrollpane by creating its object, and then we have passed the parameter of image in it. We have also set the border layout as centre, as shown.



Example for Scroll Pane


import java.awt.*;

import java.applet.*;
/*<applet code="ScrollingImageDemo" width=200 height=100>
</applet>*/
class Scrollpane extends Component {
private Image image;
public Scrollpane(Image m) {
 image = m;
}
public void paint(Graphics g) {
if (image != null)
g.drawImage(image, 0, 0, this);
}
}
public class ScrollingImageDemo extends Applet {
public void init(){
setLayout(new BorderLayout());
ScrollPane SC = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
Image mg = getImage(getCodeBase(), "cute-puppy.gif");
SC.add(new Scrollpane(mg));
add(SC, BorderLayout.CENTER);
}
}




  • Save the file as ScrollingImageDemo. Java 
  • Compile the file using javac ScrollingImageDemo.java 
  • On successful compilation, execute the file using appletviewer ScrollingImageDemo.java

The output appers as shown in following figure :




No comments:

Post a Comment