0% found this document useful (0 votes)
8 views32 pages

AWT and Swing GUI Components Overview

The document provides an overview of the Abstract Window Toolkit (AWT) and Swing in Java, detailing various user interface components such as labels, buttons, panels, and dialogs. It explains the class hierarchy, including the Component and Container classes, and discusses the functionality of key components like Frame and Dialog. Additionally, it covers the construction and methods of various AWT controls, including TextFields, TextAreas, and Buttons.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

AWT and Swing GUI Components Overview

The document provides an overview of the Abstract Window Toolkit (AWT) and Swing in Java, detailing various user interface components such as labels, buttons, panels, and dialogs. It explains the class hierarchy, including the Component and Container classes, and discusses the functionality of key components like Frame and Dialog. Additionally, it covers the construction and methods of various AWT controls, including TextFields, TextAreas, and Buttons.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-4

The AWT class hierarchy, user interface


components labels,button, canvas, scrollbars,
text components, check box, checkbox groups,
choices, Lists panels – scroll pane, dialogs,
menu bar, graphics, layout manager – layout
manager types – border, grid, flow,card, and
grid bag.

Swing – Introduction, limitations of AWT,


MVC architecture, Components, containers,
exploring swing- JApplet, JFrame and
JComponent, Icons and Labels, text
fields,buttons, The JButton class, Check
boxes, Radio buttons, Comboboxes, Tabbed
Panes, Scroll Panes, Trees, and Tables.

Page1
Introduction to AWT:
 AWT class:
 AWT means Abstract Window Toolkit. AWT is a library of classes which
provides GUI tools to develop GUI applications and applets.
 AWT is an object-oriented GUI framework.
 AWT classes are contained in [Link] package.
 It contains many classes and methods that allow you to create and manage
windows and provides machine independent interface for applications.
 AWT is one of the largest packages.
 AWT contains classes that can be extended and their properties can be
inherited, and also be abstract.
 Every GUI component must be a subclass of object class in [Link]
package.
 AWT is used to build the graphical user interface with standard windowing
elements.
 GUI= Graphical User Interface

Page2
 Component Class
 It is the base class for all AWT and Swing components.
 It defines many basic methods inherited by all components.
 A component is an object having a graphical representation that
can be displayed on the screen and that can interact with the user.
 Examples of components are the buttons, checkboxes, and
scrollbars of a typical graphical user interface.
 The Component class is the abstract superclass of the non menu
related Abstract Window Toolkit components.
 Class Component can also be extended directly to create a
lightweight component.
 A lightweight component is a component that is not associated
with a native window. On the contrary, a heavyweight component
is associated with a native window. The isLightweight() method
may be used to distinguish between the two kinds of the
components.
 Lightweight and heavyweight components may be mixed in a
single component hierarchy. However, for correct operating of
such a mixed hierarchy of components, the whole hierarchy must
be valid. When the hierarchy gets invalidated, like after changing
the bounds of components, or adding/removing components
to/from containers, the whole hierarchy must be validated
afterwards by means of the [Link]() method invoked
on the top-most invalid container of the hierarchy

Page3
 Container Class
• To use AWT components in a program, you must contain them.
• The Container class is a subclass of the component class that is used to
define components that have the capability to contain other components.
• It provides methods for adding, retrieving, displaying, counting and removing
the components that it contains.
There are two basic types of container:
1) Window class
2) Panel class
1) Window class: this class creates popup windows separate from the main
program. It has two subclasses

Frame(window that have a border and a menu bar)


Dialog (a special window used in applications to select a file)

2) Panel class: A container that represents a series of an existing window.


 The applet class is a container that is a subclass of the panel class.
 You can place components directly on applet panel or use additional panel
objects to subdivide the applet into smaller sections.
• By default component are added to container in left to right and top to bottom.

Windows Fundamental
• The AWT defines windows according to a class hierarchy that adds
functionality and specificity with each level. A window provides a top level
window on the screen, with no borders or menu bar.
• Two most common windows are derived from
• Panel, which is used by applets

Page4
• Frame, which creates a standard window.
• The window class provides an encapsulation of a generic window object.
• It is sub classed by Frame and Dialog to provide capabilities needed to
support application main windows and Dialog box.
• Default Layout for window is BorderLayout.
• A window is top level display area exists outside the browser or applet area
you are working on. It has no borders, window title, or menu bat that a typical
window manager might provide. Frame is a subclass that adds these parts
borders, window title.
• Constructor:
public Window (Frame parent)
When parent is minimized, Window is also minimized. So we must create
Frame before we create a Window. For applet you can pass null parameter
(because there is no need to access Frame),this is one way to create Dialog.

• Window class appearance method:


