[go: up one dir, main page]

0% found this document useful (0 votes)
11 views77 pages

Chapter4 New

This document outlines the course unit on event handling using AWT and Swing components in Java, detailing course outcomes and specific learning objectives. It includes practical programming tasks related to GUI design, layout management, and event handling. Additionally, it provides an overview of AWT components, their hierarchy, and methods for creating interactive applications.

Uploaded by

trushnapihal4
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)
11 views77 pages

Chapter4 New

This document outlines the course unit on event handling using AWT and Swing components in Java, detailing course outcomes and specific learning objectives. It includes practical programming tasks related to GUI design, layout management, and event handling. Additionally, it provides an overview of AWT components, their hierarchy, and methods for creating interactive applications.

Uploaded by

trushnapihal4
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/ 77

Unit - IV

Event handling using Abstract Window Toolkit (AWT) &


Swings Components
16 Marks
Course Outcomes
• CO4 - Develop java program for implementing
event handling using window-based application
components
TLO’s
• TLO 4.1 Write steps to develop Graphical User Interface (GUI)
using AWT components with frame for the given problem.
• TLO 4.2 Develop program using menu and dialog boxes for
the given problem.
• TLO 4.3 Write steps to develop Graphical user interface (GUI)
using advanced swing components for the given problem.
• TLO 4.4 Use delegation event model to develop event driven
program for the given problem
• TLO 4.5 Use relevant AWT/ Swing component(s)to handle the
given event.
LLO
1. Write program to design any type of form using AWT components.
2. Write program to create a menu bar with various menu items and sub menu
items.
3. Write program to demonstrate the use of border layout. The layout shows four
buttons at four sides with captions “left”, “right”, “top” and “bottom” using
Swing Components.
4. Write program to design a calculator to demonstrate the use of grid layout using
swing components.
5. Write program using swing to display a JComboBox in a JFrame .
6. Write program to create JTree and JTable.
7. Write program to handle key events and mouse events.
8. Write program to implement action event in frame using swing components.
9. Write program to handle text event on swing components.
Contents..
• 4.1 Component, container, window, frame, panel, use of AWT controls: labels,
buttons,checkbox, checkbox group, textfield, textarea
• 4.2 Use of layout managers: flowLayout, borderLayout, gridLayout,
gridBagLayout,menubars, menus, file dialog
• 4.3 Introduction to swing: Swing features, difference between AWT and Swing.
• 4.4 Swing components: Icons and Labels, TextField, ComboBox, Button,
Checkbox,RadioButton
• 4.5 Advanced Swing Components: Tabbed Panes, Scroll Panes, Trees, Tables,
Progressbar, tool tips
• 4.6 Introduction to Event Handling: The delegation Event Model: Event sources,
Eventlisteners
• 4.7 Event classes: The action event class, the Item event class, the Key event class,
themouse event class, text event
• 4.8 Event listener interfaces: ActionListener , ItemListener , KeyListener ,MouseListener ,
MouseMotion , TextListener
AWT(Abstract Window Toolkit)
• Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java.
• AWT contains numerous classes and methods that allow you to create and
manage window.
• To use AWT features we want to import;
import java.awt.*;
• Java AWT components are platform-dependent.
• AWT is heavyweight, which means that its components consume resources
from the underlying operating system (OS).
AWT Hierarchy
Component
• It extends object class.

• It is an object having a graphical representation that can be


displayed on the screen and that can interact with the user.

• Component class is present at top of the hierarchy.

• AWT provides various components such as buttons, labels,


text fields, checkboxes, etc used for creating GUI elements
for Java Applications.
Container
• Container class is a subclass of Component.

• Container is responsible for laying out the any components that it contains.

• It is done by using various layout managers.

• AWT provides containers like panels, frames, and dialogues to organize


and group components in the Application.
Important Methods of Component
1. public void add(Component c): Inserts a component into a Container by taking
component as parameter.

2. public void setSize(int width, int height): Sets the size of the component.

3. public void setLayout(LayoutManager lm): Sets the layout to set the components in
a particular manner.

4. public void setVisible(boolean status): Sets the visibility of a component to visible


or not.
Window
• The Window class extends the Container class

• Window is a top-level container that represents a graphical window.

• The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.

• Simply window can contain other components, such as buttons, labels, and
text fields.
Panel

• Panel is a container class in Java.

• It is a lightweight container that can be used for grouping other components


together within a window or a frame.

• Panel is the immediate superclass of Applet.

• The Panel is the container that doesn't contain title bar, border or menu bar.
It is generic container for holding the components.
Frame:

• It is subclass of Window

• The Frame is the container that contains the title bar, border
and can have menu bars.

Dialog:
• A dialog box is a temporary window an application creates to
retrieve user input.
AWT Controls
The component which are allow to interact with applications.
The AWT controls as follows;
• Labels
• Button
• Checkbox
• Checkbox group
• Scrollbars
• Text field
• Text Area
Label
A Label object is a component for placing text in a container. The three types of Label
constructors are as follows;

Label(): To create Empty Label.


