0% found this document useful (0 votes)
24 views87 pages

Unit I

The document provides an overview of the Abstract Window Toolkit (AWT) and Swing in Java, detailing the class hierarchy, components, and layout managers. It explains the functionalities of various AWT controls such as labels, buttons, checkboxes, choice lists, and text fields, along with their methods for adding, removing, and managing user interactions. Additionally, it covers the use of layout managers like FlowLayout, BorderLayout, and GridLayout for arranging components in a graphical user interface.

Uploaded by

tsl345shiv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views87 pages

Unit I

The document provides an overview of the Abstract Window Toolkit (AWT) and Swing in Java, detailing the class hierarchy, components, and layout managers. It explains the functionalities of various AWT controls such as labels, buttons, checkboxes, choice lists, and text fields, along with their methods for adding, removing, and managing user interactions. Additionally, it covers the use of layout managers like FlowLayout, BorderLayout, and GridLayout for arranging components in a graphical user interface.

Uploaded by

tsl345shiv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 87

UNIT-1

AWT & SWING


Introduction to
AWT
AWT Classes
• The AWT classes are contained in the java.awt package.
Window Fundamentals
• AWT defines windows according to a class hierarchy that adds
functionality & specificity in each level.
• The two most common windows are
• those derived from Panel
• those derived from Frame
• The following fig. shows the class hierarchy for Panel and Frame
Component

Container

Window Panel

Frame Applet
Component
• All user interface elements that are displayed on the screen and that
interact with the user are subclasses of Component.
• Responsible for managing events, such as mouse and keyboard input,
positioning and sizing the window, and repainting.
Container
• subclass of Component
• Responsible for laying out(i.e. positioning) any components that it
contain.
• It does this through the use of various layout managers.
Panel
• Concrete subclass of Container.
• No new methods; it simply implements Container.
• Panel is the superclass for Applet.
• Panel is a window that does not contain a title bar, menu bar or
border. (AppletViewer provides this; browser won’t)
• Components can be added to a Panel object by its add( )
method.
• Once added, they can be positioned and resized manually using the
setLocation( ), setSize( ), or setBounds( ) methods defined by
Component.
Window
• creates top-level window.
• Window objects generally are not created directly; instead we will use a
subclass of Window called Frame.
Frame
• subclass of Window and has a title bar, menu bar, border and resizing
corners.
• Frame object can be created from within an applet window
• it will contain a message “Java Applet Window”
• When a Frame window is created by a program ; a normal window is
created.
Canvas
• not part of hierarchy.
• Canvas encapsulates a blank window upon which you can draw.
Commonly Used Methods of Component Class
• setBackground(): used to change the background color of a component.
public void setBackground ( Color c)
Note: color is a helper class.

• setForeground(): used to change the foreground color of a


component.
public void setForeground ( Font obj)
• Font is represented by java.awt.Font.
public Font (String FontName, int Style, int Size)
e.g. : Font f = (“Times New Roman”, Font.BOLD, 20);

• setBounds(): used to specify size and position of component in a container.


public void setBounds (int left, int top, int width, int height)
Commonly used methods of Container
Class
• add(): used to add components to a container.
public void add (Component c)

• setSize(): used to specify the size of a container.


public void setSize(int width, int height)

• setLayout(): used to specify the layout manager for a container.


public void setLayout (LayoutManager mgr)

• setVisible(boolean visibility): used to set the visibility of