1. public void pack():resizes the window to preferred size the components
contains.
2. public void show() : displays the window, first call to this method generates
Window Event with Id WINDOW_OPENED.
3. public void dispose(): releases the resources of the window by hiding it and
removing its peer. Calling this method generates Window Event with Id
WINDOW_CLOSED.
4. public void toFront() : brings the window to foreground of the display.
5. public void toBack() : puts the window in back ground of the display.
6. public void boolean isShowing() : returns true if the window is visible on
the screen.

Window class events:


WINDOW_DESTROY,
WINDOW_EXPOSE,
WINDOW_ICONIFY,
WINDOW_DEICONIFY,
WINDOW_MOVED

 Panel class:
• Panel is the basic building block of an applet. It provides a container with no
special features.
• The panel class is a subclass of Container class that is used to organize GUI
components within other container objects.
• It has single constructor that takes no parameters.

Page5
• The Applet class of the java. applet package is a subclass of the Panel class.
• The default layout for a Panel object is Flow Layout.
• A panel container is not visible when it is added to an applet. It is to provide a
way to organize components in a window.
• By default component are added to container in left to right and top to bottom.

Panel p=new Panel( );


//creates Panel class’s object
Label l=new Label(“ok”);
[Link]( l );
//add control to panel object
add(p);
//add panel object to container

 Frame class:
• The frame class is used to provide the main window of an application. it may
also include menu bar.
• It is a subclass of Window that supports the capabilities to specify the icon,
cursor, Menu bar, and title.
• It implements MenuContainer interface so it can work with Menu bar object.
• Default layout is Border [Link] provides basic building block for
screen oriented applications.
• Frame constructor:
1. public Frame( ): creates a hidden window with a window title of “untitled”
or an empty string.
Frame f1=new Frame( );

2. public Frame(String title): creates a hidden window but sets the window
title to title.
Frame f1=new Frame(“My frame”);
[Link]( true);
//it displays frame in output
[Link]( 300, 400);
//width and height of frame
• Frame allows you to change the mouse cursor, set an icon image, and have
menus. Frame is a special type of window that looks like other high level
programs in your windowing environment.
• Frame class defines 14 constants that are used to specify different types of
cursors to be used within the frame.
public final static int DEFAULT_CURSOR
public final static int CROSSHAIR_CURSOR

Page6
public final static int TEXT_CURSOR
public final static int WAIT_CURSOR
public final static int SW_RESIZE_CURSOR
public final static int SE_RESIZE_CURSOR
public final static int NW_RESIZE_CURSOR
public final static int NE_RESIZE_CURSOR
public final static int N_RESIZE_CURSOR
public final static int S_RESIZE_CURSOR
public final static int E_RESIZE_CURSOR
public final static int W_RESIZE_CURSOR
public final static int HAND_CURSOR
public final static int MOVE_CURSOR
• Frame methods:
1. public String getTitle(): get title of frame object
2. public String setTitle(String title): set title for frame object
3. public Image getIconImage():Returns the image to be displayed as the icon
for this frame.
4. public Image setIconImage(): it sets image icon to be displayed
5. public MenuBar getMenuBar():Gets the menu bar for this frame.
6. public Syncronized void setMenuBar():it sets the menu bar for this frame.
7. public Syncronized void remove(Menucomponent):Removes the specified
menu bar from this frame.
8. public Syncronized void dispose():
9. public boolean isResizable():Indicates whether this frame is resizable by the
user.
[Link] boolean setResizable(boolean resizable):it set resizable or not.
[Link] int getCursorType():it returns current cursor type

11. Frame
import [Link].*;
public class FrameExample {
public static void main(String[] args) {
Frame frame = new Frame("Simple Frame");
[Link](300, 300);
[Link](true);
}
}

Page7
 Dialog class
• Dialog class is a subclass of the window class that is used to implement
dialog box windows.
• A dialog box is a window that takes input from the [Link] layout is a
default layout.
• A dialog is a popup used for user interaction; it can be modal to prevent the
user from doing anything either the application before responding.
• These classes provide handful access methods, which are used to get and sets
title, determine whether it is modal, and get and set the dialog box’s resizable
properties.
• Dialog class provides a special window that is normally used for pop up
messages or input from the user.
• Constructor:
1. public Dialog(Frame parent)
2. public Dialog(Frame parent , String title)
3. public Dialog(Frame parent ,String title , boolean modal)
• Methods:
1. String getTitle() :Gets the title of the dialog.
2. void hide(): to hide dialog box
3. boolean isModal() :Indicates whether the dialog is modal.
4. boolean isResizable() :Indicates whether this dialog is resizable by the user.
5. protected String paramString() :Returns a string representing the state of this
dialog.
6. void setResizable(boolean resizable) :Sets whether this dialog is resizable by
the user.
7. void setTitle(String title) :Sets the title of the Dialog.
8. void setVisible(boolean b) :Shows or hides this Dialog depending on the
value of parameter b.
9. void show():dispays dialog
[Link] toBack() :If this Window is visible, sends this Window to the back and
may cause it to lose focus or activation if it is the focused or active Window.