e.g. Label l1=Label();

• Label(String str): Create a Label with str as its name.

e.g. Label l1=Label(“User Name:”);

• Label(String str, int x): Create a label with the specified string and x as the specified
alignment. By default alignment is Left. Valid values for x are Left, Right and Center.
e.g. Label l1=Label(“User Name”, Label.Center);
Label
• void setText(String str): Used to sets the text of the label.

• String getText( ): Used to get the text of label.

• void setAlignment(int how) : Used to sets the alignment of text in the label.

• int getAlignment( ) : Used to get the alignment of text in the label.


Button

• Button Class is used for creating a labeled button.

• Button( ): Creates a Button with no label.

• Button(String str): Creates a Button with String str as a label.

• Setter and Getter method for Button;

• void setLabel(String str) : Used to set the label to the button.

• String getLabel( ) : Used to get the label of the button.

• setEnable(Boolean enable) : Used to enable and disable the button(Disabled button


can not be clicked)
CheckBox
• A CheckBox is a graphical component that • Setter and Getter methods for CheckBox;
can be in either an on (true) or off (false) • Boolean getState( )
state.
It returns true if checkbox is on, else
• The constructors of CheckBox class are as returns off.
follows;
• void setState(Boolean on)
• Checkbox(): Creates a checkbox with no label.
• Checkbox(String str): Creates a checkbox with It sets the state of checkbox to the
a str (label). specified state.
• Checkbox(String str, boolean state): Creates a • String getLabel( )
checkbox with the str label, and sets the state in
the mentioned group.
It fetched the label of checkbox.
• Checkbox(String str, boolean • void setLabel(String str)
state,CheckBoxGroup object): Creates a Sets the checkbox label to the String
checkbox with the str label, and sets the state and
group is specified with the object.
argument.
CheckboxGroup
• CheckboxGroup Class is used to group together a set of Checkbox.
• In which one and only one check box in the group can be checked at any
one time.
• It converts checkbox into radiobutton.
• Setter and Getter methods for CheckboxGroup;
• getSelectedCheckbox()
• setSelectedCheckbox()
Choice
• The object of Choice class is used to show popup • void insert(String item, int index)
menu of choices.
• Inserts the item into this choice at the specified position.
• Choice selected by user is shown on the top of a menu
• void remove(int position)
• It has only one constructor.
• It removes an item from the choice menu at the given index
• Choice(): create empty list.
position.
• void add(String item)
• void remove(String item)
• It adds an item to the choice menu.
• It removes the first occurrence of the item from choice
• String getItem(int index)
menu.
• It gets the item (string) at the given index position in
the choice menu.
• void removeAll()

• int getItemCount() • It removes all the items from the choice menu.
• It returns the number of items of the choice menu. • void select(int pos)
• int getSelectedIndex() • It changes / sets the selected item in the choice menu to the
• Returns the index of the currently selected item. item at given index position.

• String getSelectedItem() • void select(String str)


• Gets a representation of the current choice as a string. • It changes / sets the selected item in the choice menu to the
item whose string value is equal to string specified in the
List
• The object of the AWT List class represents a list of text • void deselect(int index)
items. • Deselects the item at the specified index in a multiple-
• List object can be constructed to show any number of selection list.
choices in the • String getItem(int index)
visible window. • Retrieves the item at the specified index in the list.
• The constructors of list are as follows; • int getItemCount()
• List( ) : Creates a new list. • Returns length(the number of items) in the list.
• List(int numRows) : Creates lists for a given • String[] getItems()
number of rows.
• Used to return an array of all the items in the list.
• List(int numRows, Boolean multipleSelect) :
• int getRows()
Ceates new list initialized that displays the given
• Used to return the number of rows present in the list.
number of rows.
• void add(String item) • int getSelectedIndex()

• Adds the specified item to the end of the list. • Returns the index of the first selected item in a multiple-
selection list.
• void add(String item, int index)
• int[] getSelectedIndexes()
• Used to insert the given item to the given index in the
• Returns an array of the selected item indexes in a multiple-
list.
List
• String getSelectedItem() • void remove(String item)
• Returns the selected item in a single-selection list. • Used to remove the first occurrence of the
• String[] getSelectedItems() given item from the list.

• Returns an array of the selected item values in a • void removeAll()


