0% found this document useful (0 votes)
10 views

AWT and Swing

The document provides an overview of Java's Abstract Window Toolkit (AWT) and Swing for creating graphical user interfaces (GUIs). It covers the hierarchy of AWT components, event handling, and various GUI controls such as buttons, text fields, checkboxes, and menus. Additionally, it highlights the differences between AWT and Swing, emphasizing Swing's lightweight components and modern look.

Uploaded by

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

AWT and Swing

The document provides an overview of Java's Abstract Window Toolkit (AWT) and Swing for creating graphical user interfaces (GUIs). It covers the hierarchy of AWT components, event handling, and various GUI controls such as buttons, text fields, checkboxes, and menus. Additionally, it highlights the differences between AWT and Swing, emphasizing Swing's lightweight components and modern look.

Uploaded by

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

JAVA AWT & Swings

Lecturer: Prof. Satishkumar Mulge


E-mail: [email protected]

Feb 10, 202


Introduction to User Interface with AWT and Swing
• Oops language like c++ are providing very poor
user interface. (Graphics methods)
• Java provides the Abstract Window Toolkit
(AWT) , and Swings for the graphics programming.
• This AWT provide the foundation or the base of
the Java Graphics Programming and even the
Swing package is based on the AWT.
• To handle these components we need event
handling.
• Event handling is also needed for Applet
programming.
AWT Hierarchy
• Different windows classes are defined by AWT which adds
functionality with each level.

Object

Component

Container

Window Panel

Frame Applet

JFrame JApplet
Component
• It is an abstract class and all GUI component that
interacts with the user are subclasses of component
class
• It defines various methods for managing events such
as keyboard and mouse.
• It also defines attributes to store current foreground
and background color and font.
Container
• It inherits various methods and attributes of component class
and having additional methods of nesting other component
objects.
• A container positions various GUI components within it.

Windows
• This class is used to create a top level window.
Generally, windows objects are not created directly,
subclass of window is used to place on the desktop.
Frame
 Frame class is a subclass of window and it
has title bar, menu bar, borders etc.
 Frame( ) constructor is used to create Frame
windows.
 There are two types of frame constructors
 Frame ( ) ;
 Frame ( String title);
 There are two important methods which are
important to decide the size of the frame
and visibility of the frame.
 To decide the size of the frame setSize( )
method is used.
Frame
• Syntax :
• setSize( int width, int height);
• Example:
• setSize( 300, 200);
• To visible the frame after creation we use
setVisible( ) method.
• Syntax :
• setVisible(VisibleFlag);
• Example :
• setVisible(True);
• Example : FrameDemo.java
JFrame
• Constructors :
• JFrame( ) : Constructs s new frame that is
initially invisible
• JFrame(String titel) : creates a new,
initially invisible frame with the specified

title.
Methods :
• void setTitle(String title)
• void setSize(int width, int height)
• void setLocation( int x, int y) (left,top)
• void setDefaultCloseOperation(int op)
• JFrame.EXIT_ON_CLOSE
• JFrame.HIDE_ON_CLOSE
• JFrame.DO_NOTHING_ON_CLOSE
• JFrame.DISPOSE_ON_CLOSE
• void setLayout(LayoutManager manager)
AWT
• At the time of creation of the Java 1.0 for graphics User
Interface , Sun provides the Abstract Window Toolkit.
• This is one of reasons of the popularity of Java of use of AWT
for user interface.
• Abstract window programming provides the magic in the look
for the Window, and provides the better look for the user
environment.
• There are various popular classes which are having AWT are
as follows.
• Applets • List
• Button • Frame
• Label • Dialog
• Menu • Panel
• ComboBox • PopUpMenu
• TextField • RadioButton
• Window • ScrollBar
• TextAres
Swing
 Swing is the option by which we can use the java Graphics.
 Swing provides the components which give the modern look
for the user interface, these components provide the toolkit.
 The major components are labels, buttons, list controls, table
controls ect.
 Swing is the one of the part of the Java Foundation Classes
(JFC). The JFC includes the rich graphics programming for
the Graphical User Interface.
 There are various controls provided by the Swing which are as
follows
 Image Buttons
 Color choosers
 List
 Tables
 Toolbars
 HTML text areas
 Trees