Page8
 Canvas class
• The canvas component is a section of a window used primarily as a place to
draw graphics or display images.
• Canvas is more similar to a container however Canvas component can’t be
used as a place to put components.
• Canvas class implements a GUI objects that supports drawing.
• Drawing is not implemented on the canvas itself, but on Graphics object
provided by the canvas.
• It provides single parameter constructor and paint ( ) method.
Example:
import [Link].*;
public class CanvasExample {
public static void main(String[] args) {
Frame frame = new Frame("Canvas Example");
Canvas canvas = new Canvas();
[Link]([Link]);
[Link](50, 100, 200, 100);

[Link](canvas);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
 AWT controls:
• Label
• TextField
• TextArea
• Buttons
• Checkboxes
• CheckboxGroup
• ChoiceList
• Scrolling lists
• Scrollbars
• Menus
1) Label
• Labels are component that are used to display text in a container which cant
be edited
by user.
• They are generally used to guide the user to perform correct actions on the
user

Page9
interface, also used for naming other components in the container.
Label l1=new Label (“name”);
add (l1);
• Label constructor:
1) Label( ) :creates an empty label, with its text aligned to left.
2) Label(String):creates label with given text, aligned left.
3) Label(String ,int) :creates a label with given text string and given alignment
value.(0 is Label. LEFT , 1 is Label. RIGHT ,2 is Label. CENTER)
Methods:
1. getText() :it returns a string containing this label’s text.
2. setText(String) : it set a new text of label
3. GetAlignment( ):it returns an integer value representing the alignment of
label (0 is
[Link] , 1 is Label. RIGHT ,2 is Label. CENTER )
5. SetAlignment(int) : changes the alignment of this label to the given integer
value (0,1 or 2)

Example :
import [Link].*;
public class LabelExample {
public static void main(String[] args) {
Frame frame = new Frame("Label Example");
Label label = new Label("Hello AWT Label");
[Link](50, 100, 150, 30);
[Link](label);
[Link](250, 250);
[Link](null);
[Link](true);
}
}
2) TextFields
• TextFields is used for inserting a single line of text.
• It creates an empty text field with an unspecified number of columns.
TextField t1=new TextField (8);
add(t);
• TextFields Constructors:
1) TextField( ):creates an empty textfield is 0 character wide.
2) TextField(int):creates empty text field. Integer argument defines no. Of
characters
to display.
3) TextField(String):creates a text fields initialized with given string.

Page10
4) TextField(String ,int):creates a text field some number of characters wide.
Methods:
• getText( ) :Returns text contained in text field
• setText (String) :Puts the text in text fields
• getColumns( ) :Returns width of this text field
• select(int, int) :Selects text between two integer positions(starts from 0)
• selectAll( ) :Selects all text in the field
• isEditable ( ) :Returns true or false based on whether text is editable.
• setEditable(boolean): True enables text to be edited, false freezes the text
• getEchoChar( ) :Returns character used for making input.

Example
import [Link].*;
public class TextFieldExample {
public static void main(String[] args) {
Frame frame = new Frame("TextField Example");
TextField tf = new TextField();
[Link](50, 100, 150, 30);
[Link](tf);
[Link](250, 250);
[Link](null);
[Link](true);
}
}
3) TextArea
• Creates an empty text area with an unspecified number of rows and columns.
• The number of rows and columns are specified as parameters to the
constructor
• It provides the capability to set the text to read-only or edit mode.
TextArea t=new TextArea(5,20);
Add(t);
• TextArea constructor:
1. TextArea():creates an empty text area 0 rows long and 0 characters wide.
1. TextArea(int, int):creates an empty text area with given number of rows
and columns
2. TextArea(String):creates a text area displaying the given string.
3. TextArea(String, int, int):creates a text area displaying the given string and
with given dimensions
TextArea t=new TextArea(“hi \n hello”,10,25);
Methods:
1. getColumns( ) :returns the width of the text area, in characters or columns

Page11
2. getRows( ):returns the number of rows in the text area
3. insertText(String,int) :inserts the string at the given position in the text
4. replaceText(String,int,int):replaces the text between the given integer
positions with the new string

Example :
import [Link].*;
public class TextAreaExample {
public static void main(String[] args) {
Frame frame = new Frame("TextArea Example");
TextArea ta = new TextArea();
[Link](50, 100, 200, 100);
[Link](ta);
[Link](300, 300);
[Link](null);
[Link](true);
}
}