multiple-selection list. • Used to remove all items from the list.
• boolean isIndexSelected(int index) • void replaceItem(String newVal, int index)
• Checks if the item at the given index is selected in • Replace the item at the given index with a
a multiple-selection list. new item.
• boolean isMultipleMode() • void select(int index)
• Check if the list allows multiple selections. • Selects the item at the given index in the list.
• void remove(int position) • void setMultipleMode(boolean b)
• Used to remove the item at the given index from • Sets whether the list allows multiple
the list. selections (true) or single selection (false).
TextField
• It allows the user to enter a single line of text as an • boolean echoCharIsSet()
input. • Check if there is a character set for echoing in this
• It is a simple way to collect text-based information from text field.
the user. • int getColumns()
• You can use the TextField component to create various • Returns the number of columns in a text field.
input fields for username, password, search boxes, etc. • char getEchoChar()
1. TextField(): Constructs a new text field component • Returns the character to be used for echoing.
2. TextField(int columns): Constructs a new empty text • void setColumns(int columns)
field with the required number of columns as the • Defines the number of columns in the text field.
parameter.
• void setEchoChar(char c)
3. TextField(String text): Creates a new text field
• Defines echo character for the text field.
initialized with the string text to be displayed.
• void setText(String t)
4. TextField(String text, int columns): Creates a new text
field with the given text to be displayed and a width • Sets the text that is presented by this text
that fits the specified number of columns. component to be the specified text.
TextArea
• Sometimes a single line of text input is not enough for a given
• int getColumns()
task. for e.g. Address
• It returns the number of columns of text area.
• It is a text component that allows for the editing of a multiple • int getRows()
lines of text.
• It returns the number of rows of text area.
• Constructors of TextArea: • int getScrollbarVisibility()
• TextArea( ) : It constructs a new and empty text area with no • It returns an enumerated value that indicates which scroll
text in it. bars the text area uses.
• void insert(String str, int pos)
• TextArea(intnumLines, intnumChars) E.g; TextArea(10,5)
• It inserts the specified text at the specified position in this
• TextArea(String str) : E.g; TextArea(“welcome”) text area.
• TextArea(String str, intnumLines, intnumChars) E.g; • void replaceRange(String str, int start, int end)
TextArea(“welcome”,10, 5) • It replaces text between the indicated start and end
• TextArea(String str, intnumLines, intnumChars, intsBars) positions with the specified replacement text.
:E.g; TextArea(“welcome”,10, 5, SCROLLBARS_BOTH) • void setColumns(int columns)
• It sets the number of columns for this text area.
• void setRows(int rows)
• It sets the number of rows for this text area.
Layout Manager
• Layout means the arrangements of components within the container.
• The task of layouting the control is done automatically by the Layout Manager.
• The Layout Managers are used to arrange components in a particular manner.
• The java Layout Managers facilitates us to control the positioning and size of the
components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes of the layout
manager.
• Layout Manager is set by using setLayout() method, comes under LayoutManager
interface.
• It is defined as: void setLayout(LayoutManager obj)
• Types of Layout Manager :
1. FlowLayout
2. BorderLayout
3. Gridlayout
4. GridbagLayout
Flow Layout
• The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow).
• Flow layout puts components (such as text fields, buttons, labels etc) in a row, if horizontal
space is not enough to hold all components then Flow layout adds them in a next row and so
on.
• All rows in Flow layout are center aligned by default.
• The default horizontal and vertical gap between components is 5 pixels.
• public FlowLayout(): Constructs a new FlowLayout with a centered alignment and a default
5-unit horizontal and vertical gap.
• pyblic FlowLayout(int align): Constructs a new FlowLayout with the specified alignment
and a default 5-unit horizontal and vertical gap.
• public FlowLayout(int align, int hgap, int vgap): Creates a new flow layout manager with
the indicated alignment and the indicated horizontal and vertical gaps.
BorderLayout
• The BorderLayout is used to arrange the components in five regions: north,
south,west,east and center.
• Each region (area) may contain one component only.
• public BorderLayout():Constructs a new border layout with no gaps
between the components.
• public BorderLayout (int hgap, int vgap):Constructs a border layout with the
specified gaps between the components.
GridLayout
• The java GridLayout class is used to arrange the components in a rectangular grid.
• One component is displayed in each grid.
• Constructors of GridLayout class
• public GridLayout(): Creates a grid layout with a default of one column per component, in
a single row.
• public GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
• public GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with the given horizontal and vertical gaps.
• setColumns(int cl): Sets the number of columns in this layout to the specified value.
• setHgap(int hgap): Sets the horizontal gap between components to the specified value.
• setRows(int rw): Sets the number of rows in this layout to the specified value.
• setVgap(int vgap): Sets the vertical gap between components to the specified value.
GridBagLayout
• The set of cells a component
• GridBagLayout is the most sophisticated and spans can be referred to as its
complex of the layouts provided in the display area.
development kit.
• A component's display area and
• The Grid bag layout (like grid layout) arranges
the way in which it fills that
components into a grid of rows and columns,
but lets you specify a number of settings to display area are defined by a set
fine-tune how the components are sized and of constraints that are
positioned within the cells. represented by the
• Unlike the grid layout, the rows and columns GridBagConstraints object
are not constrained to be a uniform size. • The GridBagConstraints object is
• With the GridBagLayout, you can organize initialized with a set of default
components in multiple rows and columns, values, each of which can be
stretch specific rows or columns when space customized to change the way the
is available, and anchor objects in different component will be layed out
corners. within the gridbag
gridx and
gridy
• The leftmost column has address gridx=0 and the top row has
address gridy=0.
• The value for gridx/gridy can either be an integer
corresponding to the explicit row/column or the value
GridBagConstraints.RELATIVE, which indicates that the
component should be placed in the row/column subsequent to
the row/column where the last component was placed.
• For example, when adding components to a row,
gridx=GridBagConstraints.RELATIVE places the component to
the right of the component just added to the row. If a
component was just added to Row 2 in Column 1, the next
component is added to Row 2 in Column 2.
• When adding components to a column,
gridy=GridBagConstraints.RELATIVE places the component
below the component just added to the column. If a
component was just added to Column 0 in Row 1, the next
component is added to Column 0 in Row 2.
gridwidth and gridheight
weightx and weighty
• The gridwidth and gridheight settings indicate the
number of cells in the display area for a component. • When the user resizes a window
• The default values are gridwidth=1 and gridheight=1 using a grid bag layout, the weightx
meaning that by default components are one column
wide (gridwidth), and one row high (gridheight). and weighty settings determine
• You can make a component two columns wide with how the components resize.
gridwidth=2 or three rows high with gridheight=3.
• Setting gridwidth to GridBagConstraints.REMAINDER
• By default the settings are
indicates the component should take up the weightx=0 and weighty=0, which
remaining number of cells in the row. means that when the window is
• Setting it to GridBagConstraints.RELATIVE indicates resized, the components stay
that the component should take up all the remaining grouped together in the center of
cells in the row except the last one.
• When you specify a component as the last or next-to-
the container.
last component in a row, you can give it a gridheight
value greater than one so the component spans
• If you give weightx>0, the
multiple rows. components expand in the x
• However, in this case, there is no way to make the direction (horizontally).
component wider than one column when it is the last
or next-to-last component in the row. • If you give weighty>0, the
components expand in the y
direction (vertically).
fill anchor
• The fill settings determines how a component fills
• When a component is smaller than its display
the display area defined by
gridx/gridy/gridwidth/gridheight.
area, you can anchor the component in the
following locations within its display area:
• The fill can be set to the following values:
• anchor=GridBagConstraints.CENTER (the
• GridBagConstraints.HORIZONTAL: The component default)
expands horizontally to fill the entire width of its anchor=GridBagConstraints.NORTH (top)
display area. anchor=GridBagConstraints.NORTHEAST (top-
• GridBagConstraints.VERTICAL: The component right)
expands vertically to fill the entire height of its anchor=GridBagConstraints.EAST (right)
display area. anchor=GridBagConstraints.SOUTHEAST
• GridBagConstraints.BOTH: The component (bottom-right)
expands to completely fill the entire display area. anchor=GridBagConstraints.SOUTH (bottom)
anchor=GridBagConstraints.SOUTHWEST
• GridBagConstraints.NONE: The component is sized
(bottom-left)
to its ideal size regardless of the size of the display
anchor=GridBagConstraints.WEST (left)
area.
anchor=GridBagConstraints.NORTHWEST(top-
left)
ipadx and ipady insets
• The layout manager calculates the size of a • The insets setting lets you specify the
component based on grid bag constraint settings minimum amount of space between
and the other components in the layout. the container edge and component
• You can specify an internal padding to increase the
calculated size of a component to make the • We can create insets with the Insets
component wider (ipadx) or taller (ipady) than its class
calculated size, yet not fill the entire display area • Insets(int top,int left,int bottom,int
the way the HORIZONTAL or VERTICAL fill setting
does.
right)
• By default ipadx and ipady are 0. • We can insets of 20 pixels on all the
• When you specify an ipadx value, the total edge by using
component width is its calculated width plus 2 public Insets getInsets()
times the padding (the padding is placed on both {
sides of the component). return(20,20,20,20);
• When you specify an ipady value, the total }
component height is its calculated height plus 2
times the padding (the padding is placed on the
Working with Menu and Menubar:
• A menubar is most useful component. • Menubar
• A menubar is associated with top level • To create a menubar, first of all create an
window only. i.e. only a Frame class object of class Menubar.
can have menubar.
• This class has only one constructor i.e. It,s
• Menubar is generated by coupling
default constructor, because Menubar do
three different classes: Menubar, menu
and menuitems not requires any parameters, title or settings.
• Each menu object contains list. • public Menubar()
• MenuItems can also be replaced by • Menu
object of CheckboxMenuItem objects; • The object of Menu class is a pull down
which contains checkable menu-items. menu component which is displayed on the
menu bar.
• Menu class has following constructor.
• Menu(String menu_title): Eg File, Edit, etc
MenuItems CheckboxMenuItem:
• MenuItem()
• MenuItem can be replaced by
• Constructs a new MenuItem with an CheckboxMenuItem object.
empty label and no keyboard shortcut.
• It has following constructors:
• MenuItem(String label)
1) CheckboxMenuItem()
• Constructs a new MenuItem with the
specified label and no keyboard 2) CheckboxMenuItem(String title)
shortcut. 3) CheckboxMenuItem(String title,
• MenuItem(String label, MenuShortcut booleanchecked)
s) • Methos:
• Create a menu item with an associated 1)Void setState(Boolean checked)
keyboard shortcut. 2)Boolean getstate()
Working with dialogbox:
• Dialog boxes are small windows.
• It is a subclass of window class.
• Dialog Boxes are used to hold the controls and also used for user input.
• There are two types of dialog boxex i.e. Model dialogbox and Modelless dialog box.
• Dialogbox does not contain any menubar, minimize and maximize button.
• Constructors :
• 1)Dialog(Frame parent_window_object, Boolean visibility)
• 2)Dialog(Frame parent_window_object, String title, Boolean visibility)
• Methods
• setTitle(String title)
• setSize(int width, int height);
• setVisible(Boolean visible);
• void dispose()
FileDialog class
• FileDialog control represents a dialog window from which • Methods:
the user can select a file. • String getDirectory()
• Field • Gets the directory of this file dialog.
• static int LOAD -- This constant value indicates that the • String getFile()
purpose of the file dialog window is to locate a file from
which to read. • Gets the selected file of this file dialog.
• static int SAVE -- This constant value indicates that the • int getMode()
purpose of the file dialog window is to locate a file to • Indicates whether this file dialog box is for
which to write. loading from a file or for saving to a file.
• Constructors • void setDirectory(String dir)
• FileDialog(Frame parent) • Sets the directory of this file dialog window
• Creates a file dialog for loading a file. to be the specified directory.
• FileDialog(Frame parent, String title) • void setFile(String file)
• Creates a file dialog window with the specified title for • Sets the selected file for this file dialog
loading a file. window to be the specified file.
• FileDialog(Frame parent, String title, int mode) • void setMode(int mode)
• Creates a file dialog window with the specified title for • Sets the mode of the file dialog.
loading or saving a file.
Introduction to Swing
• Swing is a set of classes that provides more powerful and flexible
Components than are possible with the AWT.
• In addition to the familiar components, such as buttons, check boxes, and
labels, Swing supplies several exciting additions, including tabbed panes,
scroll panes, trees, and tables. Even familiar components such as buttons
have more capabilities in Swing.
• import javax.swing.*;
• Swing is a lightweight Java graphical user interface (GUI) that is used to
create various applications.
• Swing components are written in Java language.
• Swing has platform-independent components.
• It is a part of Java Foundation Classes(JFC).
Features of Swing
• Platform Independent : It can run on any platform that supports Java. Thus, Swing-based
applications can run on Windows, Mac, Linux, or any other Java-compatible operating
system.

