Academic Tutorials



English | French | Portugese | German | Italian
Google

Home Source Codes E-Books Downloads Contact Us About Us

Java Tutorial
Java Introduction
Object Oriented Programming Concepts
Anatomy of a Java Application
Syntax and Semantics of Java
Java Objects, Classes, and Interfaces
The String and StringBuffer Classes in Java
Setting Program Attributes in Java
Using System Resources in Java
Threads of Control in Java
Errors and Exceptions in Java
Java Input and Output Streams
Overview of Java Applet
Creating an Applet User Interface in Java
Communicating with Other Programs in Java
Overview of the Java UI
Using GUI Building Blocks in Java
Laying Out Components within a Container
Working with Graphics in Java
How Java Differs from C and C++
Java Summary

HTML Tutorials
HTML Tutorial
XHTML Tutorial
CSS Tutorial
TCP/IP Tutorial
XML Tutorials
XML Tutorial
XSL Tutorial
XSLT Tutorial
DTD Tutorial
Schema Tutorial
XForms Tutorial
XSL-FO Tutorial
XML DOM Tutorial
XLink Tutorial
XQuery Tutorial
XPath Tutorial
XPointer Tutorial
RDF Tutorial
SOAP Tutorial
WSDL Tutorial
RSS Tutorial
WAP Tutorial
Web Services Tutorial
Browser Scripting
JavaScript Tutorial
VBScript Tutorial
AJAX Tutorial
DHTML Tutorial
HTML DOM Tutorial
WMLScript Tutorial
E4X Tutorial
Server Scripting
ASP Tutorial
PHP Tutorial
PERL Tutorial
SQL Tutorial
ADO Tutorial
.NET (dotnet)
Microsoft.Net
XML Web Services
ASP.Net
.Net Mobile
C# : C Sharp
ADO.NET
VB.NET
Multimedia
SVG Tutorial
Flash Tutorial
Media Tutorial
SMIL Tutorial
Web Building
Web Browsers
Web Hosting
W3C Tutorial
Web Building
Web Quality
Web Semantic
Web Careers
Java Tutorials
Java Tutorial
JSP Tutorial
Servlets Tutorial
Struts Tutorial
EJB Tutorial
JMS Tutorial
JMX Tutorial
Programming Langauges
C Tutorial
C++ Tutorial
Visual Basic Tutorial
Data Structures Using C
Soft Skills
Communication Skills
Time Management
Project Management
Team Work
Leadership Skills
Corporate Communication
Negotiation Skills


Using GUI Building Blocks in Java

Previous Next



Before you start using the components, you should know what the Component class will provide and how can you customize the components. Then will tell how to use the components which the AWT provides. Each kind of the component has its own page:




How to Use the Buttons

The Buttons class do provides a default button implementation. The onscreen appearance of the Buttons depends on a platform they are running on. If you want the program's buttons to look same for all platform or otherwise to have a special look, you should create a Canvas subclass to implement this look; the look can't be changed using the Button subclass. The only facets of Button's appearance that we can change without creating our own class are the fonts and text it displays and the foreground and background colors.

Below is an applet which displays three buttons. When you click the left button, it disables middle button and enables the right one. Similarly when you on click the right button, it will enable the left button and the middle button , and it disables itself. Below is the code which will create the buttons and reacts to the button clicks.

//In initialization code:
b1 = new Button();
b1.setLabel("Disable middle button");

b2 = new Button("Middle button");

b3 = new Button("Enable middle button");
b3.disable();

public boolean handleEvent(Event e)
{
Object target = e.target;

System.out.println("Event received: " + e);
if (e.id == Event.ACTION_EVENT)
{
if (target == b1)
{
b2.disable();
b1.disable();
b3.enable();
} else if (target == b3)
{
b2.enable();
b1.enable();
b3.disable();
}
}
return super.handleEvent(e);
}




How to Use the Canvases

A Canvas class exist to be subclassed. It will not do anything on its own; it merely provides the way to implement the custom Components. For example, The Canvases are useful as a display area for images and the custom graphics, whether or not you wish to handle the events that occurs within a display area.