4) Button
• Button component is used to trigger events in GUI.
• It is rectangular button that can be clicked with a mouse.
• Buttons are easy to manage and make the interface presentable.
• Button constructor:
1. Button( ): creates an empty button with no label
2. Button(String) :creates a button with the given string object as a label.
Button b=new Button(“ok”);
Add(b);
 Once you have button object ,you can get the value of the button’s label by
getLabel(
)method and set the label using setLabel( ).
We can add button in panel using following code:
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
Frame frame = new Frame("Button Example");
Button button = new Button("Click Me");
[Link](50, 100, 80, 30);
[Link](button);
[Link](200, 200);
[Link](null);

Page12
[Link](true);
}
}
5) Checkboxes
• A check box is a used to control in an application or a web page.
• A check box has two parts ,a lable and a state
• Label text is text that represents the caption of the control
• The state is a boolean value that represents the status of check boxes whether
checked or [Link] default the state is false, means checkbox is
unchecked.
• Checkbox constructor:
1. Checkbox( ) :creates an empty checkbox ,unselected
2. Checkbox(String) :creates a checkbox with the given string as a label.
3. Checkbox(String ,null, boolean) :creates a checkbox that is either selected
or unselected based on whether the boolean argument is true or false
Syntax:
Checkbox ch1=new Checkbox("pen");
add(ch1);
Methods:
1. getLabel( ) : returns a string containing checkbox’s label
2. setLable(String): changes the text of the check box’s label
3. getState()
:returns true or false, based on whether the check box is selected
4. setState(boolean): changes the check box’s state to selected (true) ot
unselected (false)

Example :
import [Link].*;
public class CheckboxExample {
public static void main(String[] args) {
Frame frame = new Frame("Checkbox Example");
Checkbox cb = new Checkbox("Accept Terms");
[Link](50, 100, 150, 30);
[Link](cb);
[Link](250, 250);
[Link](null);
[Link](true);
}
}

Page13
6) CheckBoxGroup
• CheckBoxGroup class is used with the Checkbox class to implement radio
buttons.
• All Checkbox objects associated with CheckBoxGroup object are treated as
a single set of radio buttons.
• Only one button in group may be set or on at a given point in time.
• CheckboxGroup constructor: it provides a single parameter less constructor.
• We can get and set CheckboxGroup object.
Checkbox ch1=new Checkbox("male");
[Link](cbg);
[Link](false);
add(ch1);

Example :
import [Link].*;
public class CheckboxGroupExample {
public static void main(String[] args) {
Frame frame = new Frame("CheckboxGroup Example");
CheckboxGroup group = new CheckboxGroup();

Checkbox cb1 = new Checkbox("Male", group, false);


[Link](50, 100, 100, 30);

Checkbox cb2 = new Checkbox("Female", group, false);


[Link](50, 140, 100, 30);

[Link](cb1);
[Link](cb2);
[Link](250, 250);
[Link](null);
[Link](true);
}
}

7) ChoiceList
• Choice class is used to implement pull-down lists that can be placed in the
main area of a window.
• These lists are known as option menus or a pop-up menu of choices.
• It is a pop up list of strings from which ha single string can be selected. It
enables selection of one Item at a time.

Page14
Choice c=new Choice();
[Link](“bhuj”);
[Link](“rajkot”);
add(c);
Methods:
1. getItem(int): returns the string item at given position (items inside a choice
begin at [Link] like arrays)
2. countItems( ):returns the number of items in the menu
3. select(int) : select the item at the given position
4. Select(string):select the item with the given string
5. getSelectedIndex( ): returns the index position of the item selected
6. getSelectedItem( ): returns the currently selected item as a string

8) Scrolling List
• The List class implements single and multiple selection list GUI controls.
• A list box is similar control to a choice list, however unlike choice menu; a
list control allows the user to select multiple values in the list as the same time.
• One or more string can be selected at same time.
• Scrolling List constructor:
1) List( ) :creates an empty scrolling list that enables only one selection at a
time.
2) List(int, boolean):creates a scrolling list with the given number of visible
lines on the screen. integer argument defines no. Of element to be displayed on
screen and boolean specifies whether list enables multiple choice or not.
Methods:
1. void add(String item) :Adds the specified item to the end of scrolling list.
2. void add(String item, int index) :Adds the specified item to the the scrolling
list at the position indicated by the index.
3. void addActionListener(ActionListener l) :Adds the specified action listener
to receive action events from this list.
4. void addItem(String item)
5. void addItem(String item, int index)
6. boolean allowsMultipleSelections() :set to select multiple selections
7. int countItems() : count no. of items in list
8. String getItem(int index) :Gets the item associated with the specified index.
9. int getItemCount() :Gets the number of items in the list.
[Link][] getItemListeners() :Returns an array of all the item listeners
registered on this list.
[Link][] getItems() :Gets the items in the list.
[Link] getSelectedIndex() :Gets the index of the selected item on the list,
[Link][] getSelectedIndexes() :Gets the selected indexes on the list.