• Lightweight : Java Swing provides a pluggable look and feels that allows developers to
customize the appearance of the GUI according to the user’s preferences.

• Pluggable look and feel : Java Swing provides a set of lightweight components that are
easy to use and customizable.

• Rich controls : Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
Difference Between AWT and Swing
Icons and Labels
• Icons:
• In swing icons are encapsulated by the ImageIcon class which paints an icon from an image.
• The constructors of Icon are:
• ImageIcon(String filename) : Creates an ImageIcon from the specified file.
• ImageIcon(URL location) : Creates an ImageIcon from the specified URL.

• JLabel:
• JLabel creates an label used to provide the information and instruction.
• It is used to display a single line of read only text (Passive Component).
• The constructors of JLabel are:
• JLabel() : creates a new label with the empty string.

• JLabel(String s) : creates a new label with the string specified.

• JLabel(Icon i) : creates a new label with a image on it which nothing but icon.
• JLabel(String s, Icon i, int alignment) : creates a new label with a string, an image and a specified alignment as LEFT,RIGHT and
CENTER.
JButton JButton Methods
 JButton component has a label and generates an event when pressed.
void setIcon(ImageIcon obj) : It is used to set
 JButton can also have an Image.
the specified Icon on the button.
 It inherits or derived from AbstractButton class.

 The JButton class is used to create a labeled button that has platform ImageIcon getIcon() : It is used to get the Icon