AWT & Swing
• Naming Convention : the components of the Swing
begins with capital letter J. There over 250 classes and
40 User Interface components which prebuilt in swing
package.
Example : JButton, JLabel,
• Lightweight Component : The graphics program of AWT
takes large number of windows which takes huge
memory. Such components are heavyweight.
• On other hand swing controls are simple drawn as
image in their containers and don’t have an operating
platform window of their own at all, so they use far
fewer system resources. Therefore they are called
lightweight components
AWT and its controls
• To develop GUI based applications, the fundamental elements
that are needed and are available in two packages java.awt
and javax.swing.
• The primary repository for class that we use to create GUI is
available in java.awt.
• Following are controls are supported by AWT or Swing .
• Label /JLabel
• Button / JButton
• TextField / JTextField
• CheckBox / JCheckBox
• RadioButtons / JRadioButton
• List / JList
• Combo Boxes – JCombo
• Menus – JMenu
• JMenuBar
• Scrollbars (JScrollBar)
• Dialogs
• JOptionPane
• JColorChooser
Label
 Label class is used to create a Label control.
 Label class is having following constructors
 Label ()
 Creates a blank label
 Label (String)
 Creates a label containing a specified string
in parameter.
 Label (String, int)
 Creates a label containing a specified string
with alignment which are specified in
second parameter.
 The alignment must be one of the three constant values.
 Label.LEFT
 Label.RIGHT
 Label.CENTER
Label
Methods
• void setText(String )
• Set or change the text in a label
• String getText()
• Obtain the text in a label
• void setAlignment(int)
• set or change the alignment of a text in a label
• Int getAlignment()
• Obtain the current alignment
Push Button :
• It is a component that contains a label and generates an event when it is
pressed.
• Button class is used to create push buttons. It has following constructors
• Button () -- > creates button with no label
• Button (String) -- > creates a button containing a specified string in
parameter.
• To create button in the AWT we perform the following steps
• Declare the button as variable
Button b1,b2,b3;
• Within frame creation method first we have to initialize the button by
dynamic.
b1 = new Button(“OK”);
b2 = new Button(“CANCEL”);
b3 = new Button(“Press Here”);
• Now we can add the labeled button to the frame with the add method.
add(b1);
add(b2);
• To make event with the button we must put them with ActionListener ( )
method as follows.
b1.addActionListener(this);
b2.addActionListener(this);
JButton :
• Swing Button provide features that are not found in
the Button class defined by the AWT
• That is we can associate an icon with a Swing
button.
• JButton class provides the functionality of a push
button.
• JButton allows an icon, a string or both to be
associated with the push button.
• Some of its constructors are
• JButton ( Icon i) ;
• JButton (String s);
• JButton (String s, Icon s);
• Here s and I are the String and icon respectively
used for the button.
• Example :

JButton
• JButton( ) Constructor
• Implements ActionListener
• JButton(Icon icon) • actionPerformed(ActionEvent e)
• JButton(String text)
Methods
• JButton(String text, Icon icon)
• void setText( String text)
• String getText( )
• void setIcon(Icon icon)
Methods
• Icon getIcon( )
• String getActionCommand( )
• void addActionListener( ActionListener al)
• void removeActionListener( ActionListener al)
• void setToolTipText( String text )
• String getToolTipText( )
TextField
• The TextField class implements a single – line text
entry, usually called an edit control.
• This TextField is subclass of the TextComponent
• The TextField uses the following components
• TextField tf1 = new TextField()
• TextField tf1 = new TextField(int numChars )
• TextField tf1 = new TextField(String str)
• TextField tf1 = new textField(String str, int
numChars)
• The TextField control had methods getText ( ) &
setText( String str) for getting and setting the
values.
void setEchoChar( char c)
char getEchoChar( )
JTextField
•The Swing text field (JTextField) is
encapsulated by the JTextComponent
class, which extends Jcomponent
•Constructors for the JTextField are as
•JTextField ( )
•JTextField (int cols)
•JTextField ( String s , int cols)
•JTextField (String s )
Example : ButtonTexFieldDemo
JTextField
• void setText( )
• String getText( )
• void setEditable ( boolean state)
• boolean isEditable( )
• void addActionListener(ActionListener al )
• void removeActionListener( ActionListener al)
Check Box :
• A Checkbox control is used to toggle an
option.
• It has following constructors
• Checkbox ( )
• creates check box without label. Initially
state is unchecked
• Checkbox (String)
• Creates a checkbox with label specified ,
initially state is unchecked
• Checkbox (String, boolean)
• checkbox with label and initial state is
specified either true or false in second
parameter.
Check Box
Methods
• boolean getState( ) :retries the current state
• void setState (boolean) : sets the state true/false
• String getLabel() : obtain the label associated
• void setLabel (String ) : set the label as specified.
• Checkbox getselectedCheckbox( );
• void setSelectedCheckbox(Checkbox which)
•Example : CheckBoxDemo.java
Check Box Group:
• This class is used to create group of checkboxes.
• From the group of check boxes only one check box be checked
at a time
• These check boxes are also called radio buttons
• It has following constructor
•CheckboxGroup CheckboxGroup()
returns group name
• Checkboxes of checkboxgroup can be created using following
constructors:

• Checkbox (String, boolean, CheckboxGroup)


• Checkbox (String,CheckboxGroup,boolean)
These creates checkbox with specified label and groupname as
parameter . The boolean type parameter specifies the initial
state true/false.
Radiobuttons
• Radio buttons are special kind of checkbox, and we can use
radio buttons in groups.
• Only one radio button in a group may be selected at a time,
when the user selects one radio button in a group, the other in
a group are automatically rejected.
• When we add checkbox to a checkbox group, they become
radio button automatically.
• Following methods are communally used.
• getSelectedCheckbox ( )
To determine which radiobox is a group is currently selected.
• setSelectedCheckbox( )
to set radiobox.
Example : CheckBoxRedio.java
JCheckbox
• The JCheckBox class, which provides the functionality of
check box.
• Some of its construnctors are
• 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)
• Here I is the icon for the button.
• The text is specified by s.
• If state is true, the check box is initially selected. Otherwise, it
is not.
• The state of the check box can be changed via
• void setSelected( boolean state);
• here state is true if the checkbox should be checked.

JRadioButtons
• Radio buttons are supported by the
JRadioButton class, which is concrete
implementation of AbstractButton.
• Constructors of the radio are as follows
• 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)
• Where I = icon for button, s = text specification, state
= value of selected of button true or false.
• Initially it is true , it is selected.

Example : CreateRadioButton.java , SelectRadioButton.java


Choice
• The Choice class is used to create a pop – up list of item from
which the user may choice.
• Following methods are communally used
• void add(String name )
• To add a selection to the list.
• getSelectedIndex ( )
• To determine which item’s index is currently selected.
• getSelectedItem( )
• To determine which item is currently selected.
• getItemCount ( )
• To obtain the number of items in the list
• void select ()
• To set the currently selected item.
• void select ( String name) .
• Example ChoiceDemo.java
JList
• A component that display a list of objects and allows the user to
select one or more items.
JList Constructor
1. JList()
Constructs a JList with an empty model.
2. JList(Object[] listData)
Constructs a JList that displays the elements in the specified array.
3. JList(Vector listData)
Constructs a JList that displays the elements in the specified Vector.
JList Mothods
1. int getSelectedIndex( )
returns the selected cell index
2. int[ ] getSelectedIndices( )
returns an array of all the selected indices, in increasing order.
3. Object getSelectedValue( )
Returns the value of the selected cell index when only a single item is selected in the
list.
4. Object[ ] getSelectedValues( )
Returns an array of all the selected values, in increasing order based on their indices
in the list.
5. Boolean isSelectedIndex(int index);
6. public void clearSelection( )
7. void setSeelctionMode(int selectionMode)
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
Event handlers

Implement interface:
ListSelectionListener( javax.swing.event )
Override method :
public valueChanged(ListSelectionEvent lse)
Register handler :
addListSelectionListener(ListSelectionListener lse)
Menu (JMenu)
• We can add AWT menus to Frame class windows using three
AWT classes Menubar , Menu, and MenuItem.
• The first class we use is the MenuBar class, which adds a
menu bar to a frame window.
• After we have added a menu bar to a frame window, we can
add menus, such as a File menu and Edit menu, to that menu
bar using Menu class.
• Finally, we add menu items to the menus in our program using
the MenuItem class.
• We create the individual menus in a MenuBar with the Menu
class.
• Constructors of the Menu class.
• Menu ( )
• Menu ( String lable)
• Menu (String lable, boolean tearOff)