Page15
[Link] getSelectedItem() :Gets the selected item on this scrolling list.
[Link][] getSelectedItems() :Gets the selected items on this scrolling list.
[Link] isSelected(int index) :checks item is selected or not
[Link] remove(int position) :Removes the item at the specified position from
this scrolling list.
[Link] remove(String item) :Removes the first occurrence of an item from the
list.
[Link] removeAll() :Removes all items from this list.
[Link] select(int index) :Selects the item at the specified index in the scrolling
list.

9) Scroll Bars
• Scrollbar is used to implement vertical and horizontal scrollbars.
• Scrollbar component is up-down or left-right slider that can be used to set a
numeric [Link] can use scrollbar by clicking mouse or an arrow or by
grabbing the box on the slider.
• Scrollbar constructor:
1. scrollbar():creates scrollbar with its initial maximum and minimum value
0,in vertical .
2. scrollbar(int):creates scrollbar with its initial maximum and minimum value
0,the argument can be set to scrollbar. HORIZONTAL or [Link].
3. Scrollbar(int orientation, int intial, int overallwidth, int min, int max ):
First argument: orientation of the scroll bat scrollbar. HORIZONTAL or
scrollbar. VERTICAL.
Second argument: initial value of scroll bar ,which should be a value between
scrollbar ‘s minimum & maximum value. Third argument: overall width (or
height) fourth and fifth: scrollbar. Minimum and maximum value for the scroll
bar.
Methods:
1. getMinimum( ): Gets the minimum value of this scroll bar
2. getMaximum( ): Gets the maximum value of this scroll bar
3. getOrientation( ) : Returns the orientation of this scroll bar, 0 for Horizontal
1 for vertical
4. getValue():Gets the current value of this scroll bar
5. setValue() : setts the new value of this scroll bar
6. setLineIncrement() : sets value of the scrollbar is changed when
incrementing in line mode
7. getLineIncrement():gets value of the scrollbar is changed when incrementing
in line mode
8. setPageIncrement(int c): sets value of the scrollbar when incrementing in
page modedefault is 10

Page16
9. getPageIncrement():sets value of the scrollbar when incrementing in page
mode.

10) Menus
• A menu is component of AWT but it is different from other components
because it can’t be added to ordinary container and laid out by layout manager.
• Menu can be added only to a menu container. Top level window can have
menu bar which display list of top level menu choices and each choice is
associated with a dropdown menu.
MenuBar
• A MenuBar component is a horizontal menu in which contains on more Menu
objects.
• It can only be added to Frame object.
• It forms the root of all menu trees.
 A Frame can display only one MenuBar at a time.
 The Menu Bar does not support any listener.
MenuBar Constructor:
- MenuBar ( ): to create default MenuBar.
Menu:
 A menu component provides a basic pull down menu.
 It can be added either to a menu bar or to another Menu.
 Menus are used to display and control Menu items.
Menu Constructor:
1. Menu () : to create default menu.
2. Menu (String str): str specifies name of the menu selection
3. Menu(String str, Boolean flag):flag shows popup menu if set true it can be
removed and allowed to float free.
MenuItem
 MenuItem component are text leaf nodes of a menu tree.
 MenuItem are added to a Menu.
 An actionListener can be added to a MenuItem Object.
MenuItem constructor:
1. MenuItem () :create s a default constructor
2. MenuItem (String str) : str is the name shown in the menu.
3. MenuItem (String str,MenuShortcut key ):key is shortcut key for that
MenuItem.
CheckboxMenuItem
• It is checkable menu item, which provides selection (on or off) listed in
menus.
• It can be controlled by the ItemListener interface.
CheckboxMenuItem constructor:

Page17
1. CheckboxMenuItem() :
2. CheckboxMenuItem(String str):
3. CheckboxMenuItem(String str, boolean flag)
import [Link].*;
public class MenuExample {
public static void main(String[] args) {
Frame frame = new Frame("Menu Example");
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("File");

[Link](new MenuItem("New"));
[Link](new MenuItem("Open"));
[Link](new MenuItem("Exit"));

[Link](menu);
[Link](menuBar);
[Link](300, 300);
[Link](true);
}
}
 Layout Manager
• There's no guarantee that a textbox or any component will be the same size on
each platform.
• Sun Microsystems has created a Layout Manager interface that defines
methods to reformat the screen based on the current layout and component
sizes.
• Layout manager try to give a consistent and reasonable appearance
regardless of platform, the screen size, or actions the user might take.
• It determines that how awt components are dynamically arranged on the
screen.
• Layout manager is an object that is used to organize components in container.
• Every container has default layout manager.
• As soon as you create container java automatically creates and assigns layout
manager to it.