independent implementation. of the button.
• JButton() : It creates a button with no text and icon(image).
void setText(String label) : It is used to set
• Example JButton jb=new JButton();

• JButton(String label) : It creates a button with the specified specified text on button.
text or string. String getText() : It is used to return the text of
• Example JButton jb=new JButton(“Button1”);

the button.
• JButton(ImageIcon obj) : Creates a button with an
icon(Image). void setEnabled(Boolean b) : It is used to set

• JButton(String label, ImageIcon obj) : Creates a button with the button enable or disable by using boolean
an initial text and an Image icon. value true or false.
JTextField

• JTextField is the mostly used and simplest swing component

• JTextField is a part of javax.swing package.

• The class JTextField is a component that allows editing of a single line of text.

• JTextField inherits the JTextComponent class.

JTextField() : It creates a new TextField.

JTextField(int columns) : It creates a new empty TextField with specified number of columns.

JTextField(String text) : It creates a new empty text field initialized with the given string.

JTextField(String text, int columns) : It creates a new empty TextField with the given string
and a specified number of columns.
JTextArea
• JTextArea is a part of java Swing package .
• It represents a multi line area that displays text.
• It is used to edit the text .
• JTextArea inherits JTextComponent class and super class is JComponent.

 JTextArea() : It used to constructs a new blank text area .

 JTextArea(String s) : It creates a new text area with a given initial text.

 JTextArea(int row, int column) : It creates a new text area with a given number of rows and columns.

 JTextArea(String s, int row, int column) : It is used to constructs a new text area with a given number of