While implementing a Canvas subclass. do take care to implement the minimumSize() and the preferredSize() method to properly reflect the canvas's size. Otherwise, depending on the layout which the canvas's container uses, your canvas could end up too small -- perhaps even be invisible. Here is an example of the Canvas subclass that displays the image:

class ImageCanvas extends Canvas
{
ImageCanvas(Image img, Dimension prefSize)
{
image = img;
preferredSize = prefSize;
}

public Dimension minimumSize()
{
return preferredSize;
}

public Dimension preferredSize()
{
return preferredSize;
}

public void paint(Graphics g)
{
g.drawImage(image, 0, 0, this);
}
}




How to Use the Checkboxes

The Checkbox class provides the checkboxes -- two-state buttons which can either be "on" or "off". If we want the group of checkboxes in which only one of the checkbox can be "on" at a time, you can add the CheckboxGroup object to oversee the checkboxes. Other good ways of providing a group of items the user can select are the choices, lists, and menus.

Given below is code for an applet that contains two columns of checkboxes. On the left are three independent checkboxes. You can select all the three checkboxes, if you like to. On the right are the three checkboxes which are coordinated by the CheckboxGroup object. The CheckboxGroup ensures no more than one of its checkboxes is selected at a time. Here is the program which performs this task. Below is the code that creates both the groups of checkboxes. Note: only the second, mutually-exclusive group of checkboxes is controlled by the CheckboxGroup.

Panel p1, p2;
Checkbox cb1, cb2, cb3; //independent checkboxes
Checkbox cb4, cb5, cb6; //only one of these three can be selected
CheckboxGroup cbg;

cb1 = new Checkbox();
cb1.setLabel("Checkbox 1");
cb2 = new Checkbox("Checkbox 2");
cb3 = new Checkbox("Checkbox 3");
cb3.setState(true);

. . . cbg = new CheckboxGroup();
cb4 = new Checkbox("Checkbox 4", cbg, false);
cb5 = new Checkbox("Checkbox 5", cbg, false);
cb6 = new Checkbox("Checkbox 6", cbg, false);




How to Use the Choices

Choice class provides a menu-like list of choices, accessed by the distinctive button. User presses the button to bring up the "menu", and later chooses one of the items from the menu list. Another name for this UI element is the "pop-up list". Other ways of providing the multiple alternatives are checkboxes, lists, and menus.

Below is an applet code which has a Choice and Label. When the user chooses item from the Choice list, the Label changes to reflect an item chosen This code creates the Choice and handles the events from it. Note: that the second parameter to action() method is a string from the selected item.

//...Where instance variables are defined:
Choice choice; //pop-up list of choices

//...Where initialization occurs:
choice = new Choice();
choice.addItem("ichi");
choice.addItem("ni");
choice.addItem("san");
choice.addItem("shi");
label = new Label();
setLabelText(choice.getSelectedIndex(), choice.getSelectedItem());

. . . public boolean action(Event e, Object arg)
{
if (e.target instanceof Choice)
{
setLabelText(choice.getSelectedIndex(), (String)arg);
return true;
}
return false;
}
}




How to Use the Dialogs