Page18
1. Flow Layout (default Layout)
 It is default layout for applets and Panels.
 It places controls in the order in which they are added, linearly, from left to
right and from top to bottom in horizontal and vertical rows.
 We can align components to left, right or center.
 Components are normally centered in applet.
 When the layout manager reaches the right border of the container (means
row is full then), it positions the components in the next row.
 If you resize an applet, the components flow will change based upon the
new width and height.
To create flow Layout :
FlowLayout f1=new FlowLayout();
FlowLayout f2=new FlowLayout([Link]);
FlowLayout f3=new FlowLayout([Link],10,30);
setLayout(f1)

FlowLayout
import [Link].*;
public class FlowLayoutOnly {
public static void main(String[] args) {
Frame frame = new Frame("FlowLayout Only");
[Link](new FlowLayout());
[Link](300, 100);
[Link](true);
}
}

Page19
2. Grid Layout:
• The Grid layout class puts each component into a place on a grid that is equal
in size to all the other places.
• The grid is given specific dimensions when created; Components are added to
the grid in order, starting with upper-left corner to right.
• Components are given equal amounts of space in the container.
• Grid layout is widely used for arranging components in rows and columns.
• However unlike, Flow Layout, here underlying components are resized to fill
the row-column area. if possible.
• Grid Layout can reposition objects after adding or removing components.
Whenever
area is resized, components are also resized.
GridLayout b1=new GridLayout(4,1);
// 4 rows and 1 column
setLayout(b1)

import [Link].*;
public class GridLayoutOnly {
public static void main(String[] args) {
Frame frame = new Frame("GridLayout Only");
[Link](new GridLayout(2, 3));
[Link](300, 150);
[Link](true);
}
}
3. Border Layout
• Border layout is the default layout manager for all window, dialog and frame
class.
• In Border layout ,components are added to the edges of the container ,the
center area is allotted all the space that’s left over.
• Border layout ,provides five areas to hold component:
Four border north, south, east, west Remaining space: center
• When you add a component to the layout you must Specify which area to
place it in.
• The order in which components are added to the screen is not important.
Although you have only one component in each area.
BorderLayout b1=new BorderLayout ();
setLayout (b1);
add (bt1,[Link]);
add(bt2,[Link]);

Page20
import [Link].*;
public class BorderLayoutOnly {
public static void main(String[] args) {
Frame frame = new Frame("BorderLayout Only");
[Link](new BorderLayout());
[Link](300, 200);
[Link](true);
}
}

4. Card Layout
• Card layout class is a special type of layout organizer.
• A card layout manages several components, displaying one of them at a time
and hiding the rest.
• All the components are given same size, Usually Card Layout manages a
group of panels and each panel contains several component of its own.
• It doesn’t display several panels concurrently but it creates a stack of panels
that can then be displayed one at a time, as stack of cards in solitaire game.
• Card Layout allows you to assign names to the components it is managing
and lets you jump to a component by name.
• Card Layout class has its own methods that are used to control which panel is
displayed. Clicking on applet area causes the Layout manager to goes the next
panel.

import [Link].*;
public class CardLayoutOnly {
public static void main(String[] args) {
Frame frame = new Frame("CardLayout Only");
[Link](new CardLayout());
[Link](300, 200);
[Link](true);
}
}

5. GridBag Layout
• GridBagLayout class provides a grid for components like GridLayout, but
allows a single component element to occupy multiple cells of the grid.
• Each GridBagLayout uses a rectangular grid of cells, just like a GridLayout.

Page21
• Cells are determined and shaped by the component placed in them rather than
components being shaped to fir the cells.
• Cells in grid are not required to take up same amount if space and
components can be aligned in different ways in each grid cell.
• GridBagLayout constructor is trivial, with no arguments.
GridBagLayout gb=new GridBagLayout();
• Unlike GridLayout ( ) constructor, this constructor does not specify the
number of rows or columns.
Rows and columns are added as required (starts from 0.)
• You will need access to the GridBagLayout object later in the applet when
you add components to the container.

GridBagConstraints objects
• GridBagConstraints object specifies the location and area of the components
display area within the container, and how they are laid out inside its display
area.
GridBagConstraints gbc=new GridBagConstraints();

import [Link].*;
public class GridBagLayoutOnly {
public static void main(String[] args) {
Frame frame = new Frame("GridBagLayout Only");
[Link](new GridBagLayout());
[Link](300, 200);
[Link](true);
}
}

 Swing
 Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
 Swing is a set of classes that provide more powerful and flexible components
than AWT.
 Swing provides familiar components like buttons, checkbox and label and
also adds new components like tabbed pane, scroll panes, tree and tables.
 In swing button may have both an image and a text string associated with it.