rows and columns and a given initial text.

 JTextArea(Document doc) : Constructs a new JTextArea with the given document model

 JTextArea(Document doc, String s, int row, int column) : Constructs a new JTextArea with the specified

number of rows and columns, and the given model.


JCheckBox

• The JCheckbox class is used to create a checkbox.

• It is used to turn an option on (true) or off (false).

• JCheckbox Constructors:

• JCheckBox() : It creates a new checkbox with no text or icon.

• JCheckBox(String text) : It creates a new checkbox with the text.

• JCheckBox(String text, boolean state) : It creates a new


checkbox with the text and the state value specifies whether it is
selected or not.
JCheckbox Constructors: JCheckbox Methods:
• JCheckBox(ImageIcon obj) : It creates a new • void setText(String s) : It sets the text to the checkbox by
checkbox with the specified icon(Image). the given text.

• JCheckBox(ImageIcon obj, boolean state) : It is • String getText() : It returns current text of the checkbox.

used to creates a new checkbox with the icon and • void setIcon(Icon i) : It sets the icon(image) to the
the state value specifies whether it is selected or not. checkbox by the given icon.

• JCheckBox(String text, ImageIcon obj) : It • ImageIcon getIcon() : It returns the image of the
checkbox.
creates a new checkbox with the string and the
image icon. • void setSelected(boolean state) : It sets the checkbox to
be selected if boolean value is true or not selected if
• JCheckBox(String text, ImageIcon obj,Boolean
boolean value is false.
state) : It creates a new checkbox with the text as
• boolean isSelected(): It is used to check the item is
string and the icon and the state value specifies
selected or not.
whether it is selected or not.
JRadioButton
• The JRadioButton class is used to create a radio button.

• It is used to choose one option from multiple options.

• In swing we must add the JRadioButton in ButtonGroup.


• JRadioButton Constructors:

• JRadioButton() : Creates an unselected radio button with no text.

• JRadioButton(String text) : Creates an unselected radio button with specified text.


• JRadioButton(String text, boolean state): Creates a radio button with the specified text and selected status.
• JRadioButton(ImageIcon obj) : It creates a new JRadioButton with the specified icon(Image).
• JRadioButton(ImageIcon obj, boolean state) : It is used to creates a new JRadioButton with the icon and the
state value specifies whether it is selected or not.
• JRadioButton(String text, ImageIcon obj) : It creates a new JRadioButton with the string and the image icon.
• JRadioButton(String text, ImageIcon obj,Boolean state) : It creates a new JRadioButton with the text as
string and the icon and the state value specifies whether it is selected or not.
JComboBox
• JComboBox is a part of Java Swing package.

• JComboBox inherits JComponent class .

• JComboBox shows a popup menu that shows a list and the user can select a option from
that specified list.

JComboBox Constructors:
JComboBox() : It creates a new empty JComboBox .

JComboBox(Vector items) : It creates a new JComboBox with items from the specified
vector(to select different items of different datatypes) or same types of data.

• To add the new items in JComboBox we can use the addItem() method.
Advanced Swing Components

• JTabbedPane
• JScrollPane
• JTree
• JTable
• JProgressBar
• Tool Tips
JTabbedPane
• JTabbedPane is a component which appears as a group of multiple tabs, each containing a title ,panel and group of
components.

• When user can click on a tab, only data related to that tab will be displayed and user can interact with it.

• The main purpose of JTabbedPane is to provide configuration related options.

• In simple JTabbedPane means same frame can be shared among the different layouts.

• Steps to Create JTabbedPane:

1. Define required number of panel classes with components.

2. Create JTabbedPane object.

3. Call its add () method with title and panel object.

4. Add the tabbed pane into container.

Default Constructor of JTabbedPane are:


 JTabbedPane() : Creates an empty TabbedPane with a default tab placement of JTabbedPane(Top).

 JTabbedPane(int tabPlacement) : Creates an empty TabbedPane with a specified tab placement(Location).The value of
JScrollPane
• JScrollPane is a component in the Java • JScrollPane(Component comp) : This constructor creates a
JScrollPane with the specified view component as the scrollable
Swing library that provides a scrollable view of
content.
another component, usually a JPanel or a
• JScrollPane(int vertical, int horizontal) : This constructor creates
JTextArea. an empty JScrollPane with the specified vertical and horizontal
scrollbar.
• A ScrollPane is a Container. A ScrollPane handles
• JScrollPane(Component comp ,int vertical, int horizontal) :
its own events and performs its own scrolling.
This constructor creates an JScrollPane with the specified
• When screen size is limited, we use a scroll pane to component with vertical and horizontal scrollbar.