container.
public void setVisible (boolean visibility)
Working with Frame
Windows
Frame’s Constructors
• Frame( )
• creates a standard window that does not contain a title.
• Frame(String title)
• creates a window with the title specified by title.
Setting the Window’s Dimensions
• void setSize(int newWidth, int newHeight)
• void setSize(Dimension newSize)
• set the dimensions of the window
• Dimension getSize( )
• obtain the current size of a window
Hiding and Showing a Window
• After a frame window has been created, it will not be visible until you
call setVisible( )
void setVisible(boolean visibleFlag)
-> visible if true otherwise hidden
Setting a Window’s Title
• void setTitle(String newTitle)
Closing a Frame Window
• Remove window from the screen by calling setVisible(false), when it is
closed.
• If Frame window is a child window, to intercept window-close event,
• implement windowClosing( ) method of the WindowListener interface.
• Inside windowClosing( ), remove the window from the screen.
import java.awt.Frame;
public class SampleFrame extends Frame {
SampleFrame(String title) {
super( );
this.setTitle(title);
this.setSize(300,200);
this.setVisible(true);
}
public static void main(String args[
]) {
SampleFrame sf = new
SampleFrame(“My
Window”);
Layout
managers
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the
LayoutManager interface.
• The layout manager is set by the setLayout( ) method.
• If no call to setLayout( ) is made, then the default layout manager is
used.
• The setLayout( ) method has the following form
void setLayout(LayoutManager layoutObj)
layoutObj -> reference to the
desired layout manager
• Java has several predefined LayoutManager
classes.
FlowLayout
• FlowLayout is the default layout manager.
• FlowLayout implements a simple layout style, which is similar to how
words flow in a text editor.
• direction -> by default it is left to right, top to bottom
• By default, components are laid out line-by-line beginning at the upper-left
corner.
• A small space is left between each component, above and below, as well as
left and right.
• Constructors
FlowLayout( ) -> creates the default layout, which centers components
and leaves 5 pixels of space between each component.
FlowLayout(int how)
-> valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
FlowLayout(int how, int horz, int vert)
-> horz and vert allows to specify the horizontal and vertical
space between components
BorderLayout
• BorderLayout class implements a common layout style for top-level
windows
• It has four narrow, fixed-width components at the edges and one large
area in the center.
• The four sides are referred to as north, south, east and west. The middle
area is called the center
• Constructors
BorderLayout( ) -> default border layout
BorderLayout(int horz, int vert)
• When adding components to border layout, call the following add( )
method
void add(Component compObj, Object region)
compObj – component to be added
region – specifies where the component will
be added
• BorderLayout defines the following constants that specify the regions
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
GridLayout
• GridLayout lays out components in a two-dimensional grid.
• Constructors
GridLayout( ) – creates a single-column grid layout
GridLayout(int numRows, int numColumns)
-> creates a grid layout with the specified number of rows and
columns
GridLayout(int numRows, int numColumns, int horz, int vert)
• Specifying numRows as zero allows for unlimited-length columns
• Specifying numColumns as zero allows for unlimited-length rows
CardLayout

• It is used to arrange containers in the form of deck of cards.

Methods:
first() / last()/ next()/ previous(): is used to make the first/
last/ next/ previous card visible.

show(): is used to make a specified card visible.


public void show ( Container deck, String CardName)

• To give a name to the container while it is added to the


deck:
public void add ( Container card, String CardName)
AWT
Controls
• The AWT supports the following types of controls
• Labels
• Push Buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text editing
-> subclasses of Component
Adding and Removing Controls
• To add a control to a window
• first create an instance of the desired control.
• then add it to a window by calling add(
) Component add(Component
compObj)
compObj -> instance of the
control to add
• To remove a control
void remove(Component obj)
obj -> control to be removed
removeAll( ) -> to remove all controls
• Except for labels, which are passive controls, all controls generate
events when they are accessed by user.
• Example
Labe
lsA label is an object of type Label, and it contains a string which it

displays.
• Passive controls – do not support any interaction with the user.
• Label defines the following constructors
Label( )
Label(String str) – string is left-justified
Label(String str, int how)
- alignment specified by how
- value of how must be one of
the 3 constants
- Label.LEFT, Label.RIGHT,
Label.CENTER
• To set or change the text in a label, use the setText( ) method.
void setText(String str)
• To obtain the current label, call getText( )
String getText( )
• To set the alignment of the string within the label, call setAlignment( )
void setAlignment(int how)
• To obtain the current alignment, call getAlignment( )
int getAlignment( )
• Example
Butto
ns
• A push button is a component that contains a label and that
generates an event when it is pressed.
• Push buttons are objects of type Button.
• Button defines these two constructors
Button( )
Button(String str) – contains str
as a label
• To set the label of a button, call
setLabel( ) void setLabel(String str)
• To retrieve the label of a button, call
getLabel( ) String getLabel( )
Check
Boxes
• A check box is a control that is used to turn an option on or off. It
consists of a small box that can either contain a check mark or not.
• There is a label associated with each check box that describes what
option the box represents.
• Check boxes can be used individually or as part of a group.
• Check boxes are objects of the Checkbox class.
• Checkbox supports these constructors
Checkbox( ) – label is initially blank; state of the checkbox is
unchecked.
Checkbox(String str) – label is specified by str; state of the
checkbox is unchecked.
Checkbox(String str, boolean on)
- if on is true, the checkbox is initially checked;
otherwise cleared.
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
- group is specified by cbGroup; if this checkbox is not
part of a group, then cbGroup must be null.
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
• To retrieve the current state of a checkbox, call getState( )
boolean getState( )
• To set the state of a checkbox, call setState( ):
void setState(Boolean on)
• To obtain the current label associated with a checkbox, call getLabel( )
String getLabel( )
CheckboxGr
oup
• It is possible to create a set of mutually exclusive check boxes in
which one and only one check box in the group can be checked at any
one time.
• These check boxes are often called radio buttons.
• To create a set of mutually excusive check boxes, first define the
group to which they will belong and then specify that group when
constructing the checkboxes.
• Check box groups are objects of type CheckboxGroup
• Only default constructor – CheckboxGroup( ) -> creates an empty
group.
• To determine which checkbox in a group is currently selected, call
getSelectedCheckbox( )
Checkbox getSelectedCheckbox( )
• To set a check box, call setSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
which -> checkbox that has to be selected; previously
selected check box will be turned off
• Example
Choice
Controls
• The Choice class is used to create a pop-up list of items from which the
user may choose.
• Thus, a choice control is a form of menu.
• When inactive, a Choice component takes up only enough space to show
the currently selected item.
• When the user clicks on it, the whole list of choices pops up, and a new
selection can be made.
• Choice only defines the default constructor, which creates an empty
list.
• To add a selection to the list, call add( ). Items are added to the list in the
order in which calls to add( ) occur.
void add(String name)
• To determine which item is currently selected, call getSelectedItem( ) or
getSelectedIndex( )
String getSelectedItem( )
-> returns a string containing the name of the item
int getSelectedIndex( )
-> returns the index of the item. The first item is at index 0
• To obtain the number of items in the list, call getItemCount( )
int getItemCount( )
• To set the currently selected item with either a zero-based index or a string that will
match a name in the list, call select( )
void select(int index)
void select(String name)
• To obtain the name
associated with the item at
an index, call getItem( )
List
sThe List class provides a compact, multiple-choice, scrolling selection list.

• A List object can be constructed to show any number of choices in the
visible window.
• It can also be created to allow multiple selections.
• List provides 3 constructors
List( ) – creates a List control that allows only one item to be
selected at any one time.
List(int numRows) – numRows specifies the number of entries in
the list that will always be visible.
List(int numRows, boolean multipleSelect) – if multipleSelect is true,
then the user may select two or more items at a
time. If it is false, only one item may be
selected.
• To add a selection to the list, call add( )
void add(String name) – name is the name of the item added to the list.
void add(String name, int index) – adds the item at the index specified
by index.
• For lists that allow only single selection, to determine which item is currently
selected, call getSelectedItem( ) or getSelectedIndex( )
• For lists that allow multiple selection, call getSelectedItems( ) or
getSelectedIndexes( )
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
TextFiel
ds
• The TextField class implements a single-line text-entry area, usually called
an edit control.
• TextField is a subclass of TextComponent.
• TextField defines the following constructors
TextField( ) – creates a default text field
TextField(int numChars) – creates a text
field that is numChars wide.
TextField(String str) – initializes the text
field with the string contained
in str.
TextField(String str, int numChars)
• To obtain the string currently contained in the text field, call getText( )
String getText( )
• To set the text, call setText( )
void setText(String str) – str is the new string
• To select a portion of the text in a text field, call
select( )
void select(int startIndex, int endIndex)
- selects the characters beginning at
startIndex and ending at
endIndex – 1
• To obtain the currently selected text, call getSelectedText( )
String getSelectedText( )
• To control whether the contents of a text field may be modified by the
user or not, call setEditable( )
void setEditable(boolean canEdit)
- if canEdit is true, the text may be changed. If
it is false, the text cannot be altered.
• To determine the editability, call isEditable( )
boolean isEditable( )
- returns true if the text may be changed and false if not.
• To disable the echoing of characters as they are typed(eg.while typing
passwords), call setEchoChar( ) method.
void setEchoChar(char ch)
- ch specifies the character to be echoed.
• To check a text field to see if it is in this mode, call echoCharIsSet( )
method.
boolean echoCharIsSet( )
• To retrieve the echo character, call getEchoChar( ) method.
char getEchoChar( )
• Example
TextAr
•ea
Sometimes, a single line of text input is not enough for a given task. to
handle these situations, the AWT includes a multiline editor called
TextArea.
• Constructors
TextArea( )
TextArea(int numLines, int numChars)
-> numLines specifies the height, in lines, of the text area
-> numChars specifies its width, in characters.
TextArea(String str)
-> initial text can be specified by str
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
-> sBars specify the scroll bars. sBars must be one of these
values
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
• TextArea is a subclass of TextComponent.
• It supports the getText( ), setText( ), getSelectedText( ), select,
isEditable( ), and setEditable( )
• TextArea adds the following methods
void append(String str)
-> appends the string specified by str to the end of the
current text.
void insert(String str, int index)
-> inserts the string passed in str at the specified index.
void replaceRange(String str, int startIndex, int endIndex)
-> replaces the characters from startIndex to
endIndex -1,
with the replacement text passed in str.
Scroll Bar

Scroll bars are used to select continuous values between


a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically.
Scrollbar defines the following constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min,
int max) throws HeadlessException
Continue…

If style is Scrollbar.VERTICAL, a vertical scroll bar is


created.
If style is Scrollbar.HORIZONTAL the scroll bar is
horizontal.
the height of the thumb is passed in thumbSize.
The minimum and maximum values for the scroll bar are
specified by min and max.
Method

void setValues(int initialValue, int thumbSize, int min, int


max)
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
void setUnitIncrement(int newIncr) //scroll line up and
down
void setBlockIncrement(int newIncr) //scroll page-up and
down
Menu Bars and Menus

• Menu is implemented in AWT by the following classes: MenuBar,


Menu, and MenuItem.
• A menu bar displays a list of top-level menu choices. Each choice
is associated with a drop-down menu.
• A menu bar contains one or more Menu objects. Each Menu
object contains a list of MenuItem objects.
• Each MenuItem object represents something that can be
selected by the user.
• Since Menu is a subclass of MenuItem, a hierarchy of nested
submenus can be created.
• Checkable menu items are menu options of type
CheckboxMenuItem and will have a check mark next to them
when they are selected
Creating Menu
• To create a menu bar, first create an instance of MenuBar.
This class only defines the default constructor.
public MenuBar()
• setMenuBar() method is used to add menubar on window.
• Next, create instances of Menu that will define the selections
displayed on the bar. Following are the constructors for
Menu:
Menu( ) throws HeadlessException
Menu(String optionName) throws HeadlessException
Menu(String optionName, boolean removable) throws
HeadlessException
Individual menu items are of type MenuItem. It defines these
constructors:
MenuItem( ) throws HeadlessException
MenuItem(String itemName) throws HeadlessException
MenuItem(String itemName, MenuShortcut keyAccel) throws
HeadlessException
Methods

• We can disable or enable a menu item by using the setEnabled( )


method.
void setEnabled (boolean enabledFlag)
• If the argument enabledFlag is true, the menu item is enabled. If false,
the menu item is disabled.
• We can determine an item’s status by calling isEnabled( ).
boolean isEnabled( )
• isEnabled( ) returns true if the menu item on which it is called is
enabled. Otherwise, it returns false.
• We can change the name of a menu item by calling setLabel( ).
We can retrieve the current name by using getLabel( ).
void setLabel(String newName)
String getLabel( )
item2 = new MenuItem("Open...");
Example item3 = new MenuItem("Close");
Import java.awt.*; item4 = new MenuItem("-");
Class MenuDemo extends item5 = new MenuItem("Quit...");
Frame // add menu items on menu
{ file.add(item1); file.add(item2);
MenuDemo() file.add(item3); file.add(item4);
{ file.add(item5);
MenuBar mbar = new // add menu on menubar mbar.add(file);
MenuBar(); }
setMenuBar(mbar); Public static void main(String arg[]) {
// create the menu and menu MenuDemo md=new MenuDemo();
items md.setVisible(true);
Menu file = new Menu("File"); md.setTitle(“Menu”);
MenuItem item1, item2, item3, md.setSize(400,400);
item4, item5; }
item1 = new MenuItem
("New...");
Dialog Boxes

• Dialog boxes are primarily used to obtain user input and are
often child windows of a top-level window.
• Dialog boxes don’t have menu bars, but in other respects,
they function like frame windows.
• You can add controls to them, for example, in the same way
that you add controls to a frame window.
• Dialog boxes are of type Dialog
• Dialog(Frame parentWindow, boolean mode)
• Dialog(Frame parentWindow, String title, boolean mode)
• parentWindow is the owner of the dialog box.
Continue..
• Dialog boxes may be modal or modeless.
• When a modal dialog box is active, all input is directed to it
until it is closed. This means that you cannot access other
parts of your program until you have closed the dialog box.
• When a modeless dialog box is active, input focus can be
directed to another window in your program.
• Thus, other parts of your program remain active and
accessible.
Example

Create subclass of Dialog Class Fdemo extends Frame{


class Fdemo()
Class DemoDialog extends {
Dialog{ setSize(300,400);
DemoDialog(Frame par, }
String title) Public static void main (String
{ arg[])
Button b1= new Button {
(“ok”); add(b1); Fdemo fd=new Fdemo();
setSize(300,100); Fd.setVisible(true);
setVisible(true); DemoDialog dd=new
} DemoDialog(fd,”First Dialog”);
} }
File Dialog
• Java provides a built-in dialog box that lets the user specify a file.
• To create a file dialog box, instantiate an object of type
FileDialog. This causes a file dialog box to be displayed.
• Usually, this is the standard file dialog box provided by the
operating system.
FileDialog constructors:
FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)
If how is FileDialog.LOAD, then the box is selecting a file for
reading.
If how is FileDialog.SAVE, the box is selecting a file for writing. If
how is omitted, the box is selecting a file for reading.
• FileDialog provides methods that allow you to determine the
name of the file and its path as selected by the user. Here are
two examples:
String getDirectory( )
String getFile( )
SWIN
GSwing was a response to deficiencies present in Java’s original GUI

system: AWT
• Limitations of AWT
• The look and feel of a component in AWT is defined by the platform, not
by
Java.
• AWT components are heavyweight, because they use native code
resources
Swing is built on the AWT
• Swing eliminates many limitations in AWT, but does not replace it.
• Instead, Swing is built on the foundation of the AWT.
• Swing also uses the same event handling mechanism as the AWT.
Two key Swing features
1. Swing components are lightweight
• Swing components are lightweight. This means that they are written entirely in Java
and do not map directly to platform-specific peers.
• So the look and feel of each component is determined by Swing, not by the
underlying operating system.
• This means that each component will work in a consistent manner across all
platforms.
2. Swing supports a Pluggable Look and Feel(PLAF)
• It is possible to change the way that a component is rendered without affecting any
of its other aspects.
• In other words, it is possible to “plug in” a new look and feel for any given
component without creating any side effects in the code that uses that component.
The MVC
Connection
• In general, a visual component is a composite of three distinct parts
• The state information associated with the component (Model)
-> For example, in the case of a check box, the model contains a field that
indicates if the box is checked or unchecked.
• The way that the component looks when rendered on the screen (View)
• The way the component reacts to the user (Controller)
-> For example, when the user clicks a check box, the controller reacts
by changing the model to reflect the user’s choice(checked or unchecked).
This then results in the view being updated.
• By separating a component into a model, a view and a controller, the
specific implementation of each can be changed without affecting the
other two. For instance, different view implementations can render the
same component in different ways without affecting the model or the
controller.
• Swing uses a modified version of MVC that combines the view and the
controller into a single logical entity called the UI delegate.
• Swing’s approach is called the Model-Delegate architecture or the
Separable Model architecture.
• Because the view(look) and controller(feel) are separate from model, the
look and feel can be changed without affecting how the component is
used within a program.
• Most Swing components contain two objects
• The first represents the model. Models are defined by interfaces. eg. Model for a
button is defined by ButtonModel interface.
• The second represents the UI delegate(view & controller). UI delegates are
classes
that inherit ComponentUI. eg. UI delegate for a button is ButtonUI
Components and
Containers
• A Swing GUI consists of two key items: components and containers.
• A component is an independent visual control, such as a push button
or slider.
• A container holds a group of components.
Components
• In general, Swing components are derived from JComponent class.
• JComponent inherits the AWT classes Component and Container.
• All of Swing’s components are represented by classes defined within
the package javax.swing
• Swing Component classes (refer book table)
Containers
• Swing defines two types of containers.
1. Top-level containers
- JFrame, JApplet, JWindow and JDialog.
- Inherit the AWT classes Component and Container
- The most commonly used container for applications is JFrame.
- The one used for applets is JApplet.
2. Lightweight containers
- Lightweight containers do inherit JComponent.
- An example of a light weight container is JPanel.
JAppl
et
• Fundamental to Swing is the JApplet class, which extends Applet.
• JApplet support various “panes” such as the,
• content pane
• glass pane
• root pane
• When adding a component, instead of invoking the add( ) method of
the applet, call add( ) for the content pane of the JApplet class
Container getContentPane( )
• The add( ) method of Container can be used to add a component to a
content pane
void add(comp)
Icons and
Labels
ImageIcon class
• Constructors
ImageIcon(String filename)
ImageIcon(URL url)
• Methods
int getIconHeight( )
int getIconWidth( )
void
paintIcon(Compon
ent comp, Graphics
g, int x, int y)
JLabel class
• extends JComponent
• can display text/or an icon
• Constructors
JLabel(Icon i)
Label(String s)
JLabel(String
s, Icon i, int
align)
align -
>
either
LEFT,
RIGHT,
CENTE
import java.awt.*;
import javax.swing.*;
/*
<applet code = “JLabelDemo” width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init( ) {
Container cp = getContentPane( );
ImageIcon ii = new ImageIcon(“France.gif”);
JLabel jl = new JLabel(“France”, ii,
JLabel.CENTER);
cp.add(jl);
}
}
Text
Fields
• JTextComponent class
• extends JComponent
• one of the subclass of JComponent -> JTextField
• constructors
• JTextField( )
• JTextField(int cols) -> no.of columns in the text field
• JTextField(String s, int cols)
• JTextField(String s)
• Eg. JTextField jtf = new JTextField(15);
contentPane.add(jtf);
Butto
ns
• Swing Buttons are subclasses of the AbstractButton class.
• AbstractButton class
• extends JComponent.
• contains methods to control the behaviour of buttons, checkboxes
and radio buttons.
• the text associated with a button can be read and written
via String getText( )
void setText(String s)
The JButton class
• Provides the functionality of a push button.
• Allows an icon, a string or both to be associated with the push button.
• Constructors
• JButton(Icon i)
• JButton(String s)
• JButton(String s, Icon i)
Check
Boxes
• JCheckBox class
• concrete implementation of AbstractButton
• immediate superclass is JToggleButton
• provides support for two-state buttons
• Constructors
• JCheckBox(Icon i)
• JCheckBox(Icon i, boolean state)
• JCheckBox(String s)
• JCheckBox(String s, boolean state)
• JCheckBox(String s, Icon i)
• JCheckBox(String s, Icon i, boolean state)
Radio
Buttons
• JRadioButton class
• Constructors
• JRadioButton(Icon i)
• JRadioButton(Icon i, boolean state)
• JRadioButton(String s)
• JRadioButton(String s, boolean state)
• JRadioButton(String s, Icon i)
• JRadioButton(String s, Icon i, boolean state)
• Radio Buttons must be configured into a group.
• Only one of the buttons in that group can be selected at any time.
JComboBox
• The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu.
• Constructors:
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
Creates a JComboBox that contains the elements in the
JComboBox(Vector<?> items)
specified Vector.

Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is editable.


JList
Constructor Description
JList() Creates a JList with an empty, read-only, model.
Creates a JList that displays the elements in the specified
JList(ary[] listData)
array.

Creates a JList that displays elements from the specified,


JList(ListModel<ary> dataModel)
non-null, model.

Methods Description
int getSelectedIndex() It is used to return the smallest selected cell index.

ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from an array of


objects.
JTabbedPane

• A tabbed pane is a container that can store and organize multiple


components into distinct tabs.
• It contains a collection of tabs. When you click on a tab, only data
related to that tab will be displayed.
• JTabbedPane comes under the Java Swing package.
Constructor Description

The JTabbedPane class in Java Swing has a default, no-argument constructor called
JTabbedPane() JTabbedPane(). This constructor initializes an empty tabbed pane with no tabs and no initial
content when a JTabbedPane is created.

The JTabbedPane(int tabPlacement) constructor allows to creation of a JTabbedPane with a


JTabbedPane(int tabPlacement) defined initial location for the tabs. The tab placement option specifies whether the tabs
appear at the top, bottom, left, or right of the tabbed pane.
•Tabs: Each tab in a JTabbedPane is normally represented by a title or
icon, and clicking on a particular tab shows the information only related
to that tab.
•Tab Placement: JTabbedPane provides many tab placement options,
such as top, bottom, left, or right sides of the pane, allowing you to
customize the layout.
•Scrolling: If the tabs don't fit in the visible region, JTabbedPane provides
scrolling options to navigate through them.
Example
import javax.swing.*;
import java.awt.*;
public class TabbedExample {
public static void main(String[] args) {
JFrame window = new JFrame("JTabbedPane Example");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setSize(400, 300);
JTabbedPane tabPanel = new JTabbedPane();
JPanel page1 = new JPanel();
page1.add(new JLabel("This is Tab 1"));
JPanel page2 = new JPanel();
page2.add(new JLabel("This is Tab 2"));
tabPanel.addTab("Tab 1", page1);
tabPanel.addTab("Tab 2", page2);
window.add(tabPanel);
window.setVisible(true);
}
}
JScrollPane
• Java JScrollPane is a component in the Java Swing library that provides a
scrollable view of another component, usually a JPanel or a JTextArea.
• It provides a scrolling functionality to the display for which the size changes
dynamically.
• It is useful to display the content which exceeds the visible area of the window.

Constructors Descriptions

JScrollPane() It is a default constructor that creates an empty JScrollPane.

This constructor creates a JScrollPane with the specified view component as


JScrollPane(Component comp) the scrollable content.

This constructor creates an empty JScrollPane with the specified vertical and
JScrollPane(int vertical, int horizontal) horizontal scrollbar.

JScrollPane(LayoutManager layout) This constructor creates a JScrollPane with the specified layout manager.
Methods Description

void setVerticalScrollBarPolicy(int vertical) Sets the vertical scrollbar policy

void setHorizontalScrollBarPolicy(int horizontal) Sets the horizontal scrollbar policy

void setColumnHeaderView(Component comp) sets the column header for the JScrollPane

void setRowHeaderView(Component comp) sets the rowheader for the JScrollPane

It is used to set a component to be displayed in one of the corners


setCorner(String key, Component corner)
of the scroll pane

It is used to retrieve the component that has been previously set


Component getCorner(String key) in one of the corners of the scroll pane using the setCorner
method

It is used to set the component that will be displayed in the


void setViewportView(Component comp)
viewport of the scroll pane
Example
import javax.swing.*;
import java.awt.*;
public class SimpleJScrollPaneExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JLabel label = new JLabel("Label ");


panel.add(label);

JScrollPane scrollPane = new JScrollPane(panel);

frame.add(scrollPane);
frame.setVisible(true);
}
}
JTree
• The JTree class is used to display the tree structured data or
hierarchical data. JTree is a complex component.
• It has a 'root node' at the top most which is a parent for all nodes in
the tree. It inherits JComponent class.
Constructor Description

This constructor creates a JTree with a sample model. It serves as a quick way to
JTree() initialize a tree structure without specifying a custom model.

JTree is created with each element of the specified array becoming a child of a new
JTree(Object[] value) root node. This constructor is useful when you want to build a tree structure based on
an array of values.

JTree is created with the specified TreeNode as its root. This allows you to define a
JTree(TreeNode root) custom structure for your tree by providing a root node explicitly.

DefaultMutableTreeNode( Strin Creates Treenode


g s)
Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt); f.setSize(200,200); f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
JTable
The JTable class is used to display data in tabular form. It is composed
of rows and columns.

Constructor Description

JTable() Creates a table with empty cells.


JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
JTable(int rows, int cols) Creates a table of size rows * cols.
Example
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
The JProgressBar class is used to display the progress of the task. It
inherits JComponent class.
Constructor Description
It is used to create a horizontal progress bar but no
JProgressBar()
string text.
It is used to create a horizontal progress bar with
JProgressBar(int min, int max)
the specified minimum and maximum value.
It is used to create a progress bar with the specified
orientation, it can be either Vertical or Horizontal by
JProgressBar(int orient)
using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
It is used to create a progress bar with the specified
JProgressBar(int orient, int min, int max)
orientation, minimum and maximum value.
Method Description
It is used to determine whether string
void setStringPainted(boolean b) should be displayed.
It is used to set value to the progress
void setString(String s)
string.
It is used to set the orientation, it may be
either vertical or horizontal by using
void setOrientation(int orientation)
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
It is used to set the current value on the
void setValue(int value)
progress bar.
Tooltip
• You can create a tool tip for
any JComponent with setToolTipText() method.
• This method is used to set up a tool tip for the component.

field.setToolTipText("Enter your Password");

• String getToolTipText() : returns the tooltip text for that component .


JMenuBar

JMenuBar

JMenu

JMenuItem
JSeparator
• The object of JSeparator class is used to provide a general purpose
component for implementing divider lines.
• It is used to draw a line to separate widgets in a Layout.
menu.addSeparator();
JSeparator() Creates a new horizontal separator.
JSeparator(int orientation) Creates a new separator with the specified horizontal or vertical orientation.

method explanation
setOrientation(int o) Sets the orientation of the separator.

getOrientation() returns the orientation of the separator.

addSeparator() adds a separator in JMenu or JPopupMenu.

You might also like