the image can be changed as the state of the button changes.
 The swing related classes are contained in [Link] and its sub packages.

Page22
 The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.

The swing component classes are as follow:


1. JApplet
2. JLabel
3. JTextField
4. JButton
5. JCheckBox
7. JComboBox
8. JtabbedPane
9. JMenus

1. JApplet :
 Fundamental of Swing is JApplet class, which extends Applet.
 Applets that use Swing must be subclasses of JApplet,do.
 JApplet is rich with functionality .It supports various “panes”,such as content

Page23
pane,glass pane and root pane.
 When adding a component to an instance of JApplet,do not invoke the add( )
method of the [Link] call add( )for content pane of the JApplet object.
 We can obtain content pane using getContentPane( ) method.
 The add( ) method of container can be used to add a component to content
pane. void add (component) //component which you want to add

2. JLabel:
 Swing labels are instances of JLabel class. which extends JComponenets.
 It can display text and or icon.
 Constructor of JLabel
1. JLabel( Icon i)
2. JLabel(String s)
3. JLabel(String s, Icon I,int align)
Align is either LEFT,RIGHT,CENTER,LEADING or TRAILING.
 Methods:
1. Icon getIcon( )
2. String getText( )
3. void setIcon( )
4. void setText( )
3. JTextField:
 Swing text field is encapsulated by JTextComponent class, which extends
JComponent.
 It provides functionality that is common to Swing text Components. One of
its sub class is JTextField,which allows you to edit one line of text.
 Constructor
1. JTextField( )
2. JTextField(int cols)
3. JTextField(String s,int cols)
4. JTextField(String s)
4. JButton:
 Swing buttons provide features that are not found in the Button class defined
by the
AWT.
 Swing buttons are subclasses of AbstractButton class which extends
JComponent.
 AbstractButton is a super class for push buttons, checkboxes and radio
buttons. It
contains many methods that allow you to control the behaviour of buttons,
checkboxes

Page24
and radio buttons.
 Concrete subclasses of AbstractButton generate action events when they are
pressed.
Method used for even handling are,
void addActionListener( ActionListener l)
void removeActionListener(ActionListener al)
 Methods for Button
1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the
action listener to this object.

 JButton class provides the functionality of a push [Link] allows an


icon,a string or both to be associated with the push button.
 Constructor for JButton:
1. JButton(Icon i)
2. JButton(String s)
3. JButton(String s,Icon i) //s and i are the string and icon used for the button.

Example:
import [Link].*;
public class ImageButton
{
ImageButton()
{
JFrame f=new JFrame();
[Link](130,100,100, 40);
[Link](b);
[Link](300,400);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ImageButton();
}

Page25
}

 JCheckBox
 JCheckBox class which provides the functionality of a check box, is a
subclass of
AbstractButton [Link] immediate superclass is JToggleButton.
 It supports two states true or false.
 We can associate an icon, string, or the state with the checkbox.
 JCheckBox constructors:
1. JCheckBox(Icon c)
2. JCheckBox(Icon c,boolean state)
3. JCheckBox(String s)
4. JCheckBox(String s,boolean state)
5. JCheckBox(String s,Icon i)
6. JCheckBox(String s,Icon c,boolean state)
Here, i is the icon for the button.s is text to be [Link] state is true,the
checkbox is initially selected else not.
 The state of the check box can be changed via following method:
void setSelected(boolean state)
 When a check box is selected or deselected ,an item event is [Link]
is handled by itemStateChanged( ).
 The getItem( ) method is used to get JCheckBox object that generated the
event.
 The getText( ) method gets the text for that check box and text inside the
text field.
 To select only one you have to create a object of ButtonGroup class and
add all components in the object.
Example :
import [Link].*;
import [Link].*;
import [Link].*;
class JCheckBoxDemo extends JFrame implements ItemListener
{
JTextField tf;
JCheckBox jch1,jch2;
JCheckBoxDemo()
{
super("Check Box Demo");
setLayout(new FlowLayout());
tf = new JTextField(15);
add(tf);

Page26
jch1 = new JCheckBox("apple");
add(jch1);
[Link](this);
jch2 = new JCheckBox("banana");
add(jch2);
[Link](this);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox jc=(JCheckBox)[Link]();
[Link]([Link]()+" is selected");
}
public static void main(String args[])
{
new JCheckBoxDemo();
}
}

6. JRadioButton
 Radio buttons are supported by the JRadioButton class,which is a concrete
implementations of [Link]’s immediate superclass is
JToggleButton,which provides support for two state buttons.
 Radio buttons must be configured into a [Link] one of the buttons in that
group can be selected at any time.
 The ButtonGroup class is instantiated to create a button [Link] default