display a large component or a component whose • The horizontal and vertical scrollbar are defined in
ScroolPaneConstants interface and theses constants are:
size can change dynamically.
1. HORIZONTAL_SCROLLBAR_ALWAYS
• JScrollPane class which
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
extends JComponent class. 3. VERTICAL_SCROLLBAR_ALWAYS

4. VERTICAL_SCROLLBAR_AS_NEEDED

JTable
• The JTable class is used to display data in tabular form.

• JTable is a component that display rows and columns of data.

• JTable must be added to the JScrollPane to see all records of the table Properly.

• Steps to create table in scroll pane are:

1. Create JTable object with data and column titles.

2. Create JScrollPane object and provide the table into it.

3. Add the scroll pane into the content pane or any frame.

• JTable(): It creates empty JTable.

• JTable(Object[][] data, Object []Column): A table is created with the specified name where
JTree
• The JTree is a type of GUI(Graphic User Interface) that displays information in a hierarchical way.
• JTree is an expandable and collapsible component containing sub_trees to display.
• It has a 'root node' at the top most which is a parent for all nodes in the tree.
• JTree inherits from JComponent class.
• To create JTree we must be include following package;
• Import javax.swing.tree.*;
• DefaultMutableTreeNode : This class is used to create a Node.
• Example: DefaultMutableTreeNode obj=new DefaultMutableTreeNode(“Name of node”);
• The default constructor of JTree is JTree(TreeNode obj), obj is nothing but root node
• Example: JTree jt=new JTree(obj);

• To create hierarchy of node the add() method of DefaultMutableTreeNode can be used.


(In simple to add the child-nodes into the respective root-node).
• Example: obj1.add(obj);
JProgressBar
• The JProgressBar class is used to display the progress of the task.

• JProgressBar shows the percentage of completion of specified task.

• It may even display the text as specified. As the task reaches its completion, the progress bar fills up.

• A progress bar is a component that is used when we process lengthy tasks. It is animated so that the user knows
that our task is progressing.

• The progress bar use following methods :


• setValue(int Value) : It set Progress bar’s current value in value variable or initial value of progress bar.
• setStringPainted(true) : It is used to show the progress of any given task in percentage or It is used to
determine whether string should be displayed.
JProgressBar Constructors:
• JProgressBar() : creates an progress bar with no text on it or no processing string and it
is Horizontal.
• Example: JProgressBar jpb=new JProgressBar();

• JProgressBar(int min, int max) : creates an progress bar with specified minimum and
maximum value.
• Example: JProgressBar jpb=new JProgressBar(0,100);

• JProgressBar(int orientation) : creates an progress bar with a specified orientation. if


SwingConstants.VERTICAL is passed as argument a vertical progress bar is created, if
SwingConstants.HORIZONTAL is passed as argument a horizontal progress bar is
created.
• Example: JProgressBar jpb=new JProgressBar(SwingConstants.VERTICAL );

• JProgressBar(int orientation, int min, int max) : creates an progress bar with
specified minimum and maximum value and a specified orientation. if
SwingConstants.VERTICAL is passed as argument a vertical progress bar is created, if
SwingConstants.HORIZONTAL is passed as argument a horizontal progress bar is
created.
• Example: JProgressBar jpb=new JProgressBar(SwingConstants.VERTICAL,0,100 );
JToolTip
• ToolTip is very important component that shows a temporary pop-up message when
the mouse pointer stays on component.

• The pop-up message can be a short description or labelled information of any


component.

• We can add tooltip text to almost all the components in java swing.

• When the cursor enters the boundary of the component a pop up appears and text is
displayed that is nothing but tooltip.

• To add tool tip to a component object we use setToolTipText()which is defined as;