• Example : MenuBarExample.java
• Example : PopUpMenu.java
JScrollPane
• This is the constructor of JScrollPane Class. It
extends from the JComponent. This constructor
uses to create a JScrollPane . This JScrollPane
displays the horizontal and vertical scroll bar. It
takes the components for which the scroll pane
has to be set.
Creating a JTabbedPane Container in
Java Swing
• JTabbedPane:
This is the class of javax.swing.*; package which creates the
JTabbedPane component of Java Swing which contains separate
button for the separate tab. You can also container component with
the specific tab.
• add():
This is the method of JTabbedPane class which is used to add
container component to the JTabbedPane component of Java Swing.
This method takes different-different types of arguments but in this
program this method has taken two argument, first is the title for the
tab and another is the component name which is specified for a
particular tab to show for that.

JComboBox
ComboBox is a drop – down list of items from which user can
select
• Class JComboBox is used to create combo box
• It generates ItemEvent Methods
• void addItem(Object Obj)
• Constructors • void insertItemAt(Object obj,int pos)
– JComboBox() • Object getItemAt(int pos)
– JComboBox(Object [] data) • Object getSelectedItem( )
– JComboBox(vector data) • void removeAllItems( )
• void removeItemAt(int pos)
• void removeItem(Object obj)
• int getItemCount( )
• void addActionListener
(ActionListener al)
• void addItemListener( ItemListener il)

JTextArea
A JTextArea is multi-line area that display pain text.
• It is lightweight component which is source compatible with
the java.awt.TextArea class
• Constructors Methods
– JTextArea( ) • void append( String str)
• void insert( String text, int pos)
– JTextArea(int rows,int cols)
• void replaceRange(String str ,int
– JTextArea(String text) start, int end)
– JTextArea(String text,int rs,int cs)
JOptionPane
• JOptionPane class makes it easy to pop up standard
dialog box that prompts users for a value or informs
them of something
• Static methods
– showConfirmDialog()
Asks a confirmaing question
– showInputDialog( )
Prompts for some input
– showMessageDialog( )
Tell the user about something that has happened.
• int showConfirmDialog(Component parentcomponent,
Object message,
String titel,
int optionType,
int messageType)
• int showInput Dialog(Component parentcomponent,
Object message,
String titel,
int optionType,
int messageType)
• int showMessageDialog(Component parentcomponent,
Object message,
String titel,
int optionType,
int messageType)

• MessageType
– ERROR_MESSAGE :used fro error messages
– INFORMATION_MESSAGE : used fro information messages
– QUESTION_MESSAGE : used for questions

• OptionType
– DEFAULT_OPTION
– YES_NOT_OPTION
– YES_NO_CANCEL_OPTION
– OK_CANCEL_OPTION
• When one of the method returns an integer, the possible values are
– YES_OPTION
– NO_OPTION
– CANCEL_OPTION
– OK_OPTION
– CLOSED_OPTION
Example
• JOptionPane.showMessageDialog(null,”alert”,”alert
”,JOptionPane.ERROR_MESSAGE)
• JOptionPane.showConfirmDialog(null,”choose one
”,JOptionPane.YES_NO_OPTION)
Layout Manager and Layouts
• For the arrangement of component within a container, Layout manger can be
used.
• A layout manager automatically arranges our controls within a window by
using some type of algorithm.

• The setLayout( ) method is to set the layout.


• the setLayout( ) method has the following general form
• void setLayout( LayoutManager layoutObject)
• java defines the several layout manager
1. FlowLayout
2. GridLayout
3. BorderLayout
4. CardLayout
FlowLayout
• Places controls in the order on which they are
added from left to right and from top to bottom
• Constructors:
• FlowLayout()
• FlowLayout(int align)
• FlowLayout(int align,int hgap,int vgap)
where align can take values
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
GridLayout
• The GridLayout manager organizes the components
by placing them in a rectangular grid consisting of
rows and columns.