constructor is invoked for this [Link] are then added to the button
group
via add( ) method.
void add(AbstractButton ab)
//ab is reference to the button to be added to
group.
 Constructor for JRadioButton
1. JRadioButton (Icon c)
2. JRadioButton (Icon c,boolean state)
3. JRadioButton (String s)
4. JRadioButton (String s,boolean state)
5. JRadioButton (String s,Icon i)
6. JRadioButton (String s,Icon c,boolean state)

Page27
Example:
import [Link].*;
import [Link].*;
import [Link].*;
class JRadioButtonDemo extends JFrame implements ItemListener
{
JTextField tf;
JRadioButton f,m;
ButtonGroup group;
JRadioButtonDemo()
{
super("Radio Button Demo");
setLayout(new FlowLayout());
tf = new JTextField(15);
add(tf);
f = new JRadioButton("Female");
add(f);
[Link](this);
m = new JRadioButton("Male");
add(m);
[Link](this);
group = new ButtonGroup();
[Link](f);
[Link](m);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
if([Link]())
{
[Link](""+[Link]());
}
else
{
[Link](""+[Link]());
}
}
public static void main(String args[])
{

Page28
new JRadioButtonDemo();
}
}

7. JComboBox
 Swing provides a combo box(a combination of a text field and a drop down
list) through the JComboBox class, which extends JComponent.
 A combo box normally displays one entry. However, it can also display a
drop-down list that allows a user to select a different entry.
 You can also type your selection into the text field.
 Constructor of JcomboBox
1. JComboBox( )
2. JComboBox(Vector v) //v is vector that initializes the combo box.
 Items are added to the list of choices via the addItem( )method,
void addItem( Object obj) //obj is object to be added to the combo box

import [Link].*;
import [Link].*;
import [Link].*;
class JComboBoxDemo extends JFrame implements ItemListener
{
JComboBox cb;
JLabel jl;
String lang[] = {"JAVA","DOTNET","VB","PHP","C++"};
JComboBoxDemo()
{
super("Combo Box Demo");
setLayout(new FlowLayout());
jl=new JLabel(" ");
add(jl);
cb = new JComboBox(lang);
add(cb);
[Link](this);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
[Link]("you have selected :"+[Link]([Link]()));
}

Page29
public static void main(String args[])
{
new JComboBoxDemo();
}
}

8. JtabbedPane
 A tabbed pane is a component that appears as a group of folders in a file
cabinet. Each folder has a title. When a user selects a folder, its content
becomes visible. Only one of the folders may be selected at a time.
 Tabbed panes are commonly used for setting configuration [Link]
panes are encapsulated by the JtabbedPane class, extends JComponent.
 We will use its default constructor. Tabs are defined via the following method.
void addTab(String str, Component comp) str is title for the tab
comp is the component that should added to the tab. Typically, a JPanel or a
subclass of it is added.

9 .JMenu:
• We can create a Menu Bar which contains several menus.
• Each menu can have several menu items. The separator can also be used to
separate out these menus.
• JMenuBar :- This class creates a menu bar.
• JMenu(String s) :- This class creates several menus. The string s denotes the
name of the menus.
• JMenuItem(String s) :- The menu items are the parts of menus. The string s
denotes the name of the menu item.
• setMnemonic(char c) :- The character which is passed to it as an argument
becomes the mnemonic key. Hence using alt+c you can select that particular
menu.
• JSeparator :- This is the constructor of the class JSeparator which adds
separating line between the menu items.
• setMenuBar :- This method is used to set menu bar to a specific frame.
Example :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Menu extends JFrame
{
JMenuBar menubar;
JMenu file,color;

Page30
JMenuItem new1,open,save,close;
JMenuItem red,blue,green;
JButton btnNew,btnSave,btnExit;
Menu()
{
super("Menu Sample Demo");
setLayout(new FlowLayout());
ImageIcon fileicon = new ImageIcon("images/[Link]");
ImageIcon saveicon = new ImageIcon("images/[Link]");
ImageIcon closeicon = new ImageIcon("images/[Link]");
btnNew = new JButton(fileicon);
btnSave = new JButton(saveicon);
btnExit = new JButton(closeicon);
menubar = new JMenuBar();
file = new JMenu("File");
[Link](KeyEvent.VK_F);
add(file);
new1 = new JMenuItem("New",fileicon);
add(new1);
[Link](new1);
save = new JMenuItem("Save",saveicon);
add(save);
[Link](save);
close = new JMenuItem("Close",closeicon);
[Link](KeyEvent.VK_X);
add(close);
[Link](close);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
[Link](0);
}
});
color = new JMenu("Color");
add(color);
red = new JMenuItem("Red");
add(red);
[Link](red);
[Link](file);
[Link](color);

Page31
setJMenuBar(menubar);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new Menu();
}
}

Page32

You might also like