• void setToolTipText(String text)
Event Handling
• Event Sources
• Event Listeners
• Event Classes
Introduction
• This examines an important aspect of Java: the event.
• Event handling is fundamental to Java programming because it is integral to the
creation of GUI-based programs.
• Any program that uses a graphical user interface, such as a Java application written
for Windows, is event driven.
• Thus, you cannot write these types of programs without a solid command of event
handling.
• Events are supported by java.awt.event package.
• Most events to which your program will respond are generated when the user
interacts with a GUI-based program.
• There are several types of events, including those generated by the mouse, the
keyboard, and various GUI controls, such as a push button, scroll bar, or check box.
• It then examines the main event classes and listeners [interfaces] used by the AWT
Event
• In the delegation model, an event is an object that describes a state change in a
source.
• It can be generated as a consequence of a person interacting with the elements in
a graphical user interface. [direct communication]
• Some of the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the
mouse.
• Events may also occur that are not directly caused by interactions with a user
interface.[indirect communication]
• For example, an event may be generated when a timer expires, a counter exceeds
a value, a software or hardware failure occurs, or an operation is completed.
• You are free to define events that are appropriate for your application.
Event Source
• A source is an object that generates an event.
• This occurs when the internal state of that object changes in some way.
• Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive notifications
about a specific type of event.
• Each type of event has its own registration method.
• public void addTypeListener(TypeListener el)
• Here, Type is the name of the event, and el is a reference to the event listener.
• For example, addKeyListener( ) , addMouseMotionListener( )
• When an event occurs, all registered listeners are notified and receive a copy of
the event object. This is known as multicasting the event.
• In all cases, notifications are sent only to listeners that register to receive them.
• Some sources may allow only one listener to register. The general form of
such a method is this:
• public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException
• Here, Type is the name of the event, and el is a reference to the event
listener.
• When such an event occurs, the registered listener is notified.
• This is known as unicasting the event.
• A source must also provide a method that allows a listener to unregister an
interest in a specific type of event.
• public void removeTypeListener(TypeListener el)
Event Listeners
• A listener is an object that is notified when an event occurs.
• It has two major requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. It must implement methods to receive and process these notifications.
• The methods that receive and process events are defined in a set of
interfaces found in java.awt.event.
• For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
• Any object may receive and process one or both of these events if it provides
an implementation of this interface.
Event Classes
• The classes that represent events are at the core of Java’s event handling
mechanism.
• Thus, a discussion of event handling must begin with the event classes.
• It is important to understand, however, that Java defines several types of
events and that not all event classes can be discussed in this chapter.
• The most widely used events are those defined by the AWT and those
defined by Swing.
• At the root of the Java event class hierarchy is EventObject, which is in
java.util.
• It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
Main Event classes of java.awt.event
ActionEvent class
• The getSource() method returns the object that generates the event (the
who)
• getWhen()
• getModifiers()
• getActionCommand()
ActionListener Interface
• public interface ActionListener extends EventListener
• The listener interface for receiving action events.
• The class that is interested in processing an action event implements this
interface
• The object created with that class is registered with a component, using
the component's addActionListener method.
• When the action event occurs, that object's actionPerformed() method
is invoked
• Method:
• void actionPerformed(ActionEvent e)
The Delegation Event Model
• The modern approach to handling events is based on the delegation event model,
which defines standard and consistent mechanisms to generate and process events.
• Its concept is quite simple: a source generates an event and sends it to one or more
listeners. In this scheme, the listener simply waits until it receives an event.
• Once an event is received, the listener processes the event and then returns.
• The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events.
• A user interface element is able to “delegate” the processing of an event to a
separate piece of code.
• In the delegation event model, listeners must register with a source in order to
receive an event notification.
• This provides an important benefit: notifications are sent only to listeners that want
to receive them
MouseEvent
• This event indicates a mouse action occurred in a component. This low-level event is
generated by a component object for Mouse Events and Mouse motion events.
• Mouse Events
• a mouse button is pressed
• a mouse button is released
• a mouse button is clicked (pressed and released)
• a mouse cursor enters the unobscured part of component's geometry
• a mouse cursor exits the unobscured part of component's geometry
• Mouse Motion Events
• a mouse is moved
• the mouse is dragged
• Class declaration
• public class MouseEvent extends InputEvent
MouseListener
• public interface MouseListener extends EventListener
• The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a
component. (To track mouse moves and mouse drags, use the MouseMotionListener.)
• void mouseClicked(MouseEvent e)
• Invoked when the mouse button has been clicked (pressed and released) on a component.
• void mouseEntered(MouseEvent e)
• Invoked when the mouse enters a component.
• void mouseExited(MouseEvent e)
• Invoked when the mouse exits a component.
• void mousePressed(MouseEvent e)
• Invoked when a mouse button has been pressed on a component.
• void mouseReleased(MouseEvent e)
• Invoked when a mouse button has been released on a component.
• For Example:
• MouselistenerExample.java
MouseMotionListener methods
• void mouseDragged(MouseEvent e)
• Invoked when a mouse button is pressed on a component and then
dragged.
• void mouseMoved(MouseEvent e)
• Invoked when the mouse cursor has been moved onto a component
but no buttons have been pushed.
• Example
KeyListener
1. void keyPressed(KeyEvent e)
• Invoked when a key has been pressed.
2. void keyReleased(KeyEvent e)
• Invoked when a key has been released.
3. void keyTyped(KeyEvent e)
• Invoked when a key has been typed.
FocusListener
• void focusGained(FocusEvent e)
• Invoked when a component gains the keyboard focus.
• void focusLost(FocusEvent e)
• Invoked when a component loses the keyboard focus.
ItemListener
• public interface ItemListener extends EventListener
• The listener interface for receiving item events.
• The class that is interested in processing an item event implements this
interface.
• The object created with that class is then registered with a component
using the component's addItemListener method.
• When an item-selection event occurs, the listener object's
itemStateChanged method is invoked
• void itemStateChanged(ItemEvent e)
• Invoked when an item has been selected or deselected by the user.
TextListener
• public interface TextListener extends EventListener
• The listener interface for receiving text events.
• The class that is interested in processing a text event implements this interface.
• The object created with that class is then registered with a component using
the component's addTextListener method.
• When the component's text changes, the listener object's textValueChanged
method is invoked
• Method
• void textValueChanged(TextEvent e)
• Invoked when the value of the text has changed.

You might also like