The thing that distinguishes dialogs from regular windows (that are implemented with Frame objects) is that the dialog is dependent on some other window (i'e Frame). When this other window is destroyed, and so are its dependent dialogs. When that other window is been iconified, its dependent dialogs will disappear from the screen. When the window is been deiconified, its dependent dialogs return to the screen. The AWT automatically provides this behavior to us.

Since no API currently do exists to let the applets find the window they are running in, applets generally cannot use dialogs. The exception is the applets that bring up their own windows can have the dialogs dependent on those windows. For this reason, the following applet consists of the button that brings up window which brings up a dialog. Here is the code for the window which the applet brings up. This code can be run as an standalone application or, with the help of AppletButton class, as an applet Here is the code that deals with the Dialog object:

//[HOW DO I MAKE THIS GET THE FOCUS?]
class SimpleDialog extends Dialog
{
private TextField field;
private DialogWindow parent;
private Button setButton;

SimpleDialog(Frame dw, String title)
{
super(dw, title, false);
parent = (DialogWindow)dw;

//Create and add components, such as the set button....

resize(350, 125);
}

public boolean action(Event event, Object arg)
{
if ( (event.target == setButton)
| (event.target instanceof TextField))
{
parent.setText(field.getText());
}
field.selectAll();
hide();
return true;
}
}




How to Use the Frames

The Frame class provides the windows for applets and applications. Every application needs atleast one Frame. If an application has the window that should be dependent on another window -- disappearing when other window is iconified, for example -- then you should use the Dialog instead of Frame for the dependent window. (Unfortunately, applets cannot use the dialogs currently well, so they need to use the frames.)

Below is a code for the menu demonstration uses to create the window and handle the case where the user closes window.

public class MenuWindow extends Frame
{
private boolean inAnApplet = true;
private TextArea output;

public MenuWindow()
{
//This constructor implicitly calls the Frame no-argument
//constructor and then adds components to the window.
}

public boolean handleEvent(Event event)
{
if (event.id == Event.WINDOW_DESTROY)
{
if (inAnApplet)
{
dispose();
} else
{
System.exit(0);
}
}
return super.handleEvent(event);
}

. . .

public static void main(String args[])
{
MenuWindow window = new MenuWindow();
window.inAnApplet = false;

window.setTitle("MenuWindow Application");
window.resize(250, 90);
window.show();
}
}




How to Use the Labels

Label class provides an easy way for putting uneditable, unselectable text into the program's GUI. The labels are aligned to the left of their drawing area, by default. we can specify that they be centered or right-aligned by specifying the Label.CENTER or by Label.RIGHT either to Label constructor or to setAlignment() method. As with every Component, you can also do specify the font and color of the Label.

Given below are the applets that use labels. The first applet (LabelDemo) simply creates three labels with a default (left) alignment, puts them in the GridLayout, and then displays them. Here is the code for LabelDemo.

import java.awt.*;
import java.applet.Applet;

public class LabelDemo extends Applet
{

public void init()
{
Label l1 = new Label();
l1.setText("Label 1");

Label l2 = new Label("Label 2");

Label l3 = new Label("Label 3");

//Add Components to the Applet.
setLayout(new GridLayout(0, 1));
add(l1);
add(l2);
add(l3);

validate();
}
}

The second applet (LabelAlignDemo) does same, except that it make use of all three possible alignments. Since the applet is wider than necessary to display the text, and because the GridLayout uses all the available space, Labels have the wider display area than they need. This results in the visible difference in a horizontal position of the three differently aligned labels.

import java.awt.*;
import java.applet.Applet;

public class LabelAlignDemo extends Applet
{

public void init()
{
Label l1 = new Label();
l1.setText("Left");
Label l2 = new Label("Center");
l2.setAlignment(Label.CENTER);
Label l3 = new Label("Right", Label.RIGHT);

//Add Components to the Applet.
setLayout(new GridLayout(0, 1));
add(l1);
add(l2);
add(l3);

validate();
}
}

Below is a code that LabelAlignDemo uses to create the labels and set their alignment. For the purpose of teaching, this applet uses all the three Label constructors.

Label l1 = new Label();
l1.setText("Left");
Label l2 = new Label("Center");
l2.setAlignment(Label.CENTER);
Label l3 = new Label("Right", Label.RIGHT);




How to Use the Lists

List class provides the scrollable area containing the selectable text items (one for each line). Lists can allow either a multiple selections or only one selection at a time. Other components that allows the users to choose from the multiple selections are checkboxes (checkbox groups particularly), choices, and menus.

Below is code for an applet that shows two lists. The first list (which lists out the Spanish numbers) allows multiple selections. The second list (which lists the Italian numbers) allows a maximum of one selection. Below is a code which creates each list and handles events on the list. Note : the e.arg data for action events is the name of an acted-on item (similar to argument for action events on other components such as buttons and the menus). However, e.arg data for other list events is a number of acted-on item.

//where instance variables are declared:
TextArea output;
List spanish, italian;

//where initialization occurs:

//Build first list, which allows multiple selections.
spanish = new List(4, true); //prefer 4 items visible
spanish.addItem("uno");
spanish.addItem("dos");
spanish.addItem("tres");
spanish.addItem("cuatro");
spanish.addItem("cinco");
spanish.addItem("seis");
spanish.addItem("siete");

//Build second list, which allows one selection at a time.
italian = new List(); //Defaults to none visible, only one selectable
italian.addItem("uno");
italian.addItem("due");
italian.addItem("tre");
italian.addItem("quattro");
italian.addItem("cinque");
italian.addItem("sei");
italian.addItem("sette");

. . .

public boolean handleEvent(Event e)
{
if (e.target instanceof List)
{
List list = (List)(e.target);
String language = (list == spanish) ?
"Spanish" : "Italian";

switch (e.id)
{
case Event.ACTION_EVENT:
String string = (String)e.arg;
output.appendText("Action event occurred on \""
+ string + "\" in "
+ language + ".\n");
break;
case Event.LIST_SELECT:
int sIndex = ((Integer)e.arg).intValue();
output.appendText("Select event occurred on item #"
+ sIndex + " (\""
+ list.getItem(sIndex) + "\") in "
+ language + ".\n");
break;
case Event.LIST_DESELECT:
int dIndex = ((Integer)e.arg).intValue();
output.appendText("Deselect event occurred on item #"
+ dIndex + " (\""
+ list.getItem(dIndex) + "\") in "
+ language + ".\n");
}
}
return super.handleEvent(e);
}




How to Use the Menus

The applet given above shows many of the menu features we are likely to use. The window it brings up has menu bar which contains four menus. Each menu contains one or more than one items. Menu 1 is a tear-off menu; by clicking a dashed line [implementation-specific?], we create a new window which contains same menu items as the Menu 1. Menu 2's only item has a checkbox. Menu 3 contains the separator between its second and the third items. Menu 4 is a window's help menu, which (depending on a platform) generally means that it is set off to the right. When we click on any menu items, the window displays the string indicating which item has been clicked and what menu it is in.

Here is the code for the window which the above applet brings up. This code can run as an standalone application or, with the help of an AppletButton class, as an applet. Here is the code that deals with menus:

public MenuWindow()
{
MenuBar mb;
Menu m1, m2, m3, m4;
MenuItem mi1_1, mi1_2, mi3_1, mi3_2, mi3_3, mi3_4, mi4_1, mi4_2;
CheckboxMenuItem mi2_1;

// ...Add the output displayer to this window...

//Build the menu bar.
mb = new MenuBar();
setMenuBar(mb);

//Build first menu in the menu bar.
m1 = new Menu("Menu 1", true);
mb.add(m1);
mi1_1 = new MenuItem("Menu Item 1_1");
m1.add(mi1_1);
mi1_2 = new MenuItem("Menu Item 1_2");
m1.add(mi1_2);

//Build help menu. Note that order in which it's added doesn't matter.
m4 = new Menu("Menu 4");
mb.add(m4); //Just setting the help menu doesn't work; must add it.
mb.setHelpMenu(m4);
mi4_1 = new MenuItem("Menu Item 4_1");
m4.add(mi4_1);
mi4_2 = new MenuItem("Menu Item 4_2");
m4.add(mi4_2);

//Build second menu in the menu bar.
m2 = new Menu("Menu 2");
mb.add(m2);
mi2_1 = new CheckboxMenuItem("Menu Item 2_1");
m2.add(mi2_1);

//Build third menu in the menu bar.
m3 = new Menu("Menu 3");
mb.add(m3);
mi3_1 = new MenuItem("Menu Item 3_1");
m3.add(mi3_1);
mi3_2 = new MenuItem("Menu Item 3_2");
m3.add(mi3_2);
m3.addSeparator();
mi3_3 = new MenuItem("Menu Item 3_3");
m3.add(mi3_3);
mi3_4 = new MenuItem("Menu Item 3_4");
mi3_4.disable();
m3.add(mi3_4);
}
public boolean action(Event event, Object arg)
{
String str = "Action detected";

if (event.target instanceof MenuItem)
{
MenuItem mi=(MenuItem)(event.target);
str += " on " + arg;
v if (mi instanceof CheckboxMenuItem)
{
str += " (state is "
+ ((CheckboxMenuItem)mi).getState()
+ ")";
}
MenuContainer parent = mi.getParent();
if (parent instanceof Menu)
{
str += " in " + ((Menu)parent).getLabel();
} else
{
str += " in a container that isn't a Menu";
}
}
str += ".\n";
//...Display string in the output area...
return false;
}




How to Use the Panels
Panel p1 = new Panel();
p1.add(new Button("Button 1"));
p1.add(new Button("Button 2"));
p1.add(new Button("Button 3"));




How to Use the Scrollbars
public boolean handleEvent(Event evt)
{
switch (evt.id)
{
case Event.SCROLL_LINE_UP:
case Event.SCROLL_LINE_DOWN:
case Event.SCROLL_PAGE_UP:
case Event.SCROLL_PAGE_DOWN:
case Event.SCROLL_ABSOLUTE:
if (evt.target == vert)
{
canvas.ty = ((Integer)evt.arg).intValue();
canvas.repaint();
}
if (evt.target == horz)
{
canvas.tx = ((Integer)evt.arg).intValue();
canvas.repaint();
}
}
return super.handleEvent(evt);
}




How to Use the TextAreas and TextFields
//Where instance variables are defined:
TextField textField;
TextArea textArea;

public void init()
{ textField = new TextField(20);
textArea = new TextArea(5, 20);
textArea.setEditable(false);

...//Add the two components to the panel.
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.ACTION_EVENT)
{
String text = textField.getText();
textArea.appendText(text + "\n");
textField.selectAll();
}
return super.handleEvent(evt);
}




Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb

Previous Next

Keywords: JoltBeans.


HTML Quizes
HTML Quiz
XHTML Quiz
CSS Quiz
TCP/IP Quiz
XML Quizes
XML Quiz
XSL Quiz
XSLT Quiz
DTD Quiz
Schema Quiz
XForms Quiz
XSL-FO Quiz
XML DOM Quiz
XLink Quiz
XQuery Quiz
XPath Quiz
XPointer Quiz
RDF Quiz
SOAP Quiz
WSDL Quiz
RSS Quiz
WAP Quiz
Web Services Quiz
Browser Scripting Quizes
JavaScript Quiz
VBScript Quiz
AJAX Quiz
DHTML Quiz
HTML DOM Quiz
WMLScript Quiz
E4X Quiz
Server Scripting Quizes
ASP Quiz
PHP Quiz
PERL Quiz
SQL Quiz
ADO Quiz
.NET (dotnet) Quizes
Microsoft.Net Quiz
XML Web Services Quiz
ASP.Net Quiz
.Net Mobile Quiz
C# : C Sharp Quiz
ADO.NET Quiz
VB.NET Quiz
Multimedia Quizes
SVG Quiz
Flash Quiz
Media Quiz
SMIL Quiz
Web Building  Quizes
Web Browsers Quiz
Web Hosting Quiz
W3C Quiz
Web Building Quiz
Web Quality Quiz
Web Semantic Quiz
Web Careers Quiz
Java Quizes
Java Quiz
JSP Quiz
Servlets Quiz
Struts Quiz
EJB Quiz
JMS Quiz
JMX Quiz
Programming Langauges Quizes
C Quiz
C++ Quiz
Visual Basic Quiz
Data Structures Using C Quiz
Soft Skills Quizes
Communication Skills Quiz
Time Management Quiz
Project Management Quiz
Team Work Quiz
Leadership Skills Quiz
Corporate Communication Quiz
Negotiation Skills Quiz

Privacy Policy
Copyright © 2003-2008 Vyom Technosoft Pvt. Ltd., All Rights Reserved.