• Constructors:
• GridLayout()
• GridLayout(int rows,int cols)
• GridLayout(int rows,int cols,int hgap,int vgap)
BorderLayout
• Organizes the components along North, south, east and west borders and
in the center of container
• Only one object can be added on each region.
• To add a componet to specified region, the add method is used.
• The various constants in the BorderLayout manager are
• BorderLayout.NORTH
• BorderLayout.SOUTH
• BorderLayout.EAST
• BorderLayout.WEST
• BorderLayout.CENTER
• Constructors:
• BorderLayout()
• BorderLayout(int hgap,int vgap)
Syntax to add component:
add(Component obj,Object region)
• E.g
• add(button1, BorderLayout.NORTH)
CardLayout
• In this layout different cards are created and each
card is an object of type Panel.
• Components are placed in a card.
• The cards that form the deck are also an object of
the type Panel.
• Thus, we have to create a Penal that contains the
deck and Panel for each card in the deck.
• Then add these panels to the panel for which that
layout manager is CardLayout.
• After this add that Panel to the frame wndow.
• Constructors:
CardLayout()
CardLayout(int hagp,int vgap)
• Once a deck is created, we can activate a card by
calling one of the following methods of class
CardLayout:
void first( Deck) //Shows the first card in the deck.
void last( Deck) //Shows the last card in the deck.
void next( Deck) //Shows the next card in the deck.
void previous( Deck) //Shows the previous card in the deck.
void show( Deck,card) //Shows specific card.
Event Handling
• In GUI based application under windows, user actions such as pressing a
key, moving the mouse, selecting a menu item are first identified by the
operating system for each action, the operating system determines for which
program the action has been taken and passes.

• Ex. If user click a mouse button, operating systems registers this and
determines the position of the cursor. It than finds which application controls
the window and where the cursor was when you pressed the button and
communicates with signal to that program.

• The signal that program receives from the operating system as a result of
actions are called events.

• A program contains methods that handles the events. Such program is called
an event-driven program.

Java Method
User Operating
Library
System Method
Action Classes
Method
Following are important classes that represents events
• WindowEvent : Window is activated, closed, deactivated, iconified,
opened ect.

• MouseEvent : Mouse is moved, clicked, released, dragged, enters


or exists component.

• MouseWheelEvent : Mouse wheel is moved.

• KeyEvent : input is received from keyboard.

• ItemEvent : A checkbox or list item or menu – item is selected.

• TextEvent : Text area or text field content is changed.

• AdjustmentEvent : A scroll bar is manipulated.

• FocusEvent : A component grains or loses keyboard focus.


Listeners are created by implementing Listener interfaces define
in package java.awt.event.
• WindowListener :
–void windowActivated (WindowEvent e)
–This window is either the focused window, or owns the focused
window.
–void windowDeactivated (WindowEvent e)
–This window has lost the focus. For more information about focus,
see the AWT Focus Subsystem specification.
–void windowOpened (WindowEvent e)
–Showing a window for the first time.
–void windowClosed (WindowEvent e)
–Removing the window from the screen.
–void windowIconified (WindowEvent e)
–Reducing the window to an icon on the desktop.
–void windowDeiconified (WindowEvent e)
–Restoring the window to its original size.
• MouseListener :
–void mouseClicked (MouseEvent e) :
Mouse is pressed or released at same point
–void mouseEntered (MouseEvent e)
Mouse enters a component
–void mouseExited (MouseEvent e)
Mouse leaves a component
–void mousePressed (MouseEvent e)
Mouse button pressed
–void mouseReleased (MouseEvent e)
Mouse button released
• MouseMotionListener :
–void mouseDragged (MouseEvent e) : Mouse is dragged

–void mouseMoved (MouseEvent e) : Mouse is simply moved

• MouseWheelListener :
void mouseWheelMoved (MouseWheelEvent e) : Mouse wheel is
moved

• KeyListener :
–void keyTyped (KeyEvent e) : when user presses a visible character key

–void keyPressed (KeyEvent e) : User presses any key

–void keyReleased (KeyEvent e) : User releases any key pressed


• ActionListener :
–void actionPerformed (ActionEvent e) : when action event occurs

• ItemListener :
–void itemStateChange (ItemEvent e) : when state of the item change
that is checked or unchecked checkbox , menu check item etc.

• TextListener :
–void textChanged (TextEvent e) : when state of the item change that is
checked or unchecked checkbox , menu check item etc.
• AdjustmentListener :
–void adjustmentValueChanged (AdjusmentEvent e) : when a scrollbar is
manipulated

• FocusListener :
–void focusGained (FocusEvent e) :
–void focusLost (FocusEvent e) :

